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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,356,249 | Getting started with Core Data | <p>I am having trouble understanding how Core Data works conceptually and in terms of code.</p>
<p>I get that there is a coordinator and a context. I also get that there is state management. How do they work together?</p>
<p>I don't understand how I can store, say, an image and a few strings as an object.</p>
<p>Let's say I want to retrieve the image and the strings later. What do I do? </p>
<p>Where do I save my state? How?</p>
<p>What does my code look like? I would really appreciate a bare-bones code sample here, because I'm really confused.</p> | 3,357,490 | 3 | 0 | null | 2010-07-28 18:41:47.663 UTC | 15 | 2012-09-04 21:09:48.927 UTC | null | null | null | null | 224,988 | null | 1 | 11 | iphone|core-data|ios|concept | 2,005 | <p>These are some of the best tutorials I've found:</p>
<ul>
<li><a href="http://www.raywenderlich.com/934/core-data-tutorial-getting-started" rel="nofollow noreferrer">Best tutorial I've found</a></li>
<li><a href="http://iphoneinaction.manning.com/iphone_in_action/2009/08/core-data-part-1-an-introduction.html" rel="nofollow noreferrer">Another good, multipage tutorial</a></li>
<li><a href="http://cocoadevcentral.com/articles/000086.php" rel="nofollow noreferrer">Very good explaination of concepts</a></li>
<li><a href="http://developer.apple.com/macosx/coredata.html" rel="nofollow noreferrer">Apple Doc, might help with the concepts</a></li>
<li><a href="http://borkware.com/quickies/one?topic=Core%20Data" rel="nofollow noreferrer">Little Cheatsheet</a></li>
</ul>
<p>As for your quesstions:</p>
<blockquote>
<p>I get that there is a coordinator and
a context. I also get that there is
state management. How do they work
together?</p>
</blockquote>
<p>The persistent store coordinator is what manages the place your data is actually being stored, be that a SQLlite DB or a XML file or whatever. The coordinator is the abstraction so you don't have to worry about what type of storage is in the backend.</p>
<p>The Managed Object Context is how you interact with the Persistent Store Coordinator. Think of it as your scratch pad. You create and modify Managed Objects from the Managed Object Context.</p>
<blockquote>
<p>I don't understand how I can store, say, an image and a few strings as an object.
Let's say I want to retrieve the image and the strings later. What do I do?</p>
</blockquote>
<p>If you look through some of the above tutorials, you'll see how to pull objects out of the managed object context. A NSString would simply be stored as a string attribute on a managed object, like so:</p>
<pre><code>[managedObject setValue:@"TestString" forKey:@"SomeStringProperty"];
</code></pre>
<p>I'm not quite sure about images as I've never stored an image in Core Data before. I know anything that can be serialized can be stored as a transformable attribute. <a href="http://www.iphonedevsdk.com/forum/iphone-sdk-development/42457-save-image-core-data.html" rel="nofollow noreferrer">Here's a post about storing UIImages in Core Data</a></p>
<blockquote>
<p>Where do I save my state? How?</p>
</blockquote>
<p>You simply call the 'save' method on your managed object context. Like so:</p>
<pre><code>[context save:&error]
</code></pre> |
8,918,401 | Does a multiple producer single consumer lock-free queue exist for c++? | <p>The more I read the more confused I become... I would have thought it trivial to find a formally correct MPSC queue implemented in C++.</p>
<p>Every time I find another stab at it, further research seems to suggest there are issues such as ABA or other subtle race conditions.</p>
<p>Many talk of the need for garbage collection. This is something I want to avoid.</p>
<p>Is there an accepted correct open-source implementation out there?</p> | 8,933,885 | 4 | 11 | null | 2012-01-18 22:23:24.497 UTC | 18 | 2021-09-21 06:05:29.547 UTC | 2021-09-21 06:05:29.547 UTC | null | 10,358,768 | null | 955,273 | null | 1 | 29 | c++|synchronization|lock-free | 34,713 | <p>You may want to check disruptor; it's available in C++ here: <a href="http://lmax-exchange.github.io/disruptor/" rel="nofollow noreferrer">http://lmax-exchange.github.io/disruptor/</a> </p>
<p>You can also find explanation how it works <a href="https://stackoverflow.com/questions/6559308/how-does-lmaxs-disruptor-pattern-work">here on stackoverflow</a> Basically it's circular buffer with no locking, optimized for passing FIFO messages between threads in a fixed-size slots.</p>
<p>Here are two implementations which I found useful: <a href="http://natsys-lab.blogspot.ru/2013/05/lock-free-multi-producer-multi-consumer.html" rel="nofollow noreferrer">Lock-free Multi-producer Multi-consumer Queue on Ring Buffer @ NatSys Lab. Blog</a> and <a href="http://www.codeproject.com/Articles/153898/Yet-another-implementation-of-a-lock-free-circular?display=PrintAll" rel="nofollow noreferrer"><br>
Yet another implementation of a lock-free circular array queue
@ CodeProject</a></p>
<p><strong>NOTE: the code below is incorrect, I leave it only as an example how tricky these things can be.</strong></p>
<p>If you don't like the complexity of google version, here is something similar from me - it's much simpler, but I leave it as an exercise to the reader to make it work (it's part of larger project, not portable at the moment). The whole idea is to maintain cirtular buffer for data and a small set of counters to identify slots for writing/written and reading/read. Since each counter is in its own cache line, and (normally) each is only atomically updated once in the live of a message, they can all be read without any synchronisation. There is one potential contention point between writing threads in <code>post_done</code>, it's required for FIFO guarantee. Counters (head_, wrtn_, rdng_, tail_) were selected to ensure correctness <em>and</em> FIFO, so dropping FIFO would also require change of counters (and that might be difficult to do without sacrifying correctness). It is possible to slightly improve performance for scenarios with one consumer, but I would not bother - you would have to undo it if other use cases with multiple readers are found.</p>
<p>On my machine latency looks like following (percentile on left, mean within this percentile on right, unit is microsecond, measured by rdtsc):</p>
<pre><code> total=1000000 samples, avg=0.24us
50%=0.214us, avg=0.093us
90%=0.23us, avg=0.151us
99%=0.322us, avg=0.159us
99.9%=15.566us, avg=0.173us
</code></pre>
<p>These results are for single polling consumer, i.e. worker thread calling wheel.read() in tight loop and checking if not empty (scroll to bottom for example). Waiting consumers (much lower CPU utilization) would wait on event (one of <code>acquire...</code> functions), this adds about 1-2us to average latency due to context switch. </p>
<p>Since there is verly little contention on read, consumers scale very well with number of worker threads, e.g. for 3 threads on my machine:</p>
<pre><code> total=1500000 samples, avg=0.07us
50%=0us, avg=0us
90%=0.155us, avg=0.016us
99%=0.361us, avg=0.038us
99.9%=8.723us, avg=0.044us
</code></pre>
<p>Patches will be welcome :)</p>
<pre><code>// Copyright (c) 2011-2012, Bronislaw (Bronek) Kozicki
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <core/api.hxx>
#include <core/wheel/exception.hxx>
#include <boost/noncopyable.hpp>
#include <boost/type_traits.hpp>
#include <boost/lexical_cast.hpp>
#include <typeinfo>
namespace core { namespace wheel
{
struct bad_size : core::exception
{
template<typename T> explicit bad_size(const T&, size_t m)
: core::exception(std::string("Slot capacity exceeded, sizeof(")
+ typeid(T).name()
+ ") = "
+ boost::lexical_cast<std::string>(sizeof(T))
+ ", capacity = "
+ boost::lexical_cast<std::string>(m)
)
{}
};
// inspired by Disruptor
template <typename Header>
class wheel : boost::noncopyable
{
__declspec(align(64))
struct slot_detail
{
// slot write: (memory barrier in wheel) > post_done > (memory barrier in wheel)
// slot read: (memory barrier in wheel) > read_done > (memory barrier in wheel)
// done writing or reading, must update wrtn_ or tail_ in wheel, as appropriate
template <bool Writing>
void done(wheel* w)
{
if (Writing)
w->post_done(sequence);
else
w->read_done();
}
// cache line for sequence number and header
long long sequence;
Header header;
// there is no such thing as data type with variable size, but we need it to avoid thrashing
// cache - so we invent one. The memory is reserved in runtime and we simply go beyond last element.
// This is well into UB territory! Using template parameter for this is not good, since it
// results in this small implementation detail leaking to all possible user interfaces.
__declspec(align(8))
char data[8];
};
// use this as a storage space for slot_detail, to guarantee 64 byte alignment
_declspec(align(64))
struct slot_block { long long padding[8]; };
public:
// wrap slot data to outside world
template <bool Writable>
class slot
{
template<typename> friend class wheel;
slot& operator=(const slot&); // moveable but non-assignable
// may only be constructed by wheel
slot(slot_detail* impl, wheel<Header>* w, size_t c)
: slot_(impl) , wheel_(w) , capacity_(c)
{}
public:
slot(slot&& s)
: slot_(s.slot_) , wheel_(s.wheel_) , capacity_(s.capacity_)
{
s.slot_ = NULL;
}
~slot()
{
if (slot_)
{
slot_->done<Writable>(wheel_);
}
}
// slot accessors - use Header to store information on what type is actually stored in data
bool empty() const { return !slot_; }
long long sequence() const { return slot_->sequence; }
Header& header() { return slot_->header; }
char* data() { return slot_->data; }
template <typename T> T& cast()
{
static_assert(boost::is_pod<T>::value, "Data type must be POD");
if (sizeof(T) > capacity_)
throw bad_size(T(), capacity_);
if (empty())
throw no_data();
return *((T*) data());
}
private:
slot_detail* slot_;
wheel<Header>* wheel_;
const size_t capacity_;
};
private:
// dynamic size of slot, with extra capacity, expressed in 64 byte blocks
static size_t sizeof_slot(size_t s)
{
size_t m = sizeof(slot_detail);
// add capacity less 8 bytes already within sizeof(slot_detail)
m += max(8, s) - 8;
// round up to 64 bytes, i.e. alignment of slot_detail
size_t r = m & ~(unsigned int)63;
if (r < m)
r += 64;
r /= 64;
return r;
}
// calculate actual slot capacity back from number of 64 byte blocks
static size_t slot_capacity(size_t s)
{
return s*64 - sizeof(slot_detail) + 8;
}
// round up to power of 2
static size_t round_size(size_t s)
{
// enfore minimum size
if (s <= min_size)
return min_size;
// find rounded value
--s;
size_t r = 1;
while (s)
{
s >>= 1;
r <<= 1;
};
return r;
}
slot_detail& at(long long sequence)
{
// find index from sequence number and return slot at found index of the wheel
return *((slot_detail*) &wheel_[(sequence & (size_ - 1)) * blocks_]);
}
public:
wheel(size_t capacity, size_t size)
: head_(0) , wrtn_(0) , rdng_(0) , tail_(0) , event_()
, blocks_(sizeof_slot(capacity)) , capacity_(slot_capacity(blocks_)) , size_(round_size(size))
{
static_assert(boost::is_pod<Header>::value, "Header type must be POD");
static_assert(sizeof(slot_block) == 64, "This was unexpected");
wheel_ = new slot_block[size_ * blocks_];
// all slots must be initialised to 0
memset(wheel_, 0, size_ * 64 * blocks_);
active_ = 1;
}
~wheel()
{
stop();
delete[] wheel_;
}
// all accessors needed
size_t capacity() const { return capacity_; } // capacity of a single slot
size_t size() const { return size_; } // number of slots available
size_t queue() const { return (size_t)head_ - (size_t)tail_; }
bool active() const { return active_ == 1; }
// enough to call it just once, to fine tune slot capacity
template <typename T>
void check() const
{
static_assert(boost::is_pod<T>::value, "Data type must be POD");
if (sizeof(T) > capacity_)
throw bad_size(T(), capacity_);
}
// stop the wheel - safe to execute many times
size_t stop()
{
InterlockedExchange(&active_, 0);
// must wait for current read to complete
while (rdng_ != tail_)
Sleep(10);
return size_t(head_ - tail_);
}
// return first available slot for write
slot<true> post()
{
if (!active_)
throw stopped();
// the only memory barrier on head seq. number we need, if not overflowing
long long h = InterlockedIncrement64(&head_);
while(h - (long long) size_ > tail_)
{
if (InterlockedDecrement64(&head_) == h - 1)
throw overflowing();
// protection against case of race condition when we are overflowing
// and two or more threads try to post and two or more messages are read,
// all at the same time. If this happens we must re-try, otherwise we
// could have skipped a sequence number - causing infinite wait in post_done
Sleep(0);
h = InterlockedIncrement64(&head_);
}
slot_detail& r = at(h);
r.sequence = h;
// wrap in writeable slot
return slot<true>(&r, this, capacity_);
}
// return first available slot for write, nothrow variant
slot<true> post(std::nothrow_t)
{
if (!active_)
return slot<true>(NULL, this, capacity_);
// the only memory barrier on head seq. number we need, if not overflowing
long long h = InterlockedIncrement64(&head_);
while(h - (long long) size_ > tail_)
{
if (InterlockedDecrement64(&head_) == h - 1)
return slot<true>(NULL, this, capacity_);
// must retry if race condition described above
Sleep(0);
h = InterlockedIncrement64(&head_);
}
slot_detail& r = at(h);
r.sequence = h;
// wrap in writeable slot
return slot<true>(&r, this, capacity_);
}
// read first available slot for read
slot<false> read()
{
slot_detail* r = NULL;
// compare rdng_ and wrtn_ early to avoid unnecessary memory barrier
if (active_ && rdng_ < wrtn_)
{
// the only memory barrier on reading seq. number we need
const long long h = InterlockedIncrement64(&rdng_);
// check if this slot has been written, step back if not
if (h > wrtn_)
InterlockedDecrement64(&rdng_);
else
r = &at(h);
}
// wrap in readable slot
return slot<false>(r , this, capacity_);
}
// waiting for new post, to be used by non-polling clients
void acquire()
{
event_.acquire();
}
bool try_acquire()
{
return event_.try_acquire();
}
bool try_acquire(unsigned long timeout)
{
return event_.try_acquire(timeout);
}
void release()
{}
private:
void post_done(long long sequence)
{
const long long t = sequence - 1;
// the only memory barrier on written seq. number we need
while(InterlockedCompareExchange64(&wrtn_, sequence, t) != t)
Sleep(0);
// this is outside of critical path for polling clients
event_.set();
}
void read_done()
{
// the only memory barrier on tail seq. number we need
InterlockedIncrement64(&tail_);
}
// each in its own cache line
// head_ - wrtn_ = no. of messages being written at this moment
// rdng_ - tail_ = no. of messages being read at the moment
// head_ - tail_ = no. of messages to read (including those being written and read)
// wrtn_ - rdng_ = no. of messages to read (excluding those being written or read)
__declspec(align(64)) volatile long long head_; // currently writing or written
__declspec(align(64)) volatile long long wrtn_; // written
__declspec(align(64)) volatile long long rdng_; // currently reading or read
__declspec(align(64)) volatile long long tail_; // read
__declspec(align(64)) volatile long active_; // flag switched to 0 when stopped
__declspec(align(64))
api::event event_; // set when new message is posted
const size_t blocks_; // number of 64-byte blocks in a single slot_detail
const size_t capacity_; // capacity of data() section per single slot. Initialisation depends on blocks_
const size_t size_; // number of slots available, always power of 2
slot_block* wheel_;
};
}}
</code></pre>
<p>Here is what polling consumer worker thread may look like:</p>
<pre><code> while (wheel.active())
{
core::wheel::wheel<int>::slot<false> slot = wheel.read();
if (!slot.empty())
{
Data& d = slot.cast<Data>();
// do work
}
// uncomment below for waiting consumer, saving CPU cycles
// else
// wheel.try_acquire(10);
}
</code></pre>
<p><strong>Edited</strong> added consumer example</p> |
22,201,620 | How to reduce Spring memory footprint | <p>I would like to ask you HOW (or IF) is possible to reduce Spring framework's RAM footprint.</p>
<p>I created a simple helloworld app for demonstrating the issue. There are only two classes and context.xml file:</p>
<ul>
<li><code>Main</code> - class with main method</li>
<li><code>Test</code> - class used for simulating some "work" (printig Hello in endless loop)</li>
</ul>
<p><code>context.xml</code> contains only this:</p>
<pre><code><context:component-scan base-package="mypackage" />
</code></pre>
<p>Test class contains only metod called <code>init</code>, called after construction:</p>
<pre><code>@Component
public class Test{
@PostConstruct
public void init() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
System.out.println("Hello " + Thread.currentThread().getName());
Thread.sleep(500);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
});
t.start();
}
}
</code></pre>
<p>I prepared two scenarios and in both of them <code>main</code> method contains only one line.</p>
<p>In first scenario main method does this: <code>(new Test()).init();</code>
App works without Spring and consumes only aprox. 8MB of RAM.</p>
<p>In second scenario main method contains following: <code>new ClassPathXmlApplicationContext(new String[]{"spring/context.xml"});</code>
So the app is initialized throug Spring container and consumes aprox. 45MB of RAM !</p>
<p>Is there any way how to reduce (in best case completely get rid of) this extra memory ? So far I wasn't able to find any fitting solution.</p>
<p>I don't mind if there is the extra memory consumption on startup - this is perfectly fine, but after that, I need our app to reduce it.</p>
<p>(The story behind this question is a bit more complicated, but this is for me now the core problem.)</p>
<p>Thank you</p> | 22,203,200 | 1 | 6 | null | 2014-03-05 15:11:29.547 UTC | 11 | 2015-04-24 11:58:58.943 UTC | 2014-03-05 15:29:41.437 UTC | null | 1,346,207 | null | 1,081,036 | null | 1 | 12 | java|spring|ram | 19,370 | <p>First a few things which you may already know but are important to understand the situation: most of the memory your program uses is <em>the JVM heap</em>. The heap has an initial size when your program starts executing. Sometimes the JVM will ask the OS for more memory and increase the size of the heap. The JVM will also perform garbage collection, thus freeing space in the heap.</p>
<p><strong>When the used heap size diminishes, memory is not necessarily released by the JVM.</strong> The oracle JVM is reluctant to do so. For example if your program uses 500 MB of ram on startup, then after garbage collection only uses 100 MB for most of its execution, you cannot assume the additional 400 MB will be given back to your OS.</p>
<p>Furthermore, tools like the windows task manager (and I assume unix's <code>ps</code>) <strong>will display the size of all the memory that is allocated to the JVM, regardless of whether this memory is actually used or not</strong>. Tools like <a href="https://visualvm.java.net/">jvisualvm</a> will let you see exactly how the memory is used in your java program, and in particular what amount of heap you're actually using vs. how much is allocated.</p>
<hr>
<p>With this in mind I tested your program in the following scenarios. Note that this depends on many factors including which JVM you use, its version, and probably your OS too. </p>
<ul>
<li>Standard java (SE) vs Spring. </li>
<li>Garbage collection (GC) vs none (NOGC) (I called the garbage collector from jvisualvm). </li>
<li>Minimum heap size defined for the JVM (using -Xmx8M). This tells the JVM to only allocate 8MB on startup. The default on my system is 256MB.</li>
</ul>
<p>For each case I report the allocated heap size and used heap size. Here are my results:</p>
<ul>
<li>SE, NOGC, 256M : 270 MB allocated, 30 MB used</li>
<li>Spring, NOGC, 256M : 270 MB allocated, 30 MB used</li>
</ul>
<p>These results are identical, so from your question I assume you already had a different environment than I did.</p>
<ul>
<li>SE, GC, 256M : 270 MB allocated, 9 MB used </li>
</ul>
<p>Using the GC reduces heap usage, but we still have the same allocated memory</p>
<ul>
<li>SE, NOGC, 8M : 9 MB allocated, <5 MB used</li>
<li>Spring, NOGC, 8M : 20 MB allocated, <5 MB used</li>
</ul>
<p>This is the most important result: more memory is allocated because Spring probably needs more at some point during startup. </p>
<p><strong>Conclusions:</strong></p>
<ul>
<li>If you're trying to reduce heap usage, using spring should not be much of a problem. The overhead is not gigantic.</li>
<li>If you're trying to reduce allocated memory, the price of using Spring, in this experiment, is steeper. But you can still configure your JVM so that it will free memory more often than the default. I don't know much about this, but jvm options such as <code>-XX:MaxHeapFreeRatio=70</code> might be a start (more here <a href="http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html#PerformanceTuning">http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html#PerformanceTuning</a> )</li>
</ul> |
11,195,569 | showing label and input in same line using css | <p>I have a html mark up with label and inputbox. However, for business reasons, I need to show the label and inputbox on sameline and hide the placeholdertext. The end result should look like the placeholder text is staying there. Example is here: <a href="http://jsfiddle.net/XhwJU/">http://jsfiddle.net/XhwJU/</a></p>
<p>Here is the markup for reference:</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test Page</title>
</head>
<body>
<h1> test </h1>
<div class="inputdata">
<label for="AccessCode"> Access Code: </label>
<div style="display:inline"> <input type="text" name="accessCode" id="AccessCode" value="" placeholder="" /> </div>
<div class="clear"></div>
</div>
</body>
</html>
</code></pre>
<p> </p>
<p>Here is the styles used:</p>
<pre><code>.inputdata {
border: thin solid gray;
padding: 0.1em;
margin: 0.1em;
vertical-align: middle;
}
div .inputdata label {
width:auto;
float:left;
color: gray;
line-height: 2;
padding-top: .4em;
}
input[type='text']{
overflow:hidden;
line-height: 2;
box-shadow: none;
border:none;
vertical-align: middle;
background:none;
width:100%;
}
.clear {
clear: both;
height: 1px;
overflow: hidden;
font-size:0pt;
margin-top: -1px;
}
</code></pre>
<p>As you can see in the jsfiddle, label and input show in separate lines. I want the label and input to show up on same line irrespective of the screenwidth. Label shall have a fixed size that allows it to fit contents in one line and the input shall occupy the rest of the screen width. </p>
<p>appreciate any help</p> | 11,198,424 | 1 | 9 | null | 2012-06-25 18:58:32.767 UTC | 3 | 2015-04-05 05:29:11.233 UTC | 2012-06-25 20:02:09.72 UTC | null | 322,933 | null | 322,933 | null | 1 | 7 | css|html|inline | 45,152 | <p>I've done some changes in your CSS and i think i got what you want, <a href="http://jsfiddle.net/masimao/zU9Xv/" rel="nofollow noreferrer">here is an example</a> and below HTML and CSS.</p>
<p><strong>CSS</strong></p>
<pre><code>div.inputdata{
border:thin solid gray;
padding:0.1em;
margin:0.1em;
}
div.inputdata label{
float:left;
margin-right:10px;
padding:5px 0;
color:gray;
}
div.inputdata span{
display: block;
overflow: hidden;
}
div.inputdata input{
width:100%;
padding-top:8px;
border:none;
background:none;
}
.clear {
clear: both;
}
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><h1>test</h1>
<div class="inputdata">
<label for="AccessCode"> Access Code: </label>
<span><input type="text" name="accessCode" id="AccessCode" value="" placeholder="" /></span>
<div class="clear"></div>
</div>
</code></pre>
<p>To understand better the reason of <code>overflow:hidden</code> in <code>span</code> you can read this: <a href="http://colinaarts.com/articles/the-magic-of-overflow-hidden/" rel="nofollow noreferrer">The magic of "overflow:hidden"</a></p> |
11,303,891 | How to have dynamic image as CSS background? | <p>I have a logo div that I want to use my logo image as the background for, such as:</p>
<pre><code>.logo {
background: #FFF url(images/logo.jpg);
}
</code></pre>
<p>However, on a settings page in my script, I would like to have a text input field to specify what the image URL is for the background image.</p>
<p>How can I set the background image for this div as the inputted image URL without having to do:</p>
<pre><code><div><img src="/images/logo.jpg" /></div>
</code></pre>
<p>(The script is written in PHP)</p> | 11,304,151 | 4 | 2 | null | 2012-07-03 02:56:56.99 UTC | 7 | 2018-08-21 20:28:15.063 UTC | null | null | null | null | 1,279,133 | null | 1 | 13 | php|css|background | 101,846 | <p>Here are two options to dynamically set a background image.</p>
<ol>
<li><p>Put an embedded stylesheet in the document's <code><head></code>:</p>
<pre><code><style type="text/css">
.logo {
background: #FFF url(<?php echo $variable_holding_img_url; ?>);
}
</style>
</code></pre></li>
<li><p>Define the <code>background-image</code> CSS property inline:</p>
<pre><code><div style="background-image: url(<?php echo $varable_holding_img_url; ?>);">...</div>
</code></pre></li>
</ol>
<p><strong>Note:</strong> Make sure to sanitize your input, before saving it to the database (see <a href="http://bobby-tables.com" rel="nofollow noreferrer">Bobby Tables</a>). Make sure it <em>does not contain HTML or anything else, only valid URL characters</em>, escape quotes, etc. If this isn't done, an attacker could inject code into the page:</p>
<pre><code>"> <script src="http://example.com/xss-attack.js"></script> <!--
</code></pre> |
11,046,684 | PHP file-upload using jquery post | <p>Let me know if anyone know what is the issue with this code. </p>
<p>Basically i want to upload a file using jQuery</p>
<pre><code><html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').submit(function(event) {
event.preventDefault();
$.post('post.php',function(data){
$('#result').html(data);
});
});
});
</script>
</head>
<body>
<form id="form1">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
</code></pre>
<p>and my php 'post.php'</p>
<pre><code><?php
echo $file['tmp_name'];
?>
</code></pre>
<p>Uploaded File name is not returned back. Issue is i couldn't access the uploaded file.</p>
<p>Thanks in advance!
Shiv</p> | 11,046,724 | 6 | 0 | null | 2012-06-15 07:53:10.34 UTC | 6 | 2015-10-14 11:28:11.56 UTC | null | null | null | null | 1,197,461 | null | 1 | 16 | php|jquery|file-upload | 46,124 | <blockquote>
<p>Basically i want to upload a file using jQuery</p>
</blockquote>
<p>You cannot upload files using AJAX. You could use the <a href="http://jquery.malsup.com/form/">jquery.form</a> plugin which uses a hidden iframe:</p>
<pre><code><html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').ajaxForm(function(data) {
$('#result').html(data);
});
});
</script>
</head>
<body>
<form id="form1" action="post.php" method="post" enctype="multipart/form-data">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
</code></pre>
<p>Also notice the <code>enctype="multipart/form-data"</code> on the form.</p>
<p>Another possibility is to use the <a href="https://developer.mozilla.org/en/Using_files_from_web_applications">HTML5 File API</a> which allows you to achieve that assuming the client browser supports it.</p> |
11,192,190 | Set border around UIImageView | <p>I want to apply two types of border on a <code>UIImageView</code>:</p>
<ol>
<li>One is the border on the <code>layer</code> of the <code>UIImageView</code>.</li>
<li>Second is the border around the <code>layer</code> of the <code>UIImageView</code>.</li>
</ol>
<p>How can I do this?</p> | 11,194,947 | 4 | 0 | null | 2012-06-25 15:20:38.703 UTC | 9 | 2020-10-16 10:14:29.357 UTC | 2012-06-25 15:23:10.03 UTC | null | 483,349 | null | 1,355,704 | null | 1 | 17 | iphone|objective-c|ios|xcode | 28,235 | <p>Try </p>
<pre><code>#define kBorderWidth 3.0
#define kCornerRadius 8.0
CALayer *borderLayer = [CALayer layer];
CGRect borderFrame = CGRectMake(0, 0, (imageView.frame.size.width), (imageView.frame.size.height));
[borderLayer setBackgroundColor:[[UIColor clearColor] CGColor]];
[borderLayer setFrame:borderFrame];
[borderLayer setCornerRadius:kCornerRadius];
[borderLayer setBorderWidth:kBorderWidth];
[borderLayer setBorderColor:[[UIColor redColor] CGColor]];
[imageView.layer addSublayer:borderLayer];
</code></pre>
<p>And don't forget to import QuartzCore/QuartzCore.h</p>
<p>This example will draw a boarder on the layer, but change it's frame slightly to make the border around the layer.</p> |
11,320,108 | What does the message "Invalid byte 2 of a 3-byte UTF-8 sequence" mean? | <p>I changed a file in Orbeon Forms, and the next time I load the page, I get an error message saying <em>Invalid byte 2 of a 3-byte UTF-8 sequence</em>. How can I solve this problem?</p> | 11,320,109 | 9 | 0 | null | 2012-07-03 22:28:59.24 UTC | 2 | 2020-04-07 07:04:00.96 UTC | null | null | null | null | 5,295 | null | 1 | 18 | encoding|utf-8|orbeon | 83,837 | <p>This happens when Orbeon Forms reads an XML file and expects it to use the UTF-8 encoding, but somehow the file isn't properly encoded in UTF-8. To solve this, make sure that:</p>
<ol>
<li><p>You have an XML declaration at the beginning of the file saying the file is in UTF-8:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
</code></pre></li>
<li><p>Your editor is XML-aware, so it can parse the XML declaration and consequently use the UTF-8 encoding. If your editor isn't XML aware, and you don't want to use another editor, look for an option or preference allowing you to specify that the editor must use UTF-8.</p></li>
</ol> |
11,094,600 | How to trim StringBuilder's string? | <p>How can we trim a <code>StringBuilder</code> value without the overhead caused by using <code>StringBuilder.toString().trim()</code> and thereby creating a new <code>String</code> and/or a new <code>StringBuilder</code> instance for each trim call?</p> | 11,094,721 | 5 | 6 | null | 2012-06-19 04:56:56.16 UTC | 1 | 2018-08-07 22:45:24.837 UTC | 2018-02-07 21:00:29.553 UTC | null | 4,851,565 | null | 1,414,799 | null | 1 | 36 | java|c# | 43,157 | <blockquote>
<p>Why does StringBuilder don't have trim() method </p>
</blockquote>
<ol>
<li>Because that's the way it was designed. Try asking the designers<sup>1</sup>.</li>
<li>Because there is not much call for it.</li>
<li>Because the String <code>trim()</code> semantics and signature is a poor fit for mutable strings, though that is debatable.</li>
</ol>
<p>Either way, the answer is not relevant to solving your problem.</p>
<blockquote>
<p>and how can we trim a StringBuilder value?</p>
</blockquote>
<p>The simplest way is to use <code>StringBuilder.toString().trim()</code> ...</p>
<blockquote>
<p>I don't want to use StringBuilder.toString().trim().</p>
</blockquote>
<p>In that case, so you need to do what <code>trim()</code> does under the covers: match and remove the leading and trailing white-space. Since the <code>StringBuilder</code> API has no regex support, you'll need to do this that hard way; i.e. by iterating the characters from the front forward and end backward to see what characters need to be removed, etcetera.</p>
<p>Are you sure you wouldn't prefer to do it the easy way? If not, this Q&A has some example implementations, analysis, benchmarking, etcetera:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/5212928/how-to-trim-a-java-stringbuilder">How to trim a java stringbuilder?</a></li>
</ul>
<p>Finally, you could implement your own variation of the <code>StringBuilder</code> class that does have a <code>trim()</code> method. You could possibly use a different internal representation so that operations that remove characters at the start don't copy characters. (I would not recommend this ... but it is an option if you have a pragmatically strong need for <code>trim()</code>.)</p>
<hr>
<blockquote>
<p>Actually i am in a loop where i have to compare this <code>StringBuilder</code> string with many other values so if i call <code>StringBuilder.toString().trim()</code> each time, it will create a new instance and i don't want to create a new String object each time.</p>
</blockquote>
<p>The flip-side is that removing characters from the start of a <code>StringBuilder</code> entails copying all of the remaining characters.</p>
<p>Maybe you would be better off turning the complete <code>StringBuilder</code> into a <code>String</code> to start with, then when you use <code>trim()</code> and <code>substring()</code> and the like, you won't be copying characters<sup>2</sup>. </p>
<hr>
<p><sup>1 - To the people who claim it is "not constructive" to say this, the alternative is to pretend that we <em>were</em> in the room when the design decisions were made and we <em>did</em> hear the debate that occurred. But that would be a lie. Frankly, it <em>is</em> constructive to point out that nobody here knows the answer, and not pretend otherwise. Why? Because a lot of readers will not be aware that the Java design processes at that time were opaque.</sup></p>
<p><sup>2 - Prior to Java 7, these methods work by creating a new String that <em>shares</em> the backing array of the original <code>String</code> ... so you only end up copying the string's control information. In Java 7 they changed the implementation of <code>trim</code> and <code>substring</code> so that they used a String constructor that copies a subarray of the backing array.</sup></p> |
10,988,569 | Storage limits on Chrome browser | <p>What is the soft limit (at which the user needs to give permission to exceed)?
What is the hard limit (maximum allowed).</p> | 11,006,368 | 6 | 2 | null | 2012-06-11 22:57:30.603 UTC | 18 | 2020-05-27 18:09:18.567 UTC | 2018-09-14 22:45:26.617 UTC | null | 3,345,644 | null | 4,906 | null | 1 | 39 | indexeddb | 63,152 | <p><strong>Warning - this information is outdated</strong> - see the <a href="https://stackoverflow.com/a/11077695/1276639">other answer</a> below.</p>
<p>Chrome has a 5mb soft limit before it hits a <a href="https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException" rel="nofollow noreferrer"><code>QUOTA_ERR</code></a>. <a href="https://developer.mozilla.org/en/IndexedDB#Storage_limits" rel="nofollow noreferrer">Here's a MDN reference</a> to that fact.</p>
<p>The <a href="http://www.w3.org/TR/IndexedDB/" rel="nofollow noreferrer">spec</a> mentions a <code>QuotaExceededError</code> but doesn't seem to say anything about when it should be thrown.</p>
<blockquote>
<p><strong>QuotaExceededError</strong> The operation failed because there was not enough
remaining storage space, or the storage quota was reached and the user
declined to give more space to the database.</p>
</blockquote>
<p>I've not heard of a hard limit and not reached one in my own development. Performance should go pretty far south before you reach it.</p> |
11,108,743 | Why does C++ mandate that complex only be instantiated for float, double, or long double? | <p>According to the C++ ISO spec, §26.2/2:</p>
<blockquote>
<p>The effect of instantiating the template <code>complex</code> for any type other than <code>float</code>, <code>double</code> or <code>long double</code> is unspecified.</p>
</blockquote>
<p>Why would the standard authors explicitly add this restriction? This makes it unspecified, for example, what happens if you make <code>complex<int></code> or a <code>complex<MyCustomFixedPointType></code> and seems like an artificial restriction.</p>
<p>Is there a reason for this limitation? Is there a workaround if you want to instantiate <code>complex</code> with your own custom type?</p>
<p>I'm primarily asking this question because of <a href="https://stackoverflow.com/q/11108587/501557">this earlier question</a>, in which the OP was confused as to why <code>abs</code> was giving bizarre outputs for <code>complex<int></code>. That said, this still doesn't quite make sense given that we also might want to make <code>complex</code> numbers out of fixed-points types, higher-precision real numbers, etc.</p> | 11,108,874 | 2 | 9 | null | 2012-06-19 20:18:30.627 UTC | 4 | 2012-09-05 14:10:28.923 UTC | 2017-05-23 11:53:49.533 UTC | null | -1 | null | 501,557 | null | 1 | 41 | c++|math|language-design|complex-numbers | 2,537 | <p>You can't properly implement many of the <code>std::complex</code> operations on integers. E.g.,</p>
<pre><code>template <class T>
T abs(const complex<T> &z);
</code></pre>
<p>for a <code>complex<long></code> cannot have <code>T = long</code> return value when complex numbers are represented as (real,imag) pairs, since it returns the value of <code>sqrt(pow(z.real(), 2) + pow(z.imag(), 2))</code>. Only a few of the operations would make sense.</p>
<p>Even worse, the <a href="http://en.cppreference.com/w/cpp/numeric/complex/polar"><code>polar</code></a> named constructor cannot be made reliable without breaking the default constructor and vice versa. The standard would have to specify that "complex integers" are <a href="https://en.wikipedia.org/wiki/Gaussian_integer">Gaussian integers</a> for them to be of any use, and that one of the constructors is severely broken.</p>
<p>Finally, how would you like your "complex integer division" served, and would you like a "complex remainder" with that? :)</p>
<p>Summarizing, I think it would be more sensible to specify a separate <code>gaussian_int<T></code> type with just a few operations than graft support for integral <code>T</code> onto <code>std::complex</code>.</p> |
11,254,491 | how do i debug/breakpoint my django app using pycharm? | <p>I'm trying to work out how to run the debug stuff that pycharm seems to offer (well, it allows me to set breakpoints, anyway, so i'm assuming there's a nice gui for it)</p>
<p>I've concluded that i cannot use the ctrl-shift-r and then "runserver" command, and that instead i'd need to setup a "run configuration"? I made a "django server" one, but i don't know what values to put etc. When i run it, it tells me that some setting is wrong - i'm pretty sure it isn't, because the standard "runserver" command works fine.</p>
<p>And that's about all i concluded. If there is a nifty tutorial or steps to get it so i can </p>
<ol>
<li>put in a break point</li>
<li>go to the page that triggers that breakpoint and follow the code's inner working in pycharm</li>
</ol>
<p>i'd be thrilled!</p>
<p>cheers!</p>
<p>UPDATE: in case you're wondering, here is the error i got:</p>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File "manage.py", line 11, in
import settings</p>
<p>File "C:\development\PycharmProjects\dumpstown\settings.py", line 185, in
add_to_builtins('gravatar.templatetags.gravatar')</p>
<p>File "C:\development\python\lib\site-packages\django\template\base.py", line 1017, in add_to_builtins</p>
<p>builtins.append(import_library(module))</p>
<p>File "C:\development\python\lib\site-packages\django\template\base.py", line 963, in import_library</p>
<p>raise InvalidTemplateLibrary("ImportError raised loading %s: %s" % (taglib_module, e))</p>
<p>django.template.base.InvalidTemplateLibrary: ImportError raised loading gravatar.templatetags.gravatar: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.</p>
</blockquote>
<p>Where the application itself, on a "runserver" never has any issues.</p>
<p>UPDATE: as per my answer below, pycharm is broken for add_to_builtins.</p> | 11,299,516 | 4 | 0 | null | 2012-06-28 23:57:18.853 UTC | 9 | 2019-11-19 09:56:46.027 UTC | 2012-07-02 18:57:05.903 UTC | null | 1,061,426 | null | 1,061,426 | null | 1 | 48 | django|pycharm | 44,696 | <p>So i gave all the answers here a +1 for trying - but they're not the issue. Near as i can tell, the answer is that pycharm is broken. Which is a pain, but the solution is easy - </p>
<p>IF you <em>dont'</em> want to use the little green button at the top of pycharm, or use the pycharm debugging feature? then don't worry, you don't need to do anything. Continue using ctrl-shift-r and runserver (or whatever your shortcut to manage.py is)</p>
<p>IF you <em>do</em> want to use the little green "run" button, or if you want to use pycharm's debugging kit, then you <em>absolutely cannot</em> use the "add_to_builtins", at least in the settings.py file (I never put it anywhere else myself, pycharm might require it elsewhere?). <code>add_to_builtins</code> doesn't work in pycharm - it gets itself caught in a loop of grave consequences when you use the little green button or the debug button. Using ctrl-shift-r and runserver doesn't, curiously, have this problem.</p>
<p>The good news is that "add_to_builtins" isn't a must-have, just a nice-to-have. Just add the "{% load x %}" command to each template where you use x and you will be set.
Alternatively, save a hundred bucks and use some sort of free eclipse tool.</p> |
11,192,511 | Does LLDB have convenience variables ($var)? | <p>Does LLDB have <a href="http://sourceware.org/gdb/onlinedocs/gdb/Convenience-Vars.html" rel="nofollow noreferrer">convenience variables</a>? If so, how do I use them? If not, is there anything similar that I can use?</p>
<p>Reference: <a href="http://software.intel.com/sites/products/documentation/hpc/atom/application/debugger/commands143.html" rel="nofollow noreferrer">http://software.intel.com/sites/products/documentation/hpc/atom/application/debugger/commands143.html</a></p> | 14,806,339 | 4 | 1 | null | 2012-06-25 15:37:47.993 UTC | 16 | 2022-09-08 04:29:17.313 UTC | 2020-03-11 06:13:13.553 UTC | null | 5,007,059 | null | 56,149 | null | 1 | 48 | lldb | 14,274 | <p>I finally figured it out myself. Run <code>help expr</code> in LLDB and you will see:</p>
<blockquote>
<p>User defined variables:
You can define your own variables for convenience or to be used in subsequent expressions.
You define them the same way you would define variables in C. If the first character of
your user defined variable is a $, then the variable's value will be available in future
expressions, otherwise it will just be available in the current expression.</p>
</blockquote>
<p>So <code>expr int $foo = 5</code> is what I want.</p> |
10,999,990 | Get raw POST body in Python Flask regardless of Content-Type header | <p>Previously, I asked <a href="https://stackoverflow.com/q/10434599">How to get data received in Flask request</a> because <code>request.data</code> was empty. The answer explained that <code>request.data</code> is the raw post body, but will be empty if form data is parsed. How can I get the raw post body unconditionally?</p>
<pre><code>@app.route('/', methods=['POST'])
def parse_request():
data = request.data # empty in some cases
# always need raw data here, not parsed form data
</code></pre> | 23,898,949 | 4 | 0 | null | 2012-06-12 15:37:10.627 UTC | 48 | 2019-08-04 22:24:07.8 UTC | 2019-08-04 22:24:07.8 UTC | null | 400,617 | null | 762,886 | null | 1 | 155 | python|flask|werkzeug | 169,938 | <p>Use <a href="http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.BaseRequest.get_data" rel="noreferrer"><code>request.get_data()</code></a> to get the raw data, regardless of content type. The data is cached and you can subsequently access <code>request.data</code>, <code>request.json</code>, <code>request.form</code> at will.</p>
<p>If you access <code>request.data</code> first, it will call <code>get_data</code> with an argument to parse form data first. If the request has a form content type (<code>multipart/form-data</code>, <code>application/x-www-form-urlencoded</code>, or <code>application/x-url-encoded</code>) then the raw data will be consumed. <code>request.data</code> and <code>request.json</code> will appear empty in this case.</p> |
48,410,996 | Dynamically append component to div in Angular 5 | <p>I have this</p>
<p><a href="https://angular-dynamic-component-append.stackblitz.io/" rel="noreferrer">https://angular-dynamic-component-append.stackblitz.io/</a></p>
<p>I managed to dynamically append an element, but it doesn't get compiled.
I saw many tutorials like <a href="https://medium.com/front-end-hacking/dynamically-add-components-to-the-dom-with-angular-71b0cb535286" rel="noreferrer">this</a></p>
<p>But it's not really what I need. And often they use the hashtag notation to identify the container.</p>
<p>I need to append a component to any element which may have
my custom directive on it.</p>
<p>I'd also need to use the bind value of the directive to control a [hidden] attribute on the appended element.</p>
<p><strong>THE GOALS</strong></p>
<ol>
<li>Override behaviour of existing component:
<ul>
<li>adding an attribute to show/hide</li>
<li>adding a class to customize appearance</li>
</ul></li>
<li>Reduce html coding
<ul>
<li>No need to write the entire component <code><my-comp></mycomp></code></li>
<li>No need to know the class</li>
<li>Automatic behaviour if the class name is changed
<ol start="3">
<li>Changing the element on which the directive is applied</li>
</ol></li>
<li>The final goal will be to add a class to the contaner element</li>
</ul></li>
</ol>
<p><strong>Expected source</strong></p>
<pre><code><div [myDirective]="myBoolean">
<p>some content</p>
</div>
</code></pre>
<p><strong>Expected compiled</strong></p>
<pre><code><div [myDirective]="myBoolean" class="myDirectiveClass1">
<p>some content</p>
<someComponent [hidden]="myBoolean" class="myDirectiveClass2"></someComponent>
</div>
</code></pre>
<p>Is there a way to achieve this?</p>
<p>Thank you in advance</p> | 48,502,150 | 3 | 7 | null | 2018-01-23 21:19:43.967 UTC | 3 | 2021-05-22 18:57:53.437 UTC | 2019-05-16 09:26:48.72 UTC | null | 3,872,998 | null | 3,872,998 | null | 1 | 10 | angular|typescript|angular-directive|angular5 | 39,387 | <p>Here's the way I got it working</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>import {
Renderer2,
Directive,
Input,
ElementRef,
OnChanges,
ViewEncapsulation
} from "@angular/core";
import { MatSpinner } from "@angular/material";
@Directive({
selector: "[myDirective]"
})
export class MyDirective {
@Input()
set myDirective(newValue: boolean) {
console.info("myDirectiveBind", newValue);
if (!!this._$matCard) {
const method = newValue ? "removeClass" : "addClass";
this.renderer[method](this._$matCard, "ng-hide");
}
this._myDirective = newValue;
}
private _myDirective: boolean;
private _$matCard;
constructor(private targetEl: ElementRef, private renderer: Renderer2) {
this._$matCard = this.renderer.createElement('mat-card');
const matCardInner = this.renderer.createText('Dynamic card!');
this.renderer.addClass(this._$matCard, "mat-card");
this.renderer.appendChild(this._$matCard, matCardInner);
const container = this.targetEl.nativeElement;
this.renderer.appendChild(container, this._$matCard);
}
}
import {
Component,
ElementRef,
AfterViewInit,
ViewEncapsulation
} from '@angular/core';
@Component({
selector: 'card-overview-example',
templateUrl: 'card-overview-example.html',
styleUrls: ['card-overview-example.css']
})
export class CardOverviewExample {
hideMyDirective = !1;
constructor(private _elementRef: ElementRef) { }
getElementRef() {
return this._elementRef;
}
ngAfterViewInit() {
let element = this._elementRef.nativeElement;
let parent = element.parentNode;
element.parentNode.className += " pippo";
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ng-hide {
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><mat-card>Simple card</mat-card>
<div class="text-center">
<button (click)="hideMyDirective = !hideMyDirective">
Toggle show dynamic card
</button>
</div>
<br />
<span>hideMyDirective: {{hideMyDirective}}</span>
<hr />
<div class="myDiv" [myDirective]="hideMyDirective">
<ul>
<li>My content</li>
</ul>
</div></code></pre>
</div>
</div>
</p> |
12,653,500 | How to access a struct member inside a union in C? | <p>I have the following union:</p>
<pre><code>union employee
{
char key;
struct manager
{
short int age;
float shares;
short int level;
};
struct worker
{
short int age;
short int skill;
short int department;
};
} company[10];
</code></pre>
<p>How can I access a member of a structure which is inside the union <code>employee</code>?
I tried to access the <code>age</code> member of the <code>manager</code> structure this way:</p>
<p><code>company[i].manager.age</code></p>
<p>But I get <code>error C2039: 'manager' : is not a member of 'employee'</code>.</p> | 12,653,519 | 4 | 0 | null | 2012-09-29 14:21:34.44 UTC | 3 | 2021-09-26 04:55:43.117 UTC | null | null | null | null | 1,380,370 | null | 1 | 12 | c|unions|structure | 53,157 | <p>Add something after the tag declaration. Perhaps:</p>
<pre><code>struct manager
{
short int age;
float shares;
short int level;
} manager;
</code></pre>
<hr>
<p>Side note: you're not using the union right. The key, i.e. the field that tells you whether you are dealing with a manager or with a mere worker should be in an enclosing object, <strong>outside the union</strong>. Perhaps:</p>
<pre><code>struct employee {
char key;
union {
struct manager ...;
struct worker ...;
} u;
};
</code></pre>
<p>As <a href="https://stackoverflow.com/users/335858/dasblinkenlight">dasblinkenlight</a> notes, you could declare your manager / worker tags outside the union.</p> |
13,059,011 | Is there any python function/library for calculate binomial confidence intervals? | <p>I need to calculate binomial confidence intervals for large set of data within a script of python. Do you know any function or library of python that can do this?</p>
<p>Ideally I would like to have a function like this <a href="http://statpages.org/confint.html">http://statpages.org/confint.html</a> implemented on python.</p>
<p>Thanks for your time.</p> | 13,061,491 | 9 | 6 | null | 2012-10-24 22:48:20.52 UTC | 9 | 2022-07-20 03:57:17.63 UTC | null | null | null | null | 747,822 | null | 1 | 28 | python|statistics | 22,423 | <p>I would say that R (or another stats package) would probably serve you better if you have the option. That said, if you only need the binomial confidence interval you probably don't need an entire library. Here's the function in my most naive translation from javascript. </p>
<pre><code>def binP(N, p, x1, x2):
p = float(p)
q = p/(1-p)
k = 0.0
v = 1.0
s = 0.0
tot = 0.0
while(k<=N):
tot += v
if(k >= x1 and k <= x2):
s += v
if(tot > 10**30):
s = s/10**30
tot = tot/10**30
v = v/10**30
k += 1
v = v*q*(N+1-k)/k
return s/tot
def calcBin(vx, vN, vCL = 95):
'''
Calculate the exact confidence interval for a binomial proportion
Usage:
>>> calcBin(13,100)
(0.07107391357421874, 0.21204372406005856)
>>> calcBin(4,7)
(0.18405151367187494, 0.9010086059570312)
'''
vx = float(vx)
vN = float(vN)
#Set the confidence bounds
vTU = (100 - float(vCL))/2
vTL = vTU
vP = vx/vN
if(vx==0):
dl = 0.0
else:
v = vP/2
vsL = 0
vsH = vP
p = vTL/100
while((vsH-vsL) > 10**-5):
if(binP(vN, v, vx, vN) > p):
vsH = v
v = (vsL+v)/2
else:
vsL = v
v = (v+vsH)/2
dl = v
if(vx==vN):
ul = 1.0
else:
v = (1+vP)/2
vsL =vP
vsH = 1
p = vTU/100
while((vsH-vsL) > 10**-5):
if(binP(vN, v, 0, vx) < p):
vsH = v
v = (vsL+v)/2
else:
vsL = v
v = (v+vsH)/2
ul = v
return (dl, ul)
</code></pre> |
12,842,997 | How to copy a file along with directory structure/path using python? | <p>First thing I have to mention here, I'm new to python.</p>
<p>Now I have a file located in:</p>
<pre><code>a/long/long/path/to/file.py
</code></pre>
<p>I want to copy to my home directory with a new folder created:</p>
<pre><code>/home/myhome/new_folder
</code></pre>
<p>My expected result is:</p>
<pre><code>/home/myhome/new_folder/a/long/long/path/to/file.py
</code></pre>
<p>Is there any existing library to do that? If no, how can I achieve that?</p> | 12,843,464 | 2 | 4 | null | 2012-10-11 15:18:36.153 UTC | 9 | 2019-01-03 06:28:03.247 UTC | 2019-01-03 06:28:03.247 UTC | null | 5,499,118 | null | 898,931 | null | 1 | 63 | python|file|directory|copy | 167,977 | <p>To create all intermediate-level destination directories you could use <a href="http://docs.python.org/library/os#os.makedirs" rel="noreferrer"><code>os.makedirs()</code></a> before copying:</p>
<pre><code>import os
import shutil
srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'
assert not os.path.isabs(srcfile)
dstdir = os.path.join(dstroot, os.path.dirname(srcfile))
os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)
</code></pre> |
12,752,288 | Git merge doesn't use default merge message, opens editor with default message | <p>How can I force <code>git merge</code> to use the default merge message instead of loading my editor with said message?</p>
<p>I have no editor listed in <code>git config -l</code>, so I'm not sure why it opens an editor.</p> | 12,752,379 | 4 | 1 | null | 2012-10-05 18:48:02.473 UTC | 19 | 2021-07-28 18:40:28.98 UTC | 2014-03-19 18:40:50.337 UTC | null | 425,313 | null | 471,947 | null | 1 | 79 | git|git-merge | 19,225 | <p>Found the answer after some digging</p>
<p>EDIT: As per Mark's suggestion, this is the best way to do so: </p>
<pre><code>git config --global core.mergeoptions --no-edit
</code></pre> |
22,034,498 | How to change ruby version | <p>Ruby 1.8 and 1.9 are installed in my Ubuntu machine. I've just installed Ruby 2.0.0 from <code>ppa:brightbox/ruby-ng-experimental</code> to install a bundle which requires 2.0.0. Now all 1.8, 1.9 and 2.0 are installed though I can't tell bundle to use 2.0:</p>
<pre><code>$ bundle install
$ Your Ruby version is 1.9.3, but your Gemfile specified 2.0.0
</code></pre>
<p>RVM fails to change version:</p>
<pre><code>$ rvm 2.0
$ ruby-2.0.0-p451 is not installed.
$ To install do: 'rvm install ruby-2.0.0-p451'
</code></pre>
<p>RBENV also does not recognize 2.0:</p>
<pre><code>$ rbenv global 2.0.0-p451
$ rbenv: version `2.0.0-p451' not installed
</code></pre> | 23,628,288 | 2 | 13 | null | 2014-02-26 07:21:52.873 UTC | 7 | 2018-09-19 06:40:07.643 UTC | null | null | null | null | 275,221 | null | 1 | 21 | ruby | 86,216 | <p>There is lots of advise in the comments to your question, some of it is advanced-ish rbenv or rvm usage.</p>
<p>My advice: Decide on how to manage multiple rubies - either use your OS package manager (in your case the <code>apt-get</code>/PPA stuff) OR <a href="https://rvm.io" rel="noreferrer">rvm</a> OR <a href="http://rbenv.org/" rel="noreferrer">rbenv</a>.</p>
<p>For the OS package manager, there should be a way to call ruby with version explicitely (e.g. <code>/usr/bin/ruby1.9.3</code>), or research on and call <code>update-alternative</code>. As bundler comes with a gem, you might get the interpreters confused here.</p>
<p>For rvm, change ruby version with <code>rvm use 2.5.1</code> (once it is installed).</p>
<p>For rbenv I actually do not know but it should be trivial, too (and people are happy with it; it just happens that I tried rvm first and it worked like a charm, never evaluated rbenv).</p>
<p>I usually install one "system" ruby (apt-get install ruby1.9.3) and use rvm afterwards. You can still switch to the packaged "production" ruby with <code>rvm use system</code>.</p>
<p><strong>Update 2017: Most distros ship with a ruby version installed already, so you probably don't have to install it manually. Run <code>ruby -v</code> or <code>which ruby</code> to see if a ruby interpreter is already installed.</strong></p>
<p>In your case I would probably deinstall all system rubys (<code>apt-get purge ...</code>), remove the PPAs, remove your ~/.rvm and rbenv and start from scratch (install packaged stable ruby, then <a href="http://rvm.io" rel="noreferrer">rvm</a> and use rvm (r.g. <code>rvm install 2.3.1</code>) from there on).</p> |
16,718,257 | Retrieve drawable resource from Uri | <p>I'm storing the drawable resource path in an Uri in this way:</p>
<pre><code>Uri uri = Uri.parse("android.resource://my_app_package/drawable/drawable_name");
</code></pre>
<p>How do I get the Drawable that the uri is referencing?</p>
<p>I don't want to put it in an ImageView, just retrieve the Drawable (or Bitmap) object.</p> | 16,718,935 | 1 | 0 | null | 2013-05-23 15:40:10.493 UTC | 8 | 2016-07-26 15:02:00.723 UTC | 2016-03-21 20:29:48.627 UTC | null | 511,795 | null | 1,226,219 | null | 1 | 24 | android|uri|android-drawable | 31,256 | <p><code>getContentResolver cr object</code> then call: </p>
<pre><code>is = cr.openInputStream(uri)
</code></pre>
<p>and finally call:</p>
<pre><code>Drawable.createFromStream(InputStream is, String srcName)
</code></pre>
<p>...Here's an actual working code example so you can see for yourself:</p>
<pre><code>try {
InputStream inputStream = getContentResolver().openInputStream(yourUri);
yourDrawable = Drawable.createFromStream(inputStream, yourUri.toString() );
} catch (FileNotFoundException e) {
yourDrawable = getResources().getDrawable(R.drawable.default_image);
}
</code></pre> |
16,586,640 | Node.js async to sync | <p>How can I make this work</p>
<pre><code>var asyncToSync = syncFunc();
function syncFunc() {
var sync = true;
var data = null;
query(params, function(result){
data = result;
sync = false;
});
while(sync) {}
return data;
}
</code></pre>
<p>I tried to get sync function from async one,
I need it to use FreeTds async query as sync one</p> | 22,442,073 | 5 | 3 | null | 2013-05-16 11:50:44.053 UTC | 10 | 2017-01-06 09:57:20.817 UTC | 2013-05-16 13:30:11.043 UTC | null | 840,250 | null | 840,250 | null | 1 | 28 | javascript|node.js|asynchronous | 63,619 | <p>Use <a href="https://github.com/abbr/deasync" rel="noreferrer">deasync</a> - a module written in C++ which exposes Node.js event loop to JavaScript. The module also exposes a <code>sleep</code> function that blocks subsequent code but doesn't block entire thread, nor incur busy wait. You can put the <code>sleep</code> function in your <code>while</code> loop:</p>
<pre><code>var asyncToSync = syncFunc();
function syncFunc() {
var sync = true;
var data = null;
query(params, function(result){
data = result;
sync = false;
});
while(sync) {require('deasync').sleep(100);}
return data;
}
</code></pre> |
16,648,190 | How to set a particular font for a button text in android? | <p>I want my button text to be in the <em>Copperplate Gothic Light</em> font and I yet have not come across a simple clean code for a simple function as this. Help! </p>
<p>PS: Since android comes with ariel and a few other fonts on its own we need to <strong>import</strong> (apologies for the lack of a better word since I'm new to this) the font we wish to use. This is all I have been able to gather till yet and this is where the trail ends for me.</p> | 16,648,457 | 9 | 6 | null | 2013-05-20 11:09:33.893 UTC | 37 | 2021-09-21 11:21:57.717 UTC | 2017-07-23 22:37:05.64 UTC | null | 3,885,376 | null | 2,006,197 | null | 1 | 37 | android|button|text|fonts | 52,466 | <p>If you plan to add the same font to several buttons I suggest that you go all the way and implement it as a style and subclass button:</p>
<pre><code>public class ButtonPlus extends Button {
public ButtonPlus(Context context) {
super(context);
}
public ButtonPlus(Context context, AttributeSet attrs) {
super(context, attrs);
CustomFontHelper.setCustomFont(this, context, attrs);
}
public ButtonPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
CustomFontHelper.setCustomFont(this, context, attrs);
}
}
</code></pre>
<p>This is a helper class to set a font on a TextView (remember, Button is a subclass of TextView) based on the com.my.package:font attribute:</p>
<pre><code>public class CustomFontHelper {
/**
* Sets a font on a textview based on the custom com.my.package:font attribute
* If the custom font attribute isn't found in the attributes nothing happens
* @param textview
* @param context
* @param attrs
*/
public static void setCustomFont(TextView textview, Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomFont);
String font = a.getString(R.styleable.CustomFont_font);
setCustomFont(textview, font, context);
a.recycle();
}
/**
* Sets a font on a textview
* @param textview
* @param font
* @param context
*/
public static void setCustomFont(TextView textview, String font, Context context) {
if(font == null) {
return;
}
Typeface tf = FontCache.get(font, context);
if(tf != null) {
textview.setTypeface(tf);
}
}
}
</code></pre>
<p>And here's the FontCache to <a href="https://code.google.com/p/android/issues/detail?id=9904">reduce memory usage on older devices</a>:</p>
<pre><code>public class FontCache {
private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();
public static Typeface get(String name, Context context) {
Typeface tf = fontCache.get(name);
if(tf == null) {
try {
tf = Typeface.createFromAsset(context.getAssets(), name);
}
catch (Exception e) {
return null;
}
fontCache.put(name, tf);
}
return tf;
}
}
</code></pre>
<p>In res/values/attrs.xml we define the custom styleable attribute</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomFont">
<attr name="font" format="string"/>
</declare-styleable>
</resources>
</code></pre>
<p>And finally an example use in a layout:</p>
<pre><code> <com.my.package.buttons.ButtonPlus
style="@style/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_sometext"/>
</code></pre>
<p>And in res/values/style.xml</p>
<pre><code><style name="button" parent="@android:style/Widget.Button">
<item name="com.my.package:font">fonts/copperplate_gothic_light.TTF</item>
</style>
</code></pre>
<p>This may seem like an awful lot of work, but you'll thank me once you have couple of handfuls of buttons and textfields that you want to change font on.</p> |
16,908,236 | How to execute Python inline from a bash shell | <p>Is there a Python argument to execute code from the shell without starting up an interactive interpreter or reading from a file?
Something similar to:</p>
<pre><code>perl -e 'print "Hi"'
</code></pre> | 16,908,265 | 4 | 1 | null | 2013-06-04 01:03:02.107 UTC | 14 | 2020-11-18 19:36:54.257 UTC | 2016-04-16 07:02:41.19 UTC | null | 837,534 | null | 1,493,578 | null | 1 | 106 | python|shell|inline|execution | 75,482 | <p>This works:</p>
<pre><code>python -c 'print("Hi")'
Hi
</code></pre>
<p>From the manual, <code>man python</code>:</p>
<blockquote>
<pre><code> -c command
Specify the command to execute (see next section). This termi-
nates the option list (following options are passed as arguments
to the command).
</code></pre>
</blockquote> |
4,335,069 | Calling a javascript function from another .js file | <p>I have two external .js files. The first contains a function. The second calls the function.</p>
<p>file1.js</p>
<pre><code>$(document).ready(function() {
function menuHoverStart(element, topshift, thumbchange) {
... function here ...
}
});
</code></pre>
<p>file2.js</p>
<pre><code>$(document).ready(function() {
setTimeout(function() { menuHoverStart("#myDiv", "63px", "myIMG"); },2000);
});
</code></pre>
<p>The trouble is that this is not running the function. I need the two separate files because file2.js is inserted dynamically depending on certain conditions. This function works if I include the setTimeout... line at the end of file1.js</p>
<p>Any ideas?</p> | 4,335,143 | 2 | 2 | null | 2010-12-02 12:41:09.12 UTC | 5 | 2013-11-21 08:28:48.567 UTC | 2013-11-21 08:28:48.567 UTC | null | 2,459,290 | null | 457,148 | null | 1 | 31 | javascript|jquery | 77,550 | <p>The problem is, that <code>menuHoverStart</code> is not accessible outside of its scope (which is defined by the <code>.ready()</code> callback function in file #1). You need to make this function available in the global scope (or through any object that is available in the global scope):</p>
<pre><code>function menuHoverStart(element, topshift, thumbchange) {
// ...
}
$(document).ready(function() {
// ...
});
</code></pre>
<p>If you want <code>menuHoverStart</code> to stay in the <code>.ready()</code> callback, you need to add the function to the global object manually (using a function expression):</p>
<pre><code>$(document).ready(function() {
window.menuHoverStart = function (element, topshift, thumbchange) {
// ...
};
// ...
});
</code></pre> |
10,141,296 | How to convert UUID value to string | <p>I want to generate unique session id for my session. So i used UUID. Here what i did</p>
<pre><code>if (session == null) {
session = httpServletRequest.getSession(true);
session.setAttribute("logedin", "0");
if (!httpServletRequest.isRequestedSessionIdFromCookie()) {
UUID sessionID = UUID.randomUUID();
Cookie sessionCookie = new Cookie("JSESSIONID", "sessionID"); //problem
}
</code></pre>
<p>The Cookie constructor accept two strings, how can i convert my UUID to string so it get the UUID value which is unique?
Thanks</p> | 10,141,339 | 2 | 6 | null | 2012-04-13 12:59:07.817 UTC | 1 | 2017-04-23 16:41:17.937 UTC | null | null | null | null | 1,000,510 | null | 1 | 16 | java | 71,018 | <p>This will convert your uniques session id to string</p>
<pre><code>String suuid = UUID.randomUUID().toString();
</code></pre> |
28,322,807 | How to declare Object within $scope AngularJS | <p>I'm using AngularJS and I'm trying to create a template where I have an implicit object that calls <strong>test</strong> and inside <strong>test</strong> I have an array that I want to repeat when I call a function inside my Controller, but I'm getting <strong>undefined error</strong> when I'm trying do push an object inside the array.</p>
<p>Here is the example of my code:</p>
<pre><code><body ng-app="MyApp" ng-controller"MyController">
<input ng-model="person.name">
<button ng-click="createPhone()">
<div data-ng-repeat="phone in person.phones">
<input ng-model="phone.number">
</div>
</div>
</div>
</code></pre>
<p>Here is my Controller:</p>
<pre><code>//app.controller...
$scope.createPhone(){
var phone = {number: '123456789'};
$scope.person.phones.push(phone);
}
</code></pre>
<p>I'm getting:</p>
<blockquote>
<p>TypeError: Cannot set property 'phones' of undefined.</p>
</blockquote>
<p>Could anyone help me?</p> | 28,325,568 | 1 | 10 | null | 2015-02-04 13:37:14.207 UTC | 1 | 2015-02-04 15:48:58.833 UTC | 2015-02-04 14:09:52.557 UTC | null | 4,266,570 | null | 4,266,570 | null | 1 | 9 | javascript|angularjs | 56,777 | <p>You are going to want to do something like this:</p>
<p>Example can be seen here - <a href="http://jsfiddle.net/hm53pyjp/4/">http://jsfiddle.net/hm53pyjp/4/</a></p>
<p><strong>HTML:</strong></p>
<pre><code><div ng-app>
<div ng-controller="TestCtrl">
<input ng-model="person.name" />
<button ng-click="createPhone()">Create Phone</button>
<div ng-repeat="phone in person.phones">
<input ng-model="phone.number" />
</div>
</div>
</div>
</code></pre>
<p><strong>Controller:</strong></p>
<p>Create a <code>person</code> object that you can add things to and create a function to push objects to it.
So here I have created a <code>person</code> with the properties <code>name</code> and <code>phones</code>. I have give the <code>name</code> property a value of "User" and the <code>phones</code> property an array of numbers. In this case I have just populated one number to get started.</p>
<p>The function then gets called on the <code>ng-click</code> and simply pushes an object to the existing <code>phones</code> array.</p>
<p>As you push the objects to the array the <code>ng-repeat</code> will start to update the inputs on the page.</p>
<pre><code>function TestCtrl($scope) {
$scope.person = {
name : "User",
phones : [{number: 12345}]
};
$scope.createPhone = function () {
$scope.person.phones.push({
'number' : '111-222'
});
};
}
</code></pre> |
9,646,684 | Can't use System.Windows.Forms | <p>I have tried making (my first) a C# program:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hello");
Console.ReadLine();
}
}
}
</code></pre>
<p>This goes well, but if I try using System.Windows.Forms:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hello");
System.MessageBox("hello");
Console.ReadLine();
}
}
}
</code></pre>
<p>This is the error I get:</p>
<pre><code>Error 1 The type or namespace name 'Windows' does not exist in the namespace 'System' (are you missing an assembly reference?) C:\Users\Ramy\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs 5 14 ConsoleApplication1
</code></pre>
<p>Some details:
- I am using Visual Studio 2012;
- I have installed the .NET Development Kit;
- It is a Console Application.</p>
<p>Maybe it's because on a Console Application can't use System.Windows.Forms?
If so, what program should be? I also have tried with a form, but I was only displaying a window and no code.</p> | 9,646,739 | 11 | 3 | null | 2012-03-10 13:08:56.193 UTC | 21 | 2022-07-26 10:45:23.707 UTC | 2015-12-05 18:33:49.487 UTC | null | 3,110,834 | null | 570,339 | null | 1 | 99 | c#|winforms|visual-studio | 279,765 | <p>A console application does not automatically add a reference to System.Windows.Forms.dll.</p>
<p>Right-click your project in Solution Explorer and select Add reference... and then find System.Windows.Forms and add it.</p> |
11,581,337 | different values for float and double | <p>I don't understand why are float values different from double values. From the example bellow it appears that float provides different result than double for the same operation:</p>
<pre><code>public class Test {
public static void main(String[] args) {
double a = 99999.8d;
double b = 99999.65d;
System.out.println(a + b);
float a2 = 99999.8f;
float b2 = 99999.65f;
System.out.println(a2 + b2);
}
}
</code></pre>
<p>Output:</p>
<pre><code>199999.45
199999.44
</code></pre>
<p>Can you explain what makes this difference between float and double?</p> | 11,581,385 | 5 | 3 | null | 2012-07-20 14:25:58.687 UTC | 1 | 2015-12-14 10:41:52.6 UTC | null | null | null | null | 1,187,403 | null | 1 | 14 | java | 41,491 | <p>A float is a 32 bit IEEE 754 floating point.</p>
<p>A double is a 64 bit IEEE 754 floating point.</p>
<p>so it is just a matter of precision because neither of the fraction portions .8 and .65 have a terminating binary representation, so there is some rounding error. the double has more precision so it has slightly less rounding error.</p>
<p><a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html</a></p> |
11,987,067 | Pivoting of data using two columns | <p>I have data in pivoted format. It looks like this:</p>
<pre><code>-----------------------------------------
| user_id | org | position | lang |
-----------------------------------------
| 1001 | USE | Boss | EN |
| 1001 | USD | Bossa | FI |
| 1002 | GWR | Dim | SV |
| 1003 | GGA | DCS | FI |
| 1003 | GCA | DDD | SV |
-----------------------------------------
</code></pre>
<p>I would like to have the data represented as:</p>
<pre><code>-------------------------------------------------------------------------------------
| user_id | org_fi | position_fi | org_en | position_en | org_sv | position_sv |
-------------------------------------------------------------------------------------
| 1001 | USD | Bossa | USE | Boss | | |
| 1002 | | | | | GWR | Dim |
| 1003 | GGA | DCS | | | GCA | DDD |
-------------------------------------------------------------------------------------
</code></pre>
<p>I think that a pivot query with connect by command is needed.</p>
<hr>
<p>This is what I tried to do:</p>
<pre><code>SELECT user_id,
org,
position,
lang,
ROW_NUMBER () OVER (PARTITION BY lang, user_id ORDER BY ROWID) rn
FROM source
</code></pre>
<p>However, I have no idea how to go forward. </p> | 11,987,970 | 3 | 2 | null | 2012-08-16 12:24:35.22 UTC | 6 | 2016-12-16 14:44:47.813 UTC | 2016-12-16 14:39:13.94 UTC | null | 330,315 | null | 1,344,302 | null | 1 | 16 | sql|oracle|oracle11g | 63,281 | <p>Here is a way to get the data in the format you want:</p>
<pre><code>SELECT user_id,
max(case when lang = 'FI' THEN org ELSE ' ' END) org_fi,
max(case when lang = 'FI' THEN position ELSE ' ' END) position_fi,
max(case when lang = 'EN' THEN org ELSE ' ' END) org_en,
max(case when lang = 'EN' THEN position ELSE ' ' END) position_en,
max(case when lang = 'SV' THEN org ELSE ' ' END) org_sv,
max(case when lang = 'SV' THEN position ELSE ' ' END) position_sv
FROM source
group by user_id
order by user_id
</code></pre>
<p>See <a href="http://sqlfiddle.com/#!4/0ccfc/17">SQL Fiddle with Demo</a></p> |
12,037,723 | Windows 7 Symbolic Link - Cannot create a file when that file already exists | <p>I'm trying to create a symbolic link between two directories. I have a directory called TestDocs and TestDocs2. I will be doing all my work in TestDocs, but I need it all to be reflected in TestDocs2. So all files that are in TestDocs2 will be replicated in TestDocs, and if I add a file, change a file, etc in TestDocs it should be reflected in TestDocs2.</p>
<p>So I thought it would be as simple as just doing this:</p>
<pre><code>mklink /D TestDocs TestDocs2
</code></pre>
<p>But when I do that I get the error:</p>
<blockquote>
<p>Cannot create a file when that file already exists</p>
</blockquote>
<p>Why am I getting this?</p>
<p>Also, do I have the order of my TestDocs and TestDocs2 wrong in the command?</p>
<p>Thanks for the help, Symbolic Links have always confused me!</p> | 12,037,915 | 5 | 0 | null | 2012-08-20 12:33:47.967 UTC | 13 | 2022-04-13 18:11:39.323 UTC | 2014-01-13 16:08:44.763 UTC | null | 814,702 | null | 1,513,171 | null | 1 | 27 | windows-7|command-line|symlink | 78,016 | <p>The correct usage is:</p>
<pre><code>MKLINK [options] {link} {target}
</code></pre>
<p>You're creating a link, so the <code>link</code> is the new link you're about to create.<br>
And the <code>target</code> is the link's target, which is the existing directory.</p> |
11,810,484 | Is C++ platform dependent? | <p>Can we say that C++ is platform dependent?</p>
<p>I know that C++ uses compiler, and those compiler are different for different platforms. When we compile C++ code using compiler for example: on Windows, <strong>.EXE</strong> format file created.</p>
<p>Why is an <strong>.EXE</strong> file OS/Platform dependent?</p>
<p>What is the format inside <strong>.EXE files</strong>?</p>
<p>Why can't we run it on other platforms?</p> | 11,810,515 | 7 | 3 | null | 2012-08-04 17:14:40.147 UTC | 22 | 2017-12-11 14:41:32.197 UTC | 2016-09-01 06:30:31.4 UTC | null | 1,350,654 | null | 1,350,654 | null | 1 | 36 | c++|compiler-construction | 38,393 | <p>This is actually a relatively extensive topic. For simplicity, it comes down to two things: operating system and CPU architecture.</p>
<p>First of all, *.exe is generally only Windows since it is <em>binary</em> code which the windows operating system knows how to execute. Furthermore, the operating system knows how to translate this to the proper code for the architecture (this is why Windows is "just compatible"). Note that a lot more is going on, but this is a (<em>very</em>) high-level abstraction of what is going on.</p>
<p>Now, compilers will take C++ code and generate its corresponding assembly code for the architecture (i.e. x86, MIPS, etc.). Usually the compiler also has an assembler (or one which it can rely on). The assembler the links code and generates binary code which the hardware can execute. For more information on this topic look for more information on co-generation.</p>
<p><strong>Additional Note</strong></p>
<p>Consider Java which is not platform-dependent. Java compilers generate Java bytecode which is run on the Java virtual machine (JVM). It is important to notice that any time you wish to run a Java application you must run the Java virtual machine. Since the precompiled JVM knows how to operate on your operating system and CPU architecture, it can run its Java bytecode and effectively run the corresponding actions for your particular system.</p>
<p>In a compiled binary file (i.e. one from C++ code), you have system bytecode. So the kind of instructions which Java simulates for you are directly hard-coded into the .exe or whatever binary format you are using. Consider the following example:</p>
<p>Notice that this java code must eventually be run in the JVM and cannot stand-alone.</p>
<pre><code>Java Code:
System.out.println("hello") (To be compiled)
Compiled Java bytecode:
Print "hello" (To be run in JVM)
JVM:
(... some translation, maybe to architecture code - I forget exactly ...)
system_print_code "hello" (JVM translation to CPU specific)
</code></pre>
<p>Versus the C++ (which can be run in stand-alone mode):</p>
<pre><code>C++ Code:
cout<< "hello";
Architecture Code:
some_assembly_routine "hello"
Binary output:
system_print_code "hello"
</code></pre>
<h2>A real example</h2>
<p>If you're curious about how this may actually look in a real-life example, I have included one below.</p>
<p><strong>C++ Source</strong>
I placed this in a file called hello.cpp</p>
<pre><code>#include <iostream>
int main() {
using namespace std;
cout << "Hello world!" << endl;
return 0;
}
</code></pre>
<p><strong>Assembly (Generated from C++ source)</strong>
Generated via <code>g++ -S hello.cpp</code></p>
<pre><code> .file "test.c"
.section .rodata
.type _ZStL19piecewise_construct, @object
.size _ZStL19piecewise_construct, 1
_ZStL19piecewise_construct:
.zero 1
.local _ZStL8__ioinit
.comm _ZStL8__ioinit,1,1
.LC0:
.string "Hello world!"
.text
.globl main
.type main, @function
main:
.LFB1493:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
leaq .LC0(%rip), %rsi
leaq _ZSt4cout(%rip), %rdi
call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT
movq %rax, %rdx
movq _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@GOTPCREL(%rip), %rax
movq %rax, %rsi
movq %rdx, %rdi
call _ZNSolsEPFRSoS_E@PLT
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE1493:
.size main, .-main
.type _Z41__static_initialization_and_destruction_0ii, @function
_Z41__static_initialization_and_destruction_0ii:
.LFB1982:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl %edi, -4(%rbp)
movl %esi, -8(%rbp)
cmpl $1, -4(%rbp)
jne .L5
cmpl $65535, -8(%rbp)
jne .L5
leaq _ZStL8__ioinit(%rip), %rdi
call _ZNSt8ios_base4InitC1Ev@PLT
leaq __dso_handle(%rip), %rdx
leaq _ZStL8__ioinit(%rip), %rsi
movq _ZNSt8ios_base4InitD1Ev@GOTPCREL(%rip), %rax
movq %rax, %rdi
call __cxa_atexit@PLT
.L5:
nop
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE1982:
.size _Z41__static_initialization_and_destruction_0ii, .-_Z41__static_initialization_and_destruction_0ii
.type _GLOBAL__sub_I_main, @function
_GLOBAL__sub_I_main:
.LFB1983:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $65535, %esi
movl $1, %edi
call _Z41__static_initialization_and_destruction_0ii
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE1983:
.size _GLOBAL__sub_I_main, .-_GLOBAL__sub_I_main
.section .init_array,"aw"
.align 8
.quad _GLOBAL__sub_I_main
.hidden __dso_handle
.ident "GCC: (GNU) 7.2.1 20171128"
.section .note.GNU-stack,"",@progbits
</code></pre>
<p><strong>Binary output (Generated from assembly)</strong>
This is the unlinked form (i.e. not yet fully populated with symbol locations) of the binary output generated via <code>g++ -c</code> in hexadecimal form. I generated the hexadecimal representation using <code>xxd</code>. </p>
<pre><code>00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000 .ELF............
00000010: 0100 3e00 0100 0000 0000 0000 0000 0000 ..>.............
00000020: 0000 0000 0000 0000 0807 0000 0000 0000 ................
00000030: 0000 0000 4000 0000 0000 4000 0f00 0e00 ....@.....@.....
00000040: 5548 89e5 488d 3500 0000 0048 8d3d 0000 UH..H.5....H.=..
00000050: 0000 e800 0000 0048 89c2 488b 0500 0000 .......H..H.....
00000060: 0048 89c6 4889 d7e8 0000 0000 b800 0000 .H..H...........
00000070: 005d c355 4889 e548 83ec 1089 7dfc 8975 .].UH..H....}..u
00000080: f883 7dfc 0175 3281 7df8 ffff 0000 7529 ..}..u2.}.....u)
00000090: 488d 3d00 0000 00e8 0000 0000 488d 1500 H.=.........H...
000000a0: 0000 0048 8d35 0000 0000 488b 0500 0000 ...H.5....H.....
000000b0: 0048 89c7 e800 0000 0090 c9c3 5548 89e5 .H..........UH..
000000c0: beff ff00 00bf 0100 0000 e8a4 ffff ff5d ...............]
000000d0: c300 4865 6c6c 6f20 776f 726c 6421 0000 ..Hello world!..
000000e0: 0000 0000 0000 0000 0047 4343 3a20 2847 .........GCC: (G
000000f0: 4e55 2920 372e 322e 3120 3230 3137 3131 NU) 7.2.1 201711
00000100: 3238 0000 0000 0000 1400 0000 0000 0000 28..............
00000110: 017a 5200 0178 1001 1b0c 0708 9001 0000 .zR..x..........
00000120: 1c00 0000 1c00 0000 0000 0000 3300 0000 ............3...
00000130: 0041 0e10 8602 430d 066e 0c07 0800 0000 .A....C..n......
00000140: 1c00 0000 3c00 0000 0000 0000 4900 0000 ....<.......I...
00000150: 0041 0e10 8602 430d 0602 440c 0708 0000 .A....C...D.....
00000160: 1c00 0000 5c00 0000 0000 0000 1500 0000 ....\...........
00000170: 0041 0e10 8602 430d 0650 0c07 0800 0000 .A....C..P......
00000180: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000190: 0000 0000 0000 0000 0100 0000 0400 f1ff ................
000001a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000001b0: 0000 0000 0300 0100 0000 0000 0000 0000 ................
000001c0: 0000 0000 0000 0000 0000 0000 0300 0300 ................
000001d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000001e0: 0000 0000 0300 0400 0000 0000 0000 0000 ................
000001f0: 0000 0000 0000 0000 0000 0000 0300 0500 ................
00000200: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000210: 0800 0000 0100 0500 0000 0000 0000 0000 ................
00000220: 0100 0000 0000 0000 2300 0000 0100 0400 ........#.......
00000230: 0000 0000 0000 0000 0100 0000 0000 0000 ................
00000240: 3200 0000 0200 0100 3300 0000 0000 0000 2.......3.......
00000250: 4900 0000 0000 0000 6200 0000 0200 0100 I.......b.......
00000260: 7c00 0000 0000 0000 1500 0000 0000 0000 |...............
00000270: 0000 0000 0300 0600 0000 0000 0000 0000 ................
00000280: 0000 0000 0000 0000 0000 0000 0300 0900 ................
00000290: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000002a0: 0000 0000 0300 0a00 0000 0000 0000 0000 ................
000002b0: 0000 0000 0000 0000 0000 0000 0300 0800 ................
000002c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000002d0: 7100 0000 1200 0100 0000 0000 0000 0000 q...............
000002e0: 3300 0000 0000 0000 7600 0000 1000 0000 3.......v.......
000002f0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000300: 8000 0000 1000 0000 0000 0000 0000 0000 ................
00000310: 0000 0000 0000 0000 9600 0000 1000 0000 ................
00000320: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000330: ce00 0000 1000 0000 0000 0000 0000 0000 ................
00000340: 0000 0000 0000 0000 0901 0000 1000 0000 ................
00000350: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000360: 1a01 0000 1000 0000 0000 0000 0000 0000 ................
00000370: 0000 0000 0000 0000 3201 0000 1002 0000 ........2.......
00000380: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000390: 3f01 0000 1000 0000 0000 0000 0000 0000 ?...............
000003a0: 0000 0000 0000 0000 5701 0000 1000 0000 ........W.......
000003b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
000003c0: 0074 6573 742e 6300 5f5a 5374 4c31 3970 .test.c._ZStL19p
000003d0: 6965 6365 7769 7365 5f63 6f6e 7374 7275 iecewise_constru
000003e0: 6374 005f 5a53 744c 385f 5f69 6f69 6e69 ct._ZStL8__ioini
000003f0: 7400 5f5a 3431 5f5f 7374 6174 6963 5f69 t._Z41__static_i
00000400: 6e69 7469 616c 697a 6174 696f 6e5f 616e nitialization_an
00000410: 645f 6465 7374 7275 6374 696f 6e5f 3069 d_destruction_0i
00000420: 6900 5f47 4c4f 4241 4c5f 5f73 7562 5f49 i._GLOBAL__sub_I
00000430: 5f6d 6169 6e00 5f5a 5374 3463 6f75 7400 _main._ZSt4cout.
00000440: 5f47 4c4f 4241 4c5f 4f46 4653 4554 5f54 _GLOBAL_OFFSET_T
00000450: 4142 4c45 5f00 5f5a 5374 6c73 4953 7431 ABLE_._ZStlsISt1
00000460: 3163 6861 725f 7472 6169 7473 4963 4545 1char_traitsIcEE
00000470: 5253 7431 3362 6173 6963 5f6f 7374 7265 RSt13basic_ostre
00000480: 616d 4963 545f 4553 355f 504b 6300 5f5a amIcT_ES5_PKc._Z
00000490: 5374 3465 6e64 6c49 6353 7431 3163 6861 St4endlIcSt11cha
000004a0: 725f 7472 6169 7473 4963 4545 5253 7431 r_traitsIcEERSt1
000004b0: 3362 6173 6963 5f6f 7374 7265 616d 4954 3basic_ostreamIT
000004c0: 5f54 305f 4553 365f 005f 5a4e 536f 6c73 _T0_ES6_._ZNSols
000004d0: 4550 4652 536f 535f 4500 5f5a 4e53 7438 EPFRSoS_E._ZNSt8
000004e0: 696f 735f 6261 7365 3449 6e69 7443 3145 ios_base4InitC1E
000004f0: 7600 5f5f 6473 6f5f 6861 6e64 6c65 005f v.__dso_handle._
00000500: 5a4e 5374 3869 6f73 5f62 6173 6534 496e ZNSt8ios_base4In
00000510: 6974 4431 4576 005f 5f63 7861 5f61 7465 itD1Ev.__cxa_ate
00000520: 7869 7400 0000 0000 0700 0000 0000 0000 xit.............
00000530: 0200 0000 0500 0000 fdff ffff ffff ffff ................
00000540: 0e00 0000 0000 0000 0200 0000 0f00 0000 ................
00000550: fcff ffff ffff ffff 1300 0000 0000 0000 ................
00000560: 0400 0000 1100 0000 fcff ffff ffff ffff ................
00000570: 1d00 0000 0000 0000 2a00 0000 1200 0000 ........*.......
00000580: fcff ffff ffff ffff 2800 0000 0000 0000 ........(.......
00000590: 0400 0000 1300 0000 fcff ffff ffff ffff ................
000005a0: 5300 0000 0000 0000 0200 0000 0400 0000 S...............
000005b0: fcff ffff ffff ffff 5800 0000 0000 0000 ........X.......
000005c0: 0400 0000 1400 0000 fcff ffff ffff ffff ................
000005d0: 5f00 0000 0000 0000 0200 0000 1500 0000 _...............
000005e0: fcff ffff ffff ffff 6600 0000 0000 0000 ........f.......
000005f0: 0200 0000 0400 0000 fcff ffff ffff ffff ................
00000600: 6d00 0000 0000 0000 2a00 0000 1600 0000 m.......*.......
00000610: fcff ffff ffff ffff 7500 0000 0000 0000 ........u.......
00000620: 0400 0000 1700 0000 fcff ffff ffff ffff ................
00000630: 0000 0000 0000 0000 0100 0000 0200 0000 ................
00000640: 7c00 0000 0000 0000 2000 0000 0000 0000 |....... .......
00000650: 0200 0000 0200 0000 0000 0000 0000 0000 ................
00000660: 4000 0000 0000 0000 0200 0000 0200 0000 @...............
00000670: 3300 0000 0000 0000 6000 0000 0000 0000 3.......`.......
00000680: 0200 0000 0200 0000 7c00 0000 0000 0000 ........|.......
00000690: 002e 7379 6d74 6162 002e 7374 7274 6162 ..symtab..strtab
000006a0: 002e 7368 7374 7274 6162 002e 7265 6c61 ..shstrtab..rela
000006b0: 2e74 6578 7400 2e64 6174 6100 2e62 7373 .text..data..bss
000006c0: 002e 726f 6461 7461 002e 7265 6c61 2e69 ..rodata..rela.i
000006d0: 6e69 745f 6172 7261 7900 2e63 6f6d 6d65 nit_array..comme
000006e0: 6e74 002e 6e6f 7465 2e47 4e55 2d73 7461 nt..note.GNU-sta
000006f0: 636b 002e 7265 6c61 2e65 685f 6672 616d ck..rela.eh_fram
00000700: 6500 0000 0000 0000 0000 0000 0000 0000 e...............
00000710: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000720: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000730: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000740: 0000 0000 0000 0000 2000 0000 0100 0000 ........ .......
00000750: 0600 0000 0000 0000 0000 0000 0000 0000 ................
00000760: 4000 0000 0000 0000 9100 0000 0000 0000 @...............
00000770: 0000 0000 0000 0000 0100 0000 0000 0000 ................
00000780: 0000 0000 0000 0000 1b00 0000 0400 0000 ................
00000790: 4000 0000 0000 0000 0000 0000 0000 0000 @...............
000007a0: 2805 0000 0000 0000 0801 0000 0000 0000 (...............
000007b0: 0c00 0000 0100 0000 0800 0000 0000 0000 ................
000007c0: 1800 0000 0000 0000 2600 0000 0100 0000 ........&.......
000007d0: 0300 0000 0000 0000 0000 0000 0000 0000 ................
000007e0: d100 0000 0000 0000 0000 0000 0000 0000 ................
000007f0: 0000 0000 0000 0000 0100 0000 0000 0000 ................
00000800: 0000 0000 0000 0000 2c00 0000 0800 0000 ........,.......
00000810: 0300 0000 0000 0000 0000 0000 0000 0000 ................
00000820: d100 0000 0000 0000 0100 0000 0000 0000 ................
00000830: 0000 0000 0000 0000 0100 0000 0000 0000 ................
00000840: 0000 0000 0000 0000 3100 0000 0100 0000 ........1.......
00000850: 0200 0000 0000 0000 0000 0000 0000 0000 ................
00000860: d100 0000 0000 0000 0e00 0000 0000 0000 ................
00000870: 0000 0000 0000 0000 0100 0000 0000 0000 ................
00000880: 0000 0000 0000 0000 3e00 0000 0e00 0000 ........>.......
00000890: 0300 0000 0000 0000 0000 0000 0000 0000 ................
000008a0: e000 0000 0000 0000 0800 0000 0000 0000 ................
000008b0: 0000 0000 0000 0000 0800 0000 0000 0000 ................
000008c0: 0800 0000 0000 0000 3900 0000 0400 0000 ........9.......
000008d0: 4000 0000 0000 0000 0000 0000 0000 0000 @...............
000008e0: 3006 0000 0000 0000 1800 0000 0000 0000 0...............
000008f0: 0c00 0000 0600 0000 0800 0000 0000 0000 ................
00000900: 1800 0000 0000 0000 4a00 0000 0100 0000 ........J.......
00000910: 3000 0000 0000 0000 0000 0000 0000 0000 0...............
00000920: e800 0000 0000 0000 1b00 0000 0000 0000 ................
00000930: 0000 0000 0000 0000 0100 0000 0000 0000 ................
00000940: 0100 0000 0000 0000 5300 0000 0100 0000 ........S.......
00000950: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000960: 0301 0000 0000 0000 0000 0000 0000 0000 ................
00000970: 0000 0000 0000 0000 0100 0000 0000 0000 ................
00000980: 0000 0000 0000 0000 6800 0000 0100 0000 ........h.......
00000990: 0200 0000 0000 0000 0000 0000 0000 0000 ................
000009a0: 0801 0000 0000 0000 7800 0000 0000 0000 ........x.......
000009b0: 0000 0000 0000 0000 0800 0000 0000 0000 ................
000009c0: 0000 0000 0000 0000 6300 0000 0400 0000 ........c.......
000009d0: 4000 0000 0000 0000 0000 0000 0000 0000 @...............
000009e0: 4806 0000 0000 0000 4800 0000 0000 0000 H.......H.......
000009f0: 0c00 0000 0a00 0000 0800 0000 0000 0000 ................
00000a00: 1800 0000 0000 0000 0100 0000 0200 0000 ................
00000a10: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000a20: 8001 0000 0000 0000 4002 0000 0000 0000 ........@.......
00000a30: 0d00 0000 0e00 0000 0800 0000 0000 0000 ................
00000a40: 1800 0000 0000 0000 0900 0000 0300 0000 ................
00000a50: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000a60: c003 0000 0000 0000 6401 0000 0000 0000 ........d.......
00000a70: 0000 0000 0000 0000 0100 0000 0000 0000 ................
00000a80: 0000 0000 0000 0000 1100 0000 0300 0000 ................
00000a90: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000aa0: 9006 0000 0000 0000 7200 0000 0000 0000 ........r.......
00000ab0: 0000 0000 0000 0000 0100 0000 0000 0000 ................
00000ac0: 0000 0000 0000 0000 ........
</code></pre>
<p>These instructions correspond to an x86_64 machine. If you're interested in following along and matching the op codes, you can <a href="http://ref.x86asm.net/geek64.html" rel="noreferrer">look at this reference</a> or <a href="https://software.intel.com/en-us/articles/intel-sdm" rel="noreferrer">download the Intel manual</a> for completeness. Likewise, it is an <a href="https://en.wikipedia.org/wiki/Executable_and_Linkable_Format" rel="noreferrer">ELF</a> file so you can observe that we see things we expect (i.e. starting magic number of <code>0x7f</code>, etc.).</p>
<p>In any case, once linked against the system (i.e. run <code>g++ test.cpp</code> or <code>g++ test.s</code> or <code>g++ test.o</code>), this executable runs directly on top of your OS. There are no additional translation layers between this and the OS. Even so, the OS still does OS things like abstracting hardware interfaces, manage system resources, etc.</p>
<p>Tying this back to the original question, the output binary will look very different on a windows machine (for the same C++ code). At the very least, on a windows machine you would expect to see the file in the <a href="https://en.wikipedia.org/wiki/Portable_Executable" rel="noreferrer">Portable Executable (PE) format</a> which is distinctly not ELF.</p>
<p>This is unlike the following Java example which requires a JVM to run:</p>
<p><strong>Java Source File</strong>
This is placed in a file called <code>Test.java</code></p>
<pre><code>package mytest;
public class Test {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
</code></pre>
<p><strong>Java Byte Code (Generated from Java Source)</strong>
This is generated by running <code>javac -d . Test.java</code> and running the output file (i.e. <code>mytest/Test.class</code>) through <code>xxd</code></p>
<pre><code>00000000: cafe babe 0000 0034 001d 0a00 0600 0f09 .......4........
00000010: 0010 0011 0800 120a 0013 0014 0700 1507 ................
00000020: 0016 0100 063c 696e 6974 3e01 0003 2829 .....<init>...()
00000030: 5601 0004 436f 6465 0100 0f4c 696e 654e V...Code...LineN
00000040: 756d 6265 7254 6162 6c65 0100 046d 6169 umberTable...mai
00000050: 6e01 0016 285b 4c6a 6176 612f 6c61 6e67 n...([Ljava/lang
00000060: 2f53 7472 696e 673b 2956 0100 0a53 6f75 /String;)V...Sou
00000070: 7263 6546 696c 6501 0009 5465 7374 2e6a rceFile...Test.j
00000080: 6176 610c 0007 0008 0700 170c 0018 0019 ava.............
00000090: 0100 0c48 656c 6c6f 2077 6f72 6c64 2107 ...Hello world!.
000000a0: 001a 0c00 1b00 1c01 000b 6d79 7465 7374 ..........mytest
000000b0: 2f54 6573 7401 0010 6a61 7661 2f6c 616e /Test...java/lan
000000c0: 672f 4f62 6a65 6374 0100 106a 6176 612f g/Object...java/
000000d0: 6c61 6e67 2f53 7973 7465 6d01 0003 6f75 lang/System...ou
000000e0: 7401 0015 4c6a 6176 612f 696f 2f50 7269 t...Ljava/io/Pri
000000f0: 6e74 5374 7265 616d 3b01 0013 6a61 7661 ntStream;...java
00000100: 2f69 6f2f 5072 696e 7453 7472 6561 6d01 /io/PrintStream.
00000110: 0007 7072 696e 746c 6e01 0015 284c 6a61 ..println...(Lja
00000120: 7661 2f6c 616e 672f 5374 7269 6e67 3b29 va/lang/String;)
00000130: 5600 2100 0500 0600 0000 0000 0200 0100 V.!.............
00000140: 0700 0800 0100 0900 0000 1d00 0100 0100 ................
00000150: 0000 052a b700 01b1 0000 0001 000a 0000 ...*............
00000160: 0006 0001 0000 0003 0009 000b 000c 0001 ................
00000170: 0009 0000 0025 0002 0001 0000 0009 b200 .....%..........
00000180: 0212 03b6 0004 b100 0000 0100 0a00 0000 ................
00000190: 0a00 0200 0000 0500 0800 0600 0100 0d00 ................
000001a0: 0000 0200 0e .....
</code></pre>
<p>As one would expect, the byte code output <a href="https://en.wikipedia.org/wiki/Java_class_file#File_layout_and_structure" rel="noreferrer">starts with 0xCAFEBABE</a>.</p>
<p>The critical distinction here, however, is that this code cannot be run directly. It is still a binary output, but it's not intended to be executed directly by the operating system. If you tried to run this without a JVM on your system, you would just get an error. However, this code can be run on <em>any</em> operating system that contains a <em>compatible</em> JVM. The set of compatible JVM's depends on how you've <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html" rel="noreferrer">set your source and target</a>. By default, it's equivalent to the Java version you're using to compile. In this case, I used Java 8.</p>
<p>The way this works is that your JVM is compiled for each system specifically (similarly to the C++ example above) and <em>translates</em> its binary Java byte code into something your system can now execute.</p>
<p>At the end of the day, there is no free lunch-- as DanielKO mentioned in the comments, the JVM is still a "platform" but it's one-level higher than the OS so it can seem a bit more portable. Eventually, somewhere along the way, the code must translate to instructions valid for your specific operating system family and CPU architecture. However, in the case of Java and the JVM, you only have to compile <strong>a single application</strong> (i.e. the JVM itself) for all system flavors. At that point, everything written on top of the JVM has system support "for free" so to speak (as long as your application is entirely written in Java and isn't using native interfaces, etc.).</p>
<p>As I mentioned before, there are many caveats to this information :) This was a pretty straightforward example intended to illustrate what you might actually observe. That said, we didn't get into calling native code, using custom JVM agents, or anything else which may affect this answer slightly. In general, however, these more often fall into the category of "special cases" and you wouldn't often be using these things unless you understood why and (hopefully) their implications to portability.</p> |
11,574,376 | Return list of specific property of object using linq | <p>Given a class like this: </p>
<pre><code>public class Stock
{
public Stock() {}
public Guid StockID { get; set; }
public string Description { get; set; }
}
</code></pre>
<p>Lets say I now have a <code>List<Stock></code>. If I would like to retrieve a list of all the StockIDs and populate it into a IEnumerable or IList. Obviously I can do this.</p>
<pre><code>List<Stock> stockItems = new List<Stock>();
List<Guid> ids = new List<Guid>();
foreach (Stock itm in stockItems)
{
ids.Add(itm.StockID);
}
</code></pre>
<p>But is there some way I could use Linq to achieve the same result? I thought <code>Distinct()</code> might do it but couldn't work out how to achieve the desired result.</p> | 11,574,405 | 3 | 0 | null | 2012-07-20 06:59:55.673 UTC | 8 | 2017-06-02 09:09:40.713 UTC | null | null | null | null | 314,661 | null | 1 | 64 | c#|.net|linq|linq-query-syntax | 78,937 | <pre><code>var list = stockItems.Select(item => item.StockID).ToList();
</code></pre> |
3,244,803 | LaTeX - Add clickable links to a section/subsection with a PDF document | <p>I am making PDF with LaTeX. I have a few sections and subsections. I want to put a link towards the top of the document so that in the PDF someone can click on it and it'll go to that section/subsection. I know it's possible to have this with a linkable table of contents, but I don't want to make a table of contents, I need more control.</p> | 3,244,826 | 4 | 2 | null | 2010-07-14 09:18:58.527 UTC | 6 | 2018-10-03 15:44:26.87 UTC | null | null | null | null | 161,922 | null | 1 | 17 | pdf|latex|hyperlink|pdf-generation|typesetting | 53,451 | <p>Include <code>\usepackage{hyperref}</code> in the preamble of your document. Assign proper labels to your sections and reference these labels using <code>\ref{}</code>. These references will then be turned into clickable links when creating PDFs with pdflatex.</p> |
3,763,511 | Sending telnet commands and reading the response with Java | <p>I work for a large organization that supports many different sites on a nation wide network. Our vendor supplies diagnostic tools for the hardware we use at each site. The diagnostics and reports are accessed via Telnet.</p>
<p>The problem is we want to monitor <strong>all</strong> sites simultaneously and currently we can only check them one at a time (via telnet).</p>
<p>I have already built something that will use <code>Runtime.exec(String)</code> to send ping commands to each IP address. But now I want to be able to send specific commands automatically using the vendor's diagnostic and reporting tools. Any ideas on the best way to do this? NOTE we have a hybrid system - some of the sites are behind a firewall some are not. A complete solution would be ideal but I will settle for a partial one as well.</p>
<p>Could it be as simple as getting the input and output streams of the Process object returned by the <code>Runtime.exec(String)</code> and send my commands to the input and reading the response on the output? Or should I be connecting to port 23 (the usual telnet port) and then behave as any other client-server system. Or something else completely different?</p>
<p>I am continuing to try things out, just brainstorming at this point...</p>
<p>CODE: (sensitive information removed)</p>
<pre><code>void exec(String ip)
{
Socket sock = null;
BufferedReader br = null;
PrintWriter pw = null;
try
{
sock = new Socket(ip, 23);
br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
pw = new PrintWriter(sock.getOutputStream());
this.read(br);
System.out.println("Sending username");
pw.println("username");
this.read(br); // Always blocks here
System.out.println("Sending password");
pw.println("password");
this.read(br);
pw.close();
br.close();
sock.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
void read(BufferedReader br) throws IOException
{
char[] ca = new char[1024];
int rc = br.read(ca);
String s = new String(ca).trim();
Arrays.fill(ca, (char)0);
System.out.println("RC=" + rc + ":" + s);
//String s = br.readLine();
//
//while(s != null)
//{
// if(s.equalsIgnoreCase("username:"))
// break;
//
// s = br.readLine();
//
// System.out.println(s);
//}
</code></pre> | 3,763,558 | 5 | 0 | null | 2010-09-21 18:58:53.817 UTC | 8 | 2017-08-17 10:50:20.783 UTC | 2012-04-29 15:11:05.287 UTC | null | 50,776 | null | 435,978 | null | 1 | 16 | java | 87,074 | <p>Why don't you simply use the Socket system ?</p>
<p>Open a socket to the chosen server on port 23 and send your own commands from here.</p>
<hr>
<p>Here is a quick example :</p>
<pre><code>public class EchoClient {
public static void main(String[] args) throws IOException {
Socket pingSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
pingSocket = new Socket("servername", 23);
out = new PrintWriter(pingSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(pingSocket.getInputStream()));
} catch (IOException e) {
return;
}
out.println("ping");
System.out.println(in.readLine());
out.close();
in.close();
pingSocket.close();
}
}
</code></pre>
<hr>
<p><strong>Resources :</strong></p>
<ul>
<li><a href="http://download.oracle.com/javase/tutorial/networking/sockets/" rel="noreferrer">oracle.com - All about sockets</a></li>
</ul> |
3,900,151 | Is there a jquery event that fires when a new node is inserted into the dom? | <p>Is there an event jquery fires on a dom element when it is inserted into the dom? </p>
<p>E.g. lets say I load some content via ajax and add it to the DOM and in some other piece of javascript I could add an event using .live() so that when an event matching a specific selector is added to the DOM the event fires on said element. Similar to $(document).ready() but on content that is added to the DOM dynamically.</p>
<p>What I am dreaming of:</p>
<pre><code>$('.myClass').live('ready', function() {
alert('.myClass added to dom');
});
</code></pre>
<p>If jquery doesn't support such a thing then is there another way I could achieve this functionality without modifying the code that actually does the initial dom manipulation?</p> | 3,900,157 | 5 | 2 | null | 2010-10-10 11:43:44.017 UTC | 13 | 2022-08-10 12:26:09.527 UTC | null | null | null | null | 292,662 | null | 1 | 64 | jquery|html | 57,260 | <p>The <a href="http://plugins.jquery.com/livequery/" rel="noreferrer"><code>.livequery()</code> plugin</a> still serves this niche need, like this:</p>
<pre><code>$('.myClass').livequery(function() {
alert('.myClass added to dom');
});
</code></pre>
<p>If you pass it <em>just</em> a callback function like above, it'll run for each new element it finds, both initially and as they're added. Inside the function <code>this</code> refers to the just-added element.</p>
<p><a href="http://api.jquery.com/live/" rel="noreferrer"><code>.live()</code></a> listens for events that bubble, so doesn't fit this "when elements are added" situation, in that respect, <a href="http://plugins.jquery.com/livequery/" rel="noreferrer"><code>.livequery()</code></a> (the plugin) wasn't <em>completely</em> replaced by the addition of <a href="http://api.jquery.com/live/" rel="noreferrer"><code>.live()</code></a> to core, only the event bubbling portion (for the most part) was.</p> |
4,017,572 | How can I make an alias to a non-function member attribute in a Python class? | <p>I'm in the midst of writing a Python library API and I often run into the scenario where my users want multiple different names for the same functions and variables.</p>
<p>If I have a Python class with the function <code>foo()</code> and I want to make an alias to it called <code>bar()</code>, that's super easy:</p>
<pre><code>class Dummy:
def __init__(self):
pass
def foo(self):
pass
bar = foo
</code></pre>
<p>Now I can do this with no problem:</p>
<pre><code>d = Dummy()
d.foo()
d.bar()
</code></pre>
<p>What I'm wondering is what is the best way to do this with a class attribute that is a regular variable (e.g. a string) rather than a function? If I had this piece of code:</p>
<pre><code>d = Dummy()
print(d.x)
print(d.xValue)
</code></pre>
<p>I want <code>d.x</code> and <code>d.xValue</code> to always print the same thing. If <code>d.x</code> changes, it should change <code>d.xValue</code> also (and vice-versa).</p>
<p>I can think of a number of ways to do this, but none of them seem as smooth as I'd like:</p>
<ul>
<li>Write a custom annotation</li>
<li>Use the <code>@property</code> annotation and mess with the setter</li>
<li>Override the <code>__setattr__</code> class functions</li>
</ul>
<p>Which of these ways is best? Or is there another way? I can't help but feel that if it's so easy to make aliases for functions, it should be just as easy for arbitrary variables...</p> | 4,017,638 | 6 | 4 | null | 2010-10-25 18:19:44.063 UTC | 10 | 2021-09-14 21:36:21.02 UTC | 2020-10-28 13:25:39.603 UTC | null | 3,064,538 | null | 159,658 | null | 1 | 27 | python|class|alias | 10,370 | <p>You can provide a <a href="https://docs.python.org/3/reference/datamodel.html#object.__setattr__" rel="nofollow noreferrer"><code>__setattr__</code></a> and <a href="https://docs.python.org/3/reference/datamodel.html#object.__getattr__" rel="nofollow noreferrer"><code>__getattr__</code></a> that reference an aliases map:</p>
<pre><code>class Dummy:
aliases = {
'xValue': 'x',
'another': 'x',
}
def __init__(self):
self.x = 17
def __setattr__(self, name, value):
name = self.aliases.get(name, name)
object.__setattr__(self, name, value)
def __getattr__(self, name):
if name == "aliases":
raise AttributeError # http://nedbatchelder.com/blog/201010/surprising_getattr_recursion.html
name = self.aliases.get(name, name)
return object.__getattribute__(self, name)
d = Dummy()
assert d.x == 17
assert d.xValue == 17
d.x = 23
assert d.xValue == 23
d.xValue = 1492
assert d.x == 1492
</code></pre> |
3,671,551 | Is it possible to give one CSS class priority over another? | <p>Say I have a div that uses two css classes that both use text-align, but one is centered and the other is right aligned. </p>
<p>Is it possible to specify something that will give one class priority over the other?</p> | 3,671,560 | 6 | 0 | null | 2010-09-08 20:16:38.76 UTC | 16 | 2021-10-04 20:28:24.907 UTC | null | null | null | null | 226,897 | null | 1 | 79 | css | 109,806 | <ol>
<li>specify a more specific selector, eg prefix an ID before it or prefix the nodename before the class</li>
<li>assign it after the other class</li>
<li>if two classes are in separate files, import the priority file second</li>
<li>!important</li>
</ol>
<p><code>!important</code> is the lazy way, but you really should go for #1 to avoid important-ception. Once you've added one <code>!important</code> you can't use it to make some other rule even <em>more</em> important.</p> |
3,770,071 | Including external jar-files in a new jar-file build with Ant | <p>I have just 'inherited' a Java-project and not coming from a Java-background I am a little lost at times. Eclipse is used to debug and run the application during development. I have through Eclipse succeeded in creating a .jar-file that 'includes' all the required external jars like Log4J, xmlrpc-server, etc. This big .jar can then be run successfully using:</p>
<pre><code>java -jar myjar.jar
</code></pre>
<p>My next step is to automate builds using Ant (version 1.7.1) so I don't have to involve Eclipse to do builds and deployment. This has proven to be a challenge due to my lacking java-knowledge. The root of the project looks like this:</p>
<pre><code>|-> jars (where external jars have been placed)
|-> java
| |-> bin (where the finished .class / .jars are placed)
| |-> src (Where code lives)
| |-> ++files like build.xml etc
|-> sql (you guessed it; sql! )
</code></pre>
<p>My build.xml contains the following:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="build" name="Seraph">
<property environment="env"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<property name="build.dir" value="bin"/>
<property name="src.dir" value="src"/>
<property name="lib.dir" value="../jars"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir" value="${build.dir}/jar"/>
<property name="jar.file" value="${jar.dir}/seraph.jar"/>
<property name="manifest.file" value="${jar.dir}/MANIFEST.MF"/>
<property name="main.class" value="no.easyconnect.seraph.core.SeraphCore"/>
<path id="external.jars">
<fileset dir="${lib.dir}" includes="**/*.jar"/>
</path>
<path id="project.classpath">
<pathelement location="${src.dir}"/>
<path refid="external.jars" />
</path>
<target name="init">
<mkdir dir="${build.dir}"/>
<mkdir dir="${classes.dir}"/>
<mkdir dir="${jar.dir}"/>
<copy includeemptydirs="false" todir="${build.dir}">
<fileset dir="${src.dir}">
<exclude name="**/*.launch"/>
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="clean">
<delete dir="${build.dir}"/>
</target>
<target name="cleanall" depends="clean"/>
<target name="build" depends="init">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}" classpathref="project.classpath">
<src path="${src.dir}"/>
</javac>
</target>
<target name="build-jar" depends="build">
<delete file="${jar.file}" />
<delete file="${manifest.file}" />
<manifest file="${manifest.file}" >
<attribute name="built-by" value="${user.name}" />
<attribute name="Main-Class" value="${main.class}" />
</manifest>
<jar destfile="${jar.file}"
basedir="${build.dir}"
manifest="${manifest.file}">
<fileset dir="${classes.dir}" includes="**/*.class" />
<fileset dir="${lib.dir}" includes="**/*.jar" />
</jar>
</target>
</project>
</code></pre>
<p>I then run:
ant clean build-jar</p>
<p>and a file named seraph.jar is placed in the java/bin/jar-directory. I then try to run this jar using the following command:
java -jar bin/jar/seraph.jar</p>
<p>The result is this output at the console:</p>
<pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/Logger
at no.easyconnect.seraph.core.SeraphCore.<clinit>(SeraphCore.java:23)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Logger
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 1 more
Could not find the main class: no.easyconnect.seraph.core.SeraphCore. Program will exit.
</code></pre>
<p>I suspect that I have done something amazingly silly in the build.xml-file and have spent the better part of two days trying variations on the configuration, to no avail. Any help on getting this working is greatly appreciated.</p>
<p>Oh, and I'm sorry if I left some crucial information out. This is my first time posting here at SO.</p> | 3,777,581 | 8 | 2 | null | 2010-09-22 14:08:25.073 UTC | 21 | 2014-07-17 08:04:31.367 UTC | 2010-09-22 14:17:32.05 UTC | null | 422,597 | null | 455,066 | null | 1 | 38 | java|eclipse|ant|jar | 112,528 | <p>With the helpful advice from people who have answered here I started digging into One-Jar. After some dead-ends (and some results that were exactly like my previous results I managed to get it working. For other peoples reference I'm listing the build.xml that worked for me.</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="build" name="<INSERT_PROJECT_NAME_HERE>">
<property environment="env"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<property name="one-jar.dist.dir" value="../onejar"/>
<import file="${one-jar.dist.dir}/one-jar-ant-task.xml" optional="true" />
<property name="src.dir" value="src"/>
<property name="bin.dir" value="bin"/>
<property name="build.dir" value="build"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.target.dir" value="${build.dir}/jars"/>
<property name="external.lib.dir" value="../jars"/>
<property name="final.jar" value="${bin.dir}/<INSERT_NAME_OF_FINAL_JAR_HERE>"/>
<property name="main.class" value="<INSERT_MAIN_CLASS_HERE>"/>
<path id="project.classpath">
<fileset dir="${external.lib.dir}">
<include name="*.jar"/>
</fileset>
</path>
<target name="init">
<mkdir dir="${bin.dir}"/>
<mkdir dir="${build.dir}"/>
<mkdir dir="${classes.dir}"/>
<mkdir dir="${jar.target.dir}"/>
<copy includeemptydirs="false" todir="${classes.dir}">
<fileset dir="${src.dir}">
<exclude name="**/*.launch"/>
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="clean">
<delete dir="${build.dir}"/>
<delete dir="${bin.dir}"/>
</target>
<target name="cleanall" depends="clean"/>
<target name="build" depends="init">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="${classes.dir}" source="${source}" target="${target}">
<src path="${src.dir}"/>
<classpath refid="project.classpath"/>
</javac>
</target>
<target name="build-jar" depends="build">
<delete file="${final.jar}" />
<one-jar destfile="${final.jar}" onejarmainclass="${main.class}">
<main>
<fileset dir="${classes.dir}"/>
</main>
<lib>
<fileset dir="${external.lib.dir}" />
</lib>
</one-jar>
</target>
</project>
</code></pre>
<p>I hope someone else can benefit from this.</p> |
3,279,145 | Remove item from list based on condition | <p>I have a struct like this:</p>
<pre><code>public struct stuff
{
public int ID;
public int quan;
}
</code></pre>
<p>and want to to remove the product where <code>ID</code> is 1.<br />
I'm trying this currently:</p>
<pre><code>prods.Remove(new stuff{ prodID = 1});
</code></pre>
<p>and it's not working.</p>
<p><strong>THANKS TO ALL</strong></p> | 3,279,164 | 9 | 0 | null | 2010-07-19 07:28:04.047 UTC | 7 | 2022-09-01 19:35:46.22 UTC | 2020-08-21 16:25:19.237 UTC | DELETE me | 5,935,112 | DELETE me | null | null | 1 | 97 | c#|.net|entity-framework|linq | 164,443 | <p>Using linq:</p>
<pre><code>prods.Remove( prods.Single( s => s.ID == 1 ) );
</code></pre>
<p>Maybe you even want to use <code>SingleOrDefault()</code> and check if the element exists at all ...</p>
<p><strong>EDIT:</strong><br />
Since <code>stuff </code> is a struct, <code>SingleOrDefault()</code> will not return null. But it will return <em>default( stuff )</em>, which will have an ID of 0. When you don't have an ID of 0 for your <em>normal</em> stuff-objects you can query for this ID:</p>
<pre><code>var stuffToRemove = prods.SingleOrDefault( s => s.ID == 1 );
if( stuffToRemove.ID != 0 )
{
prods.Remove( stuffToRemove );
}
</code></pre> |
3,962,324 | Easiest Way To Diff Two Table Schemas In SQL Server 2008? | <p>I have to do checks between a development and release database and do this manually, which is both slow and not 100% reliable (I only visually inspect the tables).</p>
<p>Is there a quick and easy way to compare table schemas automatically? Maybe even a feature that does this built right into SQL server?</p>
<p>Edit: I'm comparing structure only, thank you for pointing this out.</p> | 3,962,352 | 10 | 5 | null | 2010-10-18 18:50:20.03 UTC | 4 | 2017-02-24 19:32:45.223 UTC | 2010-10-18 18:58:07.13 UTC | null | 281,671 | null | 281,671 | null | 1 | 30 | sql|database|sql-server-2008|schema|diff | 53,807 | <p>I'm a fan of <a href="http://code.google.com/p/sql-dbdiff/" rel="noreferrer">SQL DBDiff</a>, which is an open source tool you can use to compare tables, views, functions, users, etc. of two instances of SQL Server databases and generate a change script between the source and destination databases.</p> |
3,876,456 | Find the inner-most exception without using a while loop? | <p>When C# throws an exception, it can have an inner exception. What I want to do is get the inner-most exception, or in other words, the leaf exception that doesn't have an inner exception. I can do this in a while loop:</p>
<pre><code>while (e.InnerException != null)
{
e = e.InnerException;
}
</code></pre>
<p>But I was wondering if there was some one-liner I could use to do this instead.</p> | 3,876,512 | 12 | 9 | null | 2010-10-06 20:11:30.067 UTC | 19 | 2020-03-07 01:26:19.763 UTC | 2015-12-07 18:40:53.343 UTC | null | 1,497,596 | null | 135,318 | null | 1 | 92 | c#|.net|exception|exception-handling|while-loop | 47,472 | <p>Oneliner :)</p>
<pre><code>while (e.InnerException != null) e = e.InnerException;
</code></pre>
<p>Obviously, you can't make it any simpler.</p>
<p>As said in <a href="https://stackoverflow.com/a/19299530/170230]">this answer</a> by Glenn McElhoe, it's the only reliable way.</p> |
7,814,027 | How can I get URLs of open pages from Chrome and Firefox? | <p>I'm writing a system tray app that needs to check if an internal web based app is open.</p>
<p>I can check IE using the following:</p>
<pre><code>SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
string filename;
bool sdOpen = false;
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if (filename.Equals("iexplore"))
{
string[] urlParts = (ie.LocationURL.ToString()).Split('/');
string website = urlParts[2];
if (website == "myApp:8080") { sdOpen = true; };
}
}
if (sdOpen) { Console.WriteLine("App is open"); } else { Console.WriteLine("App is not open"); };
Console.ReadKey(true);
</code></pre>
<p>However, some of the users using the system prefer Chrome or Firefox.</p>
<p>How can I do the same as above (i.e. get the urls of any open tabs in the browser) for Chrome and Firefox? (I'm not going to bother with other browsers as these are the only ones in use in our organisation.)</p> | 10,588,918 | 4 | 4 | null | 2011-10-18 21:33:13.36 UTC | 20 | 2020-04-28 04:43:01.28 UTC | null | null | null | null | 375,655 | null | 1 | 23 | c#|firefox|url|google-chrome | 47,740 | <p>It's specific for every browser. That's for the major ones:</p>
<ul>
<li><strong>Internet Explorer</strong> - You can use SHDocVw (like you did)</li>
<li><strong>Firefox</strong> - You can get the URL using DDE (source below)</li>
<li><strong>Chrome</strong> - You can get the URL while enumerating all the child windows untill you get to the control with class "Chrome_OmniboxView" and then get the text using <code>GetWindowText</code></li>
<li><strong>Opera</strong> - You can use the same thing as Firefox, but with "opera"</li>
<li><strong>Safari</strong> - There is no known method since it uses custom drawn controls</li>
</ul>
<p><strong>EDIT: Since 2014, Chrome has changed and you need to get the URL with Acessibility.</strong></p>
<p>Code to get the URL from Firefox/Opera using DDE (which used <a href="http://ndde.codeplex.com/" rel="noreferrer">NDDE</a> - the only good DDE wrapper for .NET):</p>
<pre><code>//
// usage: GetBrowserURL("opera") or GetBrowserURL("firefox")
//
private string GetBrowserURL(string browser) {
try {
DdeClient dde = new DdeClient(browser, "WWW_GetWindowInfo");
dde.Connect();
string url = dde.Request("URL", int.MaxValue);
string[] text = url.Split(new string[] { "\",\"" }, StringSplitOptions.RemoveEmptyEntries);
dde.Disconnect();
return text[0].Substring(1);
} catch {
return null;
}
}
</code></pre> |
8,157,669 | Should I use Helgrind or DRD for thread error detection? | <p>Looks like <a href="http://valgrind.org/docs/manual/manual.html">Valgrind</a> has two tools that both do thread error detection: <a href="http://valgrind.org/docs/manual/hg-manual.html">Helgrind</a> and <a href="http://valgrind.org/docs/manual/drd-manual.html">DRD</a>. These tools are substantially similar.</p>
<p>My primary question is: when should I use one instead of the other to check my multi-threaded code?</p>
<p>More broadly, why are there two tools? I assume they aren't entirely redundant. What are the important differences? Should I generally plan on running my code through both tools?</p> | 8,261,637 | 4 | 1 | null | 2011-11-16 19:43:49.71 UTC | 5 | 2018-02-27 16:44:28.567 UTC | null | null | null | null | 202,292 | null | 1 | 30 | c|pthreads|valgrind | 9,285 | <p>While Helgrind can detect locking order violations, for most programs DRD needs less memory to perform its analysis. Also, DRD has support for detached threads. There are more subtle differences too - compare the respective manuals if you want to know more. See also <a href="http://valgrind.org/docs/manual/hg-manual.html" rel="noreferrer">http://valgrind.org/docs/manual/hg-manual.html</a> and <a href="http://valgrind.org/docs/manual/drd-manual.html" rel="noreferrer">http://valgrind.org/docs/manual/drd-manual.html</a>.</p> |
8,049,912 | How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone? | <p>I would like in my application to find a way to synch the date and time with something given by an external source.</p>
<p>I don't want to use the phone time because I might get a difference of maybe 5 minutes around real time. and 5 minutes extra or less = 10 minutes! </p>
<p>I have heard about time information in the GPS satellites or in Network antennas.</p>
<p>I have tried with System.getCurrentTime but i get the current the of the device, so, if my device is set up 5 minutes earlier, it display the wrong time.</p>
<p><strong>EDIT</strong></p>
<p>To make a short question: how can I get this time?</p>
<p><img src="https://i.stack.imgur.com/BJW9x.jpg" alt="enter image description here"></p> | 8,214,204 | 8 | 1 | null | 2011-11-08 11:49:36.017 UTC | 25 | 2022-09-13 08:48:20.9 UTC | 2012-01-11 18:05:07.827 UTC | null | 21,234 | null | 327,402 | null | 1 | 61 | android|networking|time | 119,603 | <p>I didn't know, but found the question interesting. So I dug in the android code... Thanks open-source :)</p>
<p>The screen you show is <code>DateTimeSettings</code>. The checkbox "Use network-provided values" is associated to the shared preference <code>String KEY_AUTO_TIME = "auto_time";</code> and also to <code>Settings.System.AUTO_TIME</code></p>
<p>This settings is observed by an observed called <code>mAutoTimeObserver</code> in the 2 network <code>ServiceStateTracker</code>s:
<code>GsmServiceStateTracker</code> and <code>CdmaServiceStateTracker</code>.</p>
<p>Both implementations call a method called <code>revertToNitz()</code> when the settings becomes true.
Apparently <a href="http://en.wikipedia.org/wiki/NITZ">NITZ</a> is the equivalent of NTP in the carrier world.</p>
<p>Bottom line: You can set the time to the value provided by the carrier thanks to <code>revertToNitz()</code>.
Unfortunately, I haven't found a mechanism to get the network time.
If you really need to do this, I'm afraid, you'll have to copy these <code>ServiceStateTracker</code>s implementations, catch the intent raised by the framework (I suppose), and add a getter to <code>mSavedTime</code>.</p> |
7,836,867 | C++, variable declaration in 'if' expression | <p>What's going on here?</p>
<pre><code>if(int a = Func1())
{
// Works.
}
if((int a = Func1()))
{
// Fails to compile.
}
if((int a = Func1())
&& (int b = Func2()))
)
{
// Do stuff with a and b.
// This is what I'd really like to be able to do.
}
</code></pre>
<p>Section 6.4.3 in the 2003 standard explains how variables declared in a selection statement condition have scope that extends to the end of the substatements controlled by the condition. But I don't see where it says anything about not being able to put parenthesis around the declaration, nor does it say anything about only one declaration per condition.</p>
<p>This limitation is annoying even in cases where only one declaration in the condition is required. Consider this.</p>
<pre><code>bool a = false, b = true;
if(bool x = a || b)
{
}
</code></pre>
<p>If I want to enter the 'if'-body scope with x set to false then the declaration needs parenthesis (since the assignment operator has lower precedence than the logical OR), but since parenthesis can't be used it requires declaration of x outside the body, leaking that declaration to a greater scope than is desired. Obviously this example is trivial but a more realistic case would be one where a and b are functions returning values that need to be tested</p>
<p>So is what I want to do non-conformant to the standard, or is my compiler just busting my balls (VS2008)?</p> | 44,177,439 | 8 | 5 | null | 2011-10-20 13:44:36.31 UTC | 28 | 2020-12-21 08:41:00.333 UTC | 2020-12-21 08:41:00.333 UTC | null | 7,478,597 | null | 954,927 | null | 1 | 145 | c++|compilation|if-statement|variable-declaration | 88,383 | <p>As of C++17 what you were trying to do <a href="http://en.cppreference.com/w/cpp/language/if" rel="noreferrer">is finally possible</a>:</p>
<pre><code>if (int a = Func1(), b = Func2(); a && b)
{
// Do stuff with a and b.
}
</code></pre>
<p>Note the use of <code>;</code> of instead of <code>,</code> to separate the declaration and the actual condition.</p> |
4,687,626 | C: epoll and multithreading | <p>I need to create specialized HTTP server, for this I plan to use epoll sycall, but I want to utilize multiple processors/cores and I can't come up with architecture solution.
ATM my idea is followng: create multiple threads with own epoll descriptors, main thread accepts connections and distributes them among threads epoll.
But are there any better solutions? Which books/articles/guides can I read on high load architectures? I've seen only <a href="http://www.kegel.com/c10k.html" rel="noreferrer">C10K</a> article, but most links to examples are dead :( and still no in-depth books on this subject :(.</p>
<p>Thank you for answers.</p>
<p><strong>UPD:</strong> Please be more specific, I need materials and examples (nginx is not an example because its too complex and has multiple abstraction layers to support multiple systems).</p> | 4,687,666 | 3 | 2 | null | 2011-01-14 03:08:37.093 UTC | 9 | 2016-05-25 12:02:43.783 UTC | 2011-01-14 16:24:23.883 UTC | null | 184,491 | null | 184,491 | null | 1 | 14 | c|architecture|epoll|high-load | 13,346 | <p>check <a href="http://monkey.org/~provos/libevent/" rel="noreferrer">libevent</a> and <a href="http://software.schmorp.de/pkg/libev.html" rel="noreferrer">libev</a> sources. they're highly readable, and already a good infrastructure to use.</p>
<p>Also, libev's documentation has plenty of examples of several tried and true strategies. Even if you prefer to write directly to <code>epoll()</code>, the examples can lead to several insights.</p> |
4,663,444 | Is there a RowSpan="All" in WPF? | <p>I create a <code>GridSplitter</code> across the 3 rows that I have in my grid like this:</p>
<pre><code><GridSplitter Grid.Row="0" Grid.Column="1" Background="Yellow"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Width="Auto" Height="Auto" ResizeDirection="Columns"
Grid.RowSpan="3" ...
</code></pre>
<p>However, it's conceivable that I might add another row to my grid at a later stage, and I don't really want to go back and update all of my rowspans.</p>
<p>My first guess was <code>Grid.RowSpan="*"</code>, but that doesn't compile.</p> | 4,663,600 | 3 | 0 | null | 2011-01-11 22:32:46.063 UTC | 5 | 2016-10-18 08:45:14.483 UTC | 2016-10-18 08:45:14.483 UTC | null | 2,157,640 | null | 210,566 | null | 1 | 33 | wpf|grid-layout | 21,128 | <p>You can bind to the RowDefinitions.Count but would need to update the binding when adding rows manually.</p>
<p>Edit: Only semi-manually in fact<br/>
Xaml:</p>
<pre><code><StackPanel Orientation="Vertical">
<Grid Name="GridThing">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.Children>
<Button Content="TopRight" Grid.Row="0" Grid.Column="1"/>
<Button Content="LowerRight" Grid.Row="1" Grid.Column="1"/>
<Button Content="Span Rows" Name="BSpan" Grid.RowSpan="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=RowDefinitions.Count, Mode=OneWay}"/>
</Grid.Children>
</Grid>
<Button Click="Button_Click" Content="Add Row" />
</StackPanel>
</code></pre>
<p>Code:</p>
<pre><code> private void Button_Click(object sender, RoutedEventArgs e)
{
GridThing.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(20) });
foreach (FrameworkElement child in GridThing.Children)
{
BindingExpression exp = child.GetBindingExpression(Grid.RowSpanProperty);
if (exp != null)
{
exp.UpdateTarget();
}
}
}
</code></pre> |
4,672,978 | How to AutoSize the height of a Label but not the width | <p>I have a <code>Panel</code> that I'm creating programmatically; additionally I'm adding several components to it.</p>
<p>One of these components is a <code>Label</code> which will contain user-generated content.</p>
<p>I don't know how tall the label should be, but it does have a fixed width.</p>
<p>How can I set the height so that it displays all the text, without changing the width?</p> | 4,673,638 | 3 | 0 | null | 2011-01-12 19:15:03.927 UTC | 6 | 2021-08-10 08:51:36.157 UTC | 2013-07-04 16:19:30.86 UTC | null | 1,563,422 | null | 12,243 | null | 1 | 35 | c#|.net|winforms | 45,794 | <p>Just use the <code>AutoSize</code> property, set it back to <code>True</code>.</p>
<p>Set the <code>MaximumSize</code> property to, say, <code>(60, 0)</code> so it can't grow horizontally, only vertically.</p> |
4,571,111 | How to check if text1 contains text2 using vb6? | <p>How to check if text1 contains text2 using vb6 ?</p>
<pre><code>Dim text1 as string
Dim text2 as string
text1 = "hello world I am Anas"
text2 = "Anas"
if (check if text2 is in text1) 'the result should be true or false
</code></pre> | 4,571,166 | 4 | 0 | null | 2010-12-31 16:22:23.633 UTC | 1 | 2017-07-11 15:11:16.407 UTC | 2012-04-03 23:33:40.29 UTC | null | 3,043 | null | 423,903 | null | 1 | 16 | vb6 | 64,111 | <p>You can use <a href="http://www.aivosto.com/vbtips/instr.html#syntax" rel="noreferrer"><code>InStr</code></a> function like this:</p>
<pre><code>Dim position As Integer
position = InStr(1, stringToSearch, stringToFind)
If position > 0 Then
' text is inside
Else
' text is not inide
End If
</code></pre> |
4,810,289 | Best architecture for an iOS application that makes many network requests? | <p>I'm in the process of rethinking my approach to the request architecture of a large app I'm developing. I'm currently using ASIHTTPRequest to actually make requests, but since I need many different types of requests as a result of many different actions taken in different view controllers, I'm trying to work out the best system of organizing these requests.</p>
<p>I'm currently building singleton "requesters" that are retained by the app delegate and sit around listening for NSNotifications that signal a request needs to be made; they make the request, listen for the response, and send out a new NSNotification with the response data. This solves most of my problems, but doesn't elegantly handle failed requests or simultaneous requests to the same singleton requester.</p>
<p>Anyone have any success devising a clear, OO architecture for making many different types of requests in an iOS app?</p> | 4,823,001 | 4 | 1 | null | 2011-01-26 21:33:40.213 UTC | 82 | 2015-02-09 15:25:47.657 UTC | null | null | null | null | 463,892 | null | 1 | 50 | iphone|objective-c|cocoa-touch|network-programming|asihttprequest | 23,256 | <p>After having tried several approaches, this is one architecture that is giving me excellent results, is easy to document, understand, maintain and extend:</p>
<ul>
<li>I have a single object taking care of network connectivity, let's call it a "network manager". Typically this object is a singleton (created using <a href="http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html" rel="noreferrer">Matt Gallagher's Cocoa singleton macro</a>).</li>
<li>Since you use ASIHTTPRequest (which I always do, wonderful API) I add an ASINetworkQueue ivar inside my network manager. I make the network manager the delegate of that queue.</li>
<li>I create subclasses of ASIHTTPRequest for each kind of network request that my app requires (typically, for each backend REST interaction or SOAP endpoint). This has another benefit (see below for details :)</li>
<li>Every time one of my controllers requires some data (refresh, viewDidAppear, etc), the network manager creates an instance of the required ASIHTTPRequest subclass, and then adds it to the queue.</li>
<li>The ASINetworkQueue takes care of bandwidth issues (depending on whether you are on 3G, EDGE or GPRS or Wifi, you have more bandwidth, and you can process more requests, etc). This is done by the queue, which is cool (at least, that's one of the things I understand this queue does, I hope I'm not mistaken :).</li>
<li>Whenever a request finishes or fails, the network manager is called (remember, the network manager is the queue's delegate).</li>
<li>The network manager doesn't know squat about what to do with the result of each request; hence, it just calls a method <em>on the request</em>! Remember, requests are subclasses of ASIHTTPRequest, so you can just put the code that manages the result of the request (typically, deserialization of JSON or XML into real objects, triggering other network connections, updating Core Data stores, etc). Putting the code into each separate request subclass, using a polymorphic method with a common name accross request classes, makes it very easy to debug and manage IMHO.</li>
<li>Finally, I notify the controllers above about interesting events using notifications; using a delegate protocol is not a good idea, because in your app you typically have many controllers talking to your network manager, and then notifications are more flexible (you can have several controllers responding to the same notification, etc).</li>
</ul>
<p>Anyway, this is how I've been doing it for a while, and frankly it works pretty well. I can extend the system horizontally, adding more ASIHTTPRequest subclasses as I need them, and the core of the network manager stays intact.</p>
<p>Hope it helps!</p> |
4,480,075 | Argparse optional positional arguments? | <p>I have a script which is meant to be used like this:
<code>usage: installer.py dir [-h] [-v]</code></p>
<p><code>dir</code> is a positional argument which is defined like this:</p>
<pre><code>parser.add_argument('dir', default=os.getcwd())
</code></pre>
<p>I want the <code>dir</code> to be optional: when it's not specified it should just be <code>cwd</code>.</p>
<p>Unfortunately when I don't specify the <code>dir</code> argument, I get <code>Error: Too few arguments</code>.</p> | 4,480,202 | 4 | 0 | null | 2010-12-18 20:45:35.5 UTC | 106 | 2022-09-12 15:38:03.533 UTC | 2017-02-19 11:03:46.71 UTC | null | 3,959,875 | null | 448,679 | null | 1 | 826 | python|argparse | 358,435 | <p>Use <a href="https://docs.python.org/3/library/argparse.html#nargs" rel="noreferrer"><code>nargs='?'</code></a> (or <code>nargs='*'</code> if you need more than one dir)</p>
<pre><code>parser.add_argument('dir', nargs='?', default=os.getcwd())
</code></pre>
<p>extended example:</p>
<pre><code>>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]
positional arguments:
dir
optional arguments:
-h, --help show this help message and exit
-v
</code></pre> |
4,368,396 | How do I convert a floating point C code to fixed point? | <p>I have a C code which uses doubles. I want to be able to run the code on a DSP (<a href="http://en.wikipedia.org/wiki/Texas_Instruments_TMS320" rel="nofollow">TMS320</a>). But the DSP doesn't support doubles, only fixed-point numbers. What is the best way to convert the code into fixed-point? Is there a good C library for fixed-point numbers (implemented as integers)?</p> | 4,370,435 | 5 | 3 | null | 2010-12-06 16:10:03.877 UTC | 10 | 2017-06-29 21:47:19.73 UTC | 2010-12-25 13:54:20.8 UTC | null | 110,028 | null | 110,028 | null | 1 | 13 | c|signal-processing|fixed-point|texas-instruments|beagleboard | 22,932 | <p>TI provides a fixed-point library called "IQmath":</p>
<p><a href="http://focus.ti.com/lit/sw/sprc990/sprc990.pdf" rel="noreferrer">http://focus.ti.com/lit/sw/sprc990/sprc990.pdf</a></p>
<p>Converting involves analyzing your current code - for each variable you need to know what range it can hold, and what precision it needs. Then you can decide which type to store it in. IQMath provides types from q30 with a range of +/-2 and a precision of 0.0000000001 to q1 with a range of ~+/- 1 million and a precision of 0.5. </p>
<p>For operations which can possibly overflow the range of the variables, you need to add checks for overflow, and decide how to handle it - pin it at max, store with a different scale, raise an error, etc.</p>
<p>There is really no way to convert to fixed point without really gaining a deep understanding of the dataflow of your process.</p> |
4,674,737 | Avoiding content type issues when downloading a file via browser on Android | <p>If I have a file made available to a browser through my webapp, I normally just set the URL to something like <code>http://website.com/webapp/download/89347/image.jpg</code>. I then set the HTTP headers <code>Content-Type: application/octet-stream; filename=image.jpg</code> and <code>Content-Disposition: Attachment</code>.</p>
<p>However, on the Android. It seems the only way I can get the file to download is to set <code>Content-Type: image/jpg</code>. Otherwise the file name says <code><Unknown></code> and an error comes </p>
<blockquote>
<p><strong>Download unsuccessful</strong><br>
Cannot download. The content is not supported on this phone</p>
</blockquote>
<p>Is there any way I can get Android to download and open the file through the browser without keeping a list of mime types?</p> | 5,728,859 | 5 | 3 | null | 2011-01-12 22:31:00.087 UTC | 16 | 2017-01-30 11:28:18.84 UTC | null | null | null | null | 463,304 | null | 1 | 17 | android|browser|download|content-type|content-disposition | 55,529 | <p>To make any downloads work on all (and especially older) Android versions as expected, you need to...</p>
<ol>
<li>set the ContentType to application/octet-stream</li>
<li>put the Content-Disposition filename value in double quotes</li>
<li>write the Content-Disposition filename extension in UPPERCASE</li>
</ol>
<p>Read my blog post for more details:<br>
<a href="http://digiblog.de/2011/04/19/android-and-the-download-file-headers/" rel="noreferrer">http://digiblog.de/2011/04/19/android-and-the-download-file-headers/</a></p> |
4,406,606 | Can JQuery listen to AJAX calls from other javascript? | <p>I need to build a feature into a shopping cart that uses AJAX to retrieve an updated copy of the template from the server when something changes (e.g. a product is removed). I cannot modify the server side code, or the JavaScript that makes the shopping cart work in the first place. (Not ideal I know, but that's how it is)</p>
<p>What I want to do is run my own JavaScript every time the cart updates. <strong>I want to know if it is possible to listen for AJAX calls</strong>, and run my code every time one is made.</p> | 6,036,392 | 5 | 2 | null | 2010-12-10 07:27:02.44 UTC | 17 | 2018-06-11 11:00:11.127 UTC | null | null | null | null | 482,077 | null | 1 | 27 | javascript|jquery|ajax | 24,428 | <p>To follow all AJAX calls on an HTML doc, you can overwrite the <code>XMLHttpRequest</code> prototype.
This way, you can watch for actions on methods of <code>XMLHttpRequest</code> objects.</p>
<p>Here's a small sample code :</p>
<pre><code>var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send,
onReadyStateChange;
function openReplacement(method, url, async, user, password) {
var syncMode = async !== false ? 'async' : 'sync';
console.warn(
'Preparing ' +
syncMode +
' HTTP request : ' +
method +
' ' +
url
);
return open.apply(this, arguments);
}
function sendReplacement(data) {
console.warn('Sending HTTP request data : ', data);
if(this.onreadystatechange) {
this._onreadystatechange = this.onreadystatechange;
}
this.onreadystatechange = onReadyStateChangeReplacement;
return send.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
console.warn('HTTP request ready state changed : ' + this.readyState);
if(this._onreadystatechange) {
return this._onreadystatechange.apply(this, arguments);
}
}
window.XMLHttpRequest.prototype.open = openReplacement;
window.XMLHttpRequest.prototype.send = sendReplacement;
</code></pre>
<p>With this sample, for every AJAX call you'll have a warning in the JavaScript console.</p>
<p>It's not jQuery script, but you can use jQuery inside as you want.</p>
<p>This solution probably won't work on IE 6 or older, but it works in FF, IE7+, Chrome, Opera, Safari...</p> |
4,103,405 | What is the algorithm for finding the center of a circle from three points? | <p>I have three points on the circumference of a circle:</p>
<pre><code>pt A = (A.x, A.y);
pt B = (B.x, B.y);
pt C = (C.x, C.y);
</code></pre>
<p>How do I calculate the center of the circle?</p>
<p>Implementing it in Processing (Java).</p>
<p>I found the answer and implemented a working solution:</p>
<pre><code> pt circleCenter(pt A, pt B, pt C) {
float yDelta_a = B.y - A.y;
float xDelta_a = B.x - A.x;
float yDelta_b = C.y - B.y;
float xDelta_b = C.x - B.x;
pt center = P(0,0);
float aSlope = yDelta_a/xDelta_a;
float bSlope = yDelta_b/xDelta_b;
center.x = (aSlope*bSlope*(A.y - C.y) + bSlope*(A.x + B.x)
- aSlope*(B.x+C.x) )/(2* (bSlope-aSlope) );
center.y = -1*(center.x - (A.x+B.x)/2)/aSlope + (A.y+B.y)/2;
return center;
}
</code></pre> | 4,103,414 | 6 | 3 | null | 2010-11-05 03:35:59.917 UTC | 13 | 2022-07-13 19:08:17.83 UTC | 2019-08-20 11:16:06.097 UTC | null | 3,578,997 | null | 497,681 | null | 1 | 36 | java|algorithm|geometry|computational-geometry | 41,410 | <p>It can be a rather in depth calculation. There is a simple step-by-step here: <a href="http://paulbourke.net/geometry/circlesphere/" rel="noreferrer">http://paulbourke.net/geometry/circlesphere/</a>. Once you have the equation of the circle, you can simply put it in a form involving H and K. The point (h,k) will be the center.</p>
<p>(scroll down a little ways at the link to get to the equations)</p> |
4,524,957 | How to check if my string only numeric | <p>How I can check if my string only contain numbers?</p>
<p>I don't remember. Something like isnumeric?</p> | 4,524,969 | 7 | 1 | null | 2010-12-24 07:43:01.093 UTC | 1 | 2020-02-25 14:54:15.31 UTC | 2016-01-16 09:52:44.147 UTC | user3956566 | null | null | 43,907 | null | 1 | 27 | c# | 66,262 | <p>Just check each character.</p>
<pre><code>bool IsAllDigits(string s)
{
foreach (char c in s)
{
if (!char.IsDigit(c))
return false;
}
return true;
}
</code></pre>
<p>Or use LINQ.</p>
<pre><code>bool IsAllDigits(string s) => s.All(char.IsDigit);
</code></pre>
<p>If you want to know whether or not a value entered into your program represents a valid integer value (in the range of <code>int</code>), you can use <code>TryParse()</code>. Note that this approach is not the same as checking if the string contains only numbers.</p>
<pre><code>bool IsAllDigits(string s) => int.TryParse(s, out int i);
</code></pre> |
4,072,260 | How to change Java version used by TOMCAT? | <p>I have Java 1.6 and Tomcat 5.5 installed on my system.</p>
<p>But Tomcat 5.5 accesses Java 1.5 and hence as the outcome I get the error <code>Bad version number in .class file</code> while executing java code with JSP.</p>
<p>How can I change the Tomcat version to Java 1.6?</p>
<p><strong>UPDATE</strong></p>
<p>I tried changing the JVM that the tomcat5w.exe is pointing to the version 1.6 and now I am out of the <code>Bad version in .class file</code> error. But now, I get the following error.</p>
<pre><code>exception
org.apache.jasper.JasperException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:498)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
root cause
java.lang.NullPointerException
myfirst.SearchLink.checkURL(SearchLink.java:20)
org.apache.jsp.Test_jsp._jspService(Test_jsp.java:52)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
</code></pre>
<p>What might be the root cause?</p> | 4,072,272 | 7 | 3 | null | 2010-11-01 19:12:34.347 UTC | 10 | 2019-04-11 12:59:32.053 UTC | 2016-01-14 10:09:03.8 UTC | null | 3,885,376 | null | 402,011 | null | 1 | 60 | java|jsp|tomcat|tomcat5.5|java-home | 230,421 | <p>When you open catalina.sh / catalina.bat, you can see :</p>
<blockquote>
<p>Environment Variable Prequisites</p>
<p>JAVA_HOME Must point at your Java Development Kit installation.</p>
</blockquote>
<p>So, set your environment variable <code>JAVA_HOME</code> to point to Java 6. Also make sure <code>JRE_HOME</code> is pointing to the same target, if it is set.</p>
<p>Update: since you are on Windows, <a href="http://support.microsoft.com/kb/310519" rel="noreferrer">see here</a> for how to manage your environment variables</p> |
4,781,772 | How to test if an executable exists in the %PATH% from a windows batch file? | <p>I'm looking for a simple way to test if an executable exists in the PATH environment variable from a Windows batch file. </p>
<p>Usage of external tools not provided by the OS is not allowed. The minimal Windows version required is Windows XP.</p> | 4,781,795 | 8 | 2 | null | 2011-01-24 12:08:03.077 UTC | 30 | 2019-03-25 07:06:57.96 UTC | 2013-11-17 19:37:22.063 UTC | null | 14,749 | null | 99,834 | null | 1 | 104 | windows|batch-file|batch-processing | 64,552 | <pre><code>for %%X in (myExecutable.exe) do (set FOUND=%%~$PATH:X)
if defined FOUND ...
</code></pre>
<p>If you need this for different extensions, just iterate over <code>PATHEXT</code>:</p>
<pre><code>set FOUND=
for %%e in (%PATHEXT%) do (
for %%X in (myExecutable%%e) do (
if not defined FOUND (
set FOUND=%%~$PATH:X
)
)
)
</code></pre>
<p>Could be that <code>where</code> also exists already on legacy Windows versions, but I don't have access to one, so I cannot tell. On my machine the following also works:</p>
<pre><code>where myExecutable
</code></pre>
<p>and returns with a non-zero exit code if it couldn't be found. In a batch you probably also want to redirect output to <code>NUL</code>, though.</p>
<p><strong>Keep in mind</strong></p>
<p>Parsing in batch (<code>.bat</code>) files and on the command line differs (because batch files have <code>%0</code>–<code>%9</code>), so you have to double the <code>%</code> there. On the command line this isn't necessary, so for variables are just <code>%X</code>. </p> |
4,291,151 | jQuery count child elements | <p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="selected">
<ul>
<li>29</li>
<li>16</li>
<li>5</li>
<li>8</li>
<li>10</li>
<li>7</li>
</ul>
</div></code></pre>
</div>
</div>
</p>
<p>I want to count the total number of <code><li></code> elements in <code><div id="selected"></div></code>. How is that possible using jQuery's <code>.children([selector])</code>?</p> | 4,291,160 | 8 | 2 | null | 2010-11-27 10:22:33.993 UTC | 36 | 2021-05-12 07:25:56.2 UTC | 2019-04-25 10:35:41.203 UTC | null | 860,099 | null | 417,143 | null | 1 | 363 | javascript|jquery|dom | 487,394 | <p>You can use <a href="http://api.jquery.com/length/"><code>.length</code></a> with just a <a href="http://api.jquery.com/descendant-selector/">descendant selector</a>, like this:</p>
<pre><code>var count = $("#selected li").length;
</code></pre>
<p>If you have to use <a href="http://api.jquery.com/children/"><code>.children()</code></a>, then it's like this:</p>
<pre><code>var count = $("#selected ul").children().length;
</code></pre>
<p><a href="http://www.jsfiddle.net/nick_craver/VXg2D/">You can test both versions here</a>.</p> |
4,507,718 | How to change the Tabs Images in the TabHost | <p>I am using the TabHost in my application, I am using four Tabs in my application and I want to use the different Images in the TabHost when the Particular Tab is been Selected and not selected. I need to use to different Images for a particular tab each. </p>
<p>When I Select any Tab the Image is little bright and when I switch to another Tab that bright Image becomes grey shaded. </p>
<p>I have implemented the TabHost but I don know how to change the Images in the TabHost.</p>
<p>Can anybody help me in this.</p>
<p>Thanks,
david</p> | 4,507,844 | 9 | 1 | null | 2010-12-22 09:19:44.94 UTC | 18 | 2016-03-28 09:00:21.23 UTC | 2013-07-31 11:46:07.653 UTC | null | 399,459 | null | 422,859 | null | 1 | 27 | android|android-tabhost|android-image | 43,491 | <p>If you wish to use different images for the selected and unselected states, then create 'selector' XML files in your drawables folder for each tab, e.g. tab1_selector.xml, tab2_selector.xml which should contain the following, replacing the drawable references to your images for selected and unselected states. i.e.</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="@drawable/tab1_selected_image" />
<item
android:state_selected="false"
android:drawable="@drawable/tab2_unselected_image" />
</selector>
</code></pre>
<p>Then using the .setIndicator method as bharath wrote above you should reference your new xml drawable resource. </p> |
4,770,985 | How to check if a string starts with another string in C? | <p>Is there something like <code>startsWith(str_a, str_b)</code> in the standard C library?</p>
<p>It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.</p>
<p>Examples:</p>
<pre><code>"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc" -> true
</code></pre> | 4,771,038 | 10 | 2 | null | 2011-01-22 22:15:22.973 UTC | 10 | 2022-07-15 22:04:13.02 UTC | 2015-06-09 20:23:35.843 UTC | null | 895,245 | null | 492,364 | null | 1 | 105 | c|string|comparison|startswith | 107,217 | <p>Apparently there's no standard C function for this. So:</p>
<pre><code>bool startsWith(const char *pre, const char *str)
{
size_t lenpre = strlen(pre),
lenstr = strlen(str);
return lenstr < lenpre ? false : memcmp(pre, str, lenpre) == 0;
}
</code></pre>
<hr>
<p>Note that the above is nice and clear, but if you're doing it in a tight loop or working with <em>very</em> large strings, it does not offer the best performance, as it scans the full length of both strings up front (<code>strlen</code>). Solutions like <a href="https://stackoverflow.com/a/4771055/157247">wj32's</a> or <a href="https://stackoverflow.com/a/4771386/157247">Christoph's</a> may offer better performance (although <a href="https://stackoverflow.com/questions/4770985/how-to-check-if-a-string-starts-with-another-string-in-c/4771038?noredirect=1#comment50194475_4771386">this comment</a> about vectorization is beyond my ken of C). Also note <a href="https://stackoverflow.com/a/4770992/157247">Fred Foo's solution</a> which avoids <code>strlen</code> on <code>str</code> (he's right, it's unnecessary if you use <code>strncmp</code> instead of <code>memcmp</code>). Only matters for (very) large strings or repeated use in tight loops, but when it matters, it matters.</p> |
4,178,168 | How to programmatically move, copy and delete files and directories on SD? | <p>I want to programmatically move, copy and delete files and directories on SD card. I've done a Google search but couldn't find anything useful.</p> | 4,178,184 | 16 | 0 | null | 2010-11-14 15:34:21.073 UTC | 46 | 2022-04-07 07:22:03.397 UTC | 2014-12-10 11:26:02.73 UTC | null | 44,390 | null | 458,678 | null | 1 | 104 | android|file|directory|copy|move | 197,673 | <p><a href="http://docs.oracle.com/javase/tutorial/essential/io/">Use standard Java I/O</a>. Use <code>Environment.getExternalStorageDirectory()</code> to get to the root of external storage (which, on some devices, is an SD card).</p> |
14,829,025 | Setting timeout for all the ProxyPass mappings in Apache Server mod_proxy directive | <p><strong>What I have and works:</strong></p>
<p>I'm using <em>Apache HTTPD 2.2</em> for proxy requests. I have multiple <em>ProxyPass</em> mappings:</p>
<pre><code>ProxyRequests On
<Proxy *>
AddDefaultCharset off
Order deny,allow
Allow from all
</Proxy>
ProxyPreserveHost Off
ProxyPass /a http://some_ip/
ProxyPassReverse /a http://some_ip/
ProxyPass /b http://some_other_ip/
ProxyPassReverse /b http://some_other_ip/
...
</code></pre>
<p>This works well.</p>
<p><strong>What I want:</strong></p>
<p>Some of my requests are taking longer, so they timed out giving me a <strong><em>Proxy Error - Reason: Error reading from remote server</em></strong>. </p>
<p>I want to set <code>timeout</code> for all of my requests. Can I do this without having to add <code>timeout=... KeepAlive=On</code> for every <code>ProxyPass</code> mapping? </p>
<p>I currently have something like:</p>
<pre><code>ProxyPass /a http://some_ip/ timeout=1200 KeepAlive=On
ProxyPassReverse /a http://some_ip/
ProxyPass /b http://some_other_ip/ timeout=1200 KeepAlive=On
ProxyPassReverse /b http://some_other_ip/
... and i do this for all my ProxyPass mappings
</code></pre>
<p>Can I tell Apache in some way to add <code>timeout</code> and <code>KeepAlive</code> parameters for all the mappings? Thanks in advance.</p> | 14,832,488 | 1 | 3 | null | 2013-02-12 09:12:37.95 UTC | 2 | 2013-02-12 12:23:33.527 UTC | null | null | null | null | 1,300,817 | null | 1 | 14 | apache|apache2|mod-proxy|apache2.2 | 83,757 | <p>I've managed to find a solution by my own. You can set the timeout using directly the <code>ProxyTimeout</code> directive of <code>mod_proxy</code> :</p>
<pre><code>ProxyRequests On
<Proxy *>
AddDefaultCharset off
Order deny,allow
Allow from all
</Proxy>
ProxyPreserveHost Off
ProxyTimeout 1200
</code></pre> |
14,587,085 | How can I globally force screen orientation in Android? | <p>There are a number of apps that are able to force screen rotation. They work even if an app explicitly wants to be viewed in another orientation. Right now I am disabling the accelerometer rotation system setting and setting my preferred orientation. An app can still override this.</p>
<p>Here is one of the apps that is able to override an app's requested orientation:</p>
<p><a href="https://play.google.com/store/apps/details?id=nl.fameit.rotate&hl=en">https://play.google.com/store/apps/details?id=nl.fameit.rotate&hl=en</a></p> | 14,654,302 | 4 | 4 | null | 2013-01-29 16:05:02.617 UTC | 16 | 2021-10-05 10:04:35.08 UTC | null | null | null | null | 907,872 | null | 1 | 19 | android|android-layout|orientation | 39,239 | <p>This can be done by creating a hidden system dialog. Its kind of a hack but its crazy enough to work.</p>
<pre><code> wm = (WindowManager) content.getSystemService(Service.WINDOW_SERVICE);
orientationChanger = new LinearLayout(content);
orientationChanger.setClickable(false);
orientationChanger.setFocusable(false);
orientationChanger.setFocusableInTouchMode(false);
orientationChanger.setLongClickable(false);
orientationLayout = new WindowManager.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
windowType, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.RGBA_8888);
wm.addView(orientationChanger, orientationLayout);
orientationChanger.setVisibility(View.GONE);
orientationLayout.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
wm.updateViewLayout(orientationChanger, orientationLayout);
orientationChanger.setVisibility(View.VISIBLE);
</code></pre> |
14,372,730 | Skip first line of fgetcsv method | <p>I have a CSV file and I read data from CSV file then I want to skip first line of CSV file.Which'll contain any header. I am using this code.</p>
<pre><code>while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
// Code to insert into database
}
</code></pre>
<p>When I insert data into th database then header should not to be saved into the database.</p> | 14,372,764 | 6 | 1 | null | 2013-01-17 05:29:24.887 UTC | 5 | 2020-07-25 11:20:44.21 UTC | 2020-07-22 21:20:29.057 UTC | null | 1,839,439 | null | 1,977,139 | null | 1 | 28 | php | 49,350 | <p>try:</p>
<pre><code>$flag = true;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
if($flag) { $flag = false; continue; }
// rest of your code
}
</code></pre> |
14,520,597 | IllegalStateException( "You can not set Dialog's OnCancelListener or OnDismissListener") | <p>This DialogFragment implementation causes an </p>
<blockquote>
<p>IllegalStateException( "You can not set Dialog's OnCancelListener or
OnDismissListener")</p>
</blockquote>
<p>. Why? Solution?</p>
<pre><code>public class OkCThreadDialog1 extends DialogFragment{
DialogInterface.OnCancelListener onCancelListener;
public OkCThreadDialog1(){
}
public static OkCThreadDialog1 newInstance(String title, String message) {
OkCThreadDialog1 frag = new OkCThreadDialog1();
Bundle args = new Bundle();
args.putString("title", title);
args.putString("message", message);
frag.setArguments(args);
return frag;
}
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder .setTitle(getArguments().getString("title"))
.setMessage(getArguments().getString("message"))
.setOnCancelListener(onCancelListener)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getDialog().cancel();
}});
return builder.create();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
onCancelListener = (DialogInterface.OnCancelListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement OkCancelDialogListener");
}
}
}
</code></pre>
<p>My Activity implements <code>DialogInterface.OnCancelListener</code> as follow:</p>
<pre><code>public class MainActivity extends Activity implements OkCancelDialogListener{
static final String TAG ="MainActivity";
@Override
public void onCancel(DialogInterface dialog) {
}
}
</code></pre>
<p>Exeception is thrown from <code>builder.create();</code>. What's wrong?</p> | 14,876,248 | 4 | 0 | null | 2013-01-25 11:11:18.013 UTC | 3 | 2019-12-04 10:47:51.503 UTC | 2017-12-31 15:06:05.703 UTC | null | 360,211 | null | 1,709,805 | null | 1 | 35 | android|android-dialogfragment | 10,587 | <p>From <a href="https://developer.android.com/reference/android/app/DialogFragment#onCreateDialog(android.os.Bundle)" rel="nofollow noreferrer">Android documentation</a>:</p>
<blockquote>
<p>public Dialog onCreateDialog (Bundle savedInstanceState)</p>
<p>Override to build your own custom Dialog container. This is
typically used to show an AlertDialog instead of a generic Dialog;
when doing so, onCreateView(LayoutInflater, ViewGroup, Bundle) does
not need to be implemented since the AlertDialog takes care of its own
content.</p>
<p>This method will be called after onCreate(Bundle) and before
onCreateView(LayoutInflater, ViewGroup, Bundle). The default
implementation simply instantiates and returns a Dialog class.</p>
<p><strong>Note: DialogFragment own the Dialog.setOnCancelListener and Dialog.setOnDismissListener callbacks. You must not set them yourself.</strong></p>
<p><strong>To find out about these events, override onCancel(DialogInterface) and
onDismiss(DialogInterface).</strong></p>
</blockquote>
<p>So basically, you must override the onDismiss or OnCancel instead of '.setOnCancelListener(onCancelListener)'.</p> |
14,911,038 | nav role=navigation | <p>I'm a little confused with roles. If I have in my page a navigation that is enclosed in a <code>nav</code> element and specify a <code>role="navigation"</code>.</p>
<pre><code><nav role="navigation">
...
</nav>
</code></pre>
<p>Isn't it already semantically explicit that the <code>nav</code> section is navigation?</p>
<p>Or if I have some other navigation sections on my page, and specify role for only one of them, this section becomes the most important on a page? And those without <code>role="navigation"</code> just boring navigations?</p> | 14,911,121 | 4 | 0 | null | 2013-02-16 13:53:45.137 UTC | 11 | 2021-05-12 12:16:08.333 UTC | 2017-11-02 03:39:08.63 UTC | null | 552,067 | null | 2,008,650 | null | 1 | 40 | html|semantic-markup | 38,731 | <p>It is true that most modern browsers/technologies recognise the HTML5 <code><nav></code> element as navigation and give it the same attention. But explicitly setting the <code>role="navigation"</code> attribute just makes sure that a lot more technologies can pick it up.</p>
<p>For example screen-readers and other technologies for users with disabilities are very rarely fully standards compliant (especially if they have to work all the way back to IE6 or lower!) so adding the role attributes explicitly always ensures that you cover all your bases for the most users possible.</p>
<p>Also (and this is just a guess) some of the lesser known search engines may not fully recognise HTML5 yet, so adding these roles should help with the sites crawl-ability.</p> |
3,076,526 | Undo command in R | <p>I can't find something to the effect of an undo command in R (neither on An Introduction to R nor in R in a Nutshell). I am particularly interested in undoing/deleting when dealing with interactive graphs.</p>
<p>What approaches do you suggest?</p> | 3,076,842 | 2 | 0 | null | 2010-06-19 17:28:47.683 UTC | 8 | 2016-07-28 07:17:14.31 UTC | 2012-07-14 01:27:41.697 UTC | null | 180,892 | null | 344,513 | null | 1 | 11 | r | 71,133 | <p>You should consider a different approach which leads to <em>reproducible</em> work:</p>
<ul>
<li>Pick an editor you like and which has <a href="http://www.r-project.org" rel="noreferrer">R</a> support</li>
<li>Write your code in 'snippets', ie short files for functions, and then use the facilities of the editor / <a href="http://www.r-project.org" rel="noreferrer">R</a> integration to send the code to the <a href="http://www.r-project.org" rel="noreferrer">R</a> interpreter</li>
<li>If you make a mistake, re-edit your snippet and run it again</li>
<li>You will always have a log of what you did</li>
</ul>
<p>All this works <em>tremendously</em> well in <a href="http://ess.r-project.org" rel="noreferrer">ESS</a> which is why many experienced <a href="http://www.r-project.org" rel="noreferrer">R</a> users like this environment. But editors are a subjective and personal choice; other people like Eclipse with StatET better. There are other solutions for Mac OS X and Windows too, and all this has been discussed countless times before here on SO and on other places like the R lists.</p> |
2,787,543 | What is the difference between $ (dollar) and $! (dollar exclamation point) | <p>Can anybody explain the difference in Haskell between the operators <code>($)</code> and <code>($!)</code> (dollar sign vs dollar sign exclamation point)?</p>
<p>I haven't seen the use of <code>$!</code> anywhere so far, but while browsing through the Haskell <a href="http://www.zvon.org" rel="noreferrer">reference</a>, I noticed its existence and that it has the exact same definition as <code>$</code>. When trying some simple statements in a Haskell interpreter (<a href="http://www.haskell.org/haskellwiki/GHC/GHCi" rel="noreferrer">GHCi</a>), I couldn't find any difference, nor could I find any reference to the operator in the top listed tutorials when searching for <code>haskell tutorial</code>.</p>
<p>So, just out of curiosity, what is the difference, if at all?</p> | 2,787,560 | 2 | 2 | null | 2010-05-07 09:36:48.533 UTC | 11 | 2013-10-22 20:41:42.163 UTC | 2013-10-22 20:41:42.163 UTC | null | 1,309,352 | null | 212,115 | null | 1 | 32 | haskell|syntax | 6,774 | <p><code>($!)</code> is strict function application. That is, it evaluates the argument before evaluating the function.</p>
<p>This is contrary to normal lazy function application in Haskell, e.g. <code>f x</code> or <code>f $ x</code>, which first start to evaluate the function <code>f</code>, and only compute the argument <code>x</code> if it is needed.</p>
<p>For example <code>succ (1 + 2)</code> will delay the addition <code>1 + 2</code> by creating a thunk, and start to evaluate <code>succ</code> first. Only if the argument to succ is needed, will <code>1 + 2</code> be evaluated.</p>
<p>However, if you know for sure that the argument to a function will always be needed, you can use <code>($!)</code>, which will first evaluate the argument to weak head normal form, and then enter the function. This way, you don't create a whole big pile of thunks and this can be more efficient. In this example, <code>succ $! 1 + 2</code> would first compute <code>3</code> and then enter the function <code>succ</code>.</p>
<p>Note that it is not always safe to just replace normal function application with strict function application. For example:</p>
<pre><code>ghci> const 1 (error "noo!")
1
ghci> const 1 $! (error "noo!")
*** Exception: noo!
</code></pre> |
1,461,913 | Does C# Monitor.Wait() suffer from spurious wakeups? | <p>Java's <a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#wait%28long%29" rel="noreferrer">Object.wait()</a> warns against "spurious wakeups" but C#'s <a href="http://msdn.microsoft.com/en-us/library/syehfawa.aspx" rel="noreferrer">Monitor.wait()</a> doesn't seem to mention it at all.</p>
<p>Seeing how Mono is implemented on top of Linux, and Linux has <a href="http://en.wikipedia.org/wiki/Spurious_wakeup#Spurious_wakeup_in_Linux" rel="noreferrer">spurious wakeups</a>, shouldn't this be documented somewhere?</p> | 1,461,956 | 1 | 0 | null | 2009-09-22 18:48:46.353 UTC | 22 | 2015-06-03 20:40:56.407 UTC | 2015-06-03 20:40:56.407 UTC | null | 179,850 | null | 14,731 | null | 1 | 49 | c#|java|multithreading | 10,540 | <p>Joe Duffy's <a href="https://rads.stackoverflow.com/amzn/click/com/032143482X" rel="noreferrer" rel="nofollow noreferrer">"Concurrent Programming On Windows"</a> mentions this (P311-312, P598). This bit is interesting:</p>
<blockquote>
<p>Note that in all of the above examples, threads must be resilient to something called spurious wake-ups - code that uses condition variables should remain correct and lively even in cases where it is awoken prematurely, that is, before the condition being sought has been established. This is not because the implementation will actually do such things (although some implementations on other platforms like Java and Pthreads are known to do so), nor because code will wake threads intentionally when it's unnecessary, but rather due to the fact that there is no guarantee around when a thread that has been awakened will become scheduled. Condition variables are not fair. It's possible - and even likely - that another thread will acquire the associated lock and make the condition false again before the awakened thread has a chance to reacquire the lock and return to the critical region.</p>
</blockquote>
<p>He then gives the normal pattern for a while loop testing the condition.</p>
<p>I would say that from this it's reasonable to expect that <code>Monitor.Wait</code> <em>won't</em> normally wake you prematurely, and that if you absolutely <em>know</em> that nothing else can have changed the condition then you <em>might</em> be able to get away without the condition loop: but that it's safer to include it anyway, just in case your logic is inaccurate.</p> |
31,385,363 | How to export a table dataframe in PySpark to csv? | <p>I am using Spark 1.3.1 (PySpark) and I have generated a table using a SQL query. I now have an object that is a <code>DataFrame</code>. I want to export this <code>DataFrame</code> object (I have called it "table") to a csv file so I can manipulate it and plot the columns. How do I export the <code>DataFrame</code> "table" to a csv file?</p>
<p>Thanks!</p> | 31,386,290 | 9 | 0 | null | 2015-07-13 13:56:14.3 UTC | 29 | 2022-04-05 08:34:06.77 UTC | 2019-01-09 22:14:33.007 UTC | null | -1 | null | 4,139,143 | null | 1 | 111 | python|apache-spark|dataframe|apache-spark-sql|export-to-csv | 366,088 | <p>If data frame fits in a driver memory and you want to save to local files system you can convert <a href="https://github.com/apache/spark/blob/master/python/pyspark/sql/dataframe.py#L42" rel="noreferrer">Spark DataFrame</a> to local <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="noreferrer">Pandas DataFrame</a> using <a href="https://github.com/apache/spark/blob/master/python/pyspark/sql/dataframe.py#L1229" rel="noreferrer"><code>toPandas</code></a> method and then simply use <code>to_csv</code>:</p>
<pre><code>df.toPandas().to_csv('mycsv.csv')
</code></pre>
<p>Otherwise you can use <a href="https://github.com/databricks/spark-csv" rel="noreferrer">spark-csv</a>:</p>
<ul>
<li><p>Spark 1.3</p>
<pre><code>df.save('mycsv.csv', 'com.databricks.spark.csv')
</code></pre></li>
<li><p>Spark 1.4+</p>
<pre><code>df.write.format('com.databricks.spark.csv').save('mycsv.csv')
</code></pre></li>
</ul>
<p>In Spark 2.0+ you can use <code>csv</code> data source directly:</p>
<pre><code>df.write.csv('mycsv.csv')
</code></pre> |
40,365,354 | Linker command failed with exit code 1 - duplicate symbol __TMRbBp | <p>Since I've updated to Xcode 8.1 I can't archive and also not run in Release mode (in debug mode its working). The error is that there are several "duplicate symbols for architecture arm64" and all are "duplicate symbol __TMRbBp". Whats that?</p> | 40,398,562 | 15 | 0 | null | 2016-11-01 17:27:47.34 UTC | 8 | 2020-07-18 11:47:12.537 UTC | 2019-03-21 13:30:17.603 UTC | null | 107,625 | null | 170,448 | null | 1 | 40 | xcode8 | 171,717 | <p>It seems to be a bug in Swift. See
<a href="https://forums.developer.apple.com/thread/66580" rel="noreferrer">discussion on Apple developers portal</a></p>
<p>It is said to be fixed in Xcode version that is about to be released.
But for now there is temporary workaround:</p>
<p>Go to your target <code>Build Settings</code> and set <code>Reflection Metadata Level</code> flag to <code>None</code></p> |
38,599,554 | How do you get a specific version from Git in Visual Studio 2015? | <p>Is there a way to get a specific version (from a specific commit) of a file in Visual Studio 2015 - Team Explorer/Team Services Git?</p>
<p>I simply wish to run the solution with a previous version of a file just to see how things used to run and then come back to the latest version to continue development.</p>
<p>I did not create any branches. I kept on committing in the "master" branch.</p> | 38,599,925 | 3 | 0 | null | 2016-07-26 20:45:40.113 UTC | 8 | 2020-09-18 03:44:43.033 UTC | 2018-07-25 20:47:23.957 UTC | null | 63,550 | null | 483,638 | null | 1 | 65 | git|visual-studio-2015|azure-devops | 60,835 | <p>In Visual Studio 2015, if you do <em>View History</em> (from the <em>Actions</em> menu on the <em>Changes</em> panel in Team Explorer):</p>
<p><a href="https://i.stack.imgur.com/fXYBJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fXYBJ.png" alt="View History"></a></p>
<p>Then right click on the commit you're interested in:</p>
<p><a href="https://i.stack.imgur.com/21StM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/21StM.png" alt="Right Click"></a></p>
<p>You can create a branch from there:</p>
<p><a href="https://i.stack.imgur.com/ZaNeg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZaNeg.png" alt="New branch"></a></p>
<p>I cannot see a way to just checkout to the commit in Visual Studio.</p>
<hr>
<p>Working with the command line you can do a checkout of the commit SHA you want to use:</p>
<pre><code>git checkout 9eab01d9
</code></pre>
<p>When you are done, just check out master again:</p>
<pre><code>git checkout master
</code></pre>
<p>You might get warnings about working on a detached head, in that case you could <a href="https://stackoverflow.com/a/5658339/383710">create a branch temporarily</a>:</p>
<pre><code>git checkout -b temp-branch-name 9eab01d9
</code></pre>
<p>It is a good idea to get comfortable with the Git command line, the Visual Studio tooling is coming along, but it misses a lot of features.</p> |
30,050,097 | copy data from csv to postgresql using python | <p>I am on windows 7 64 bit.
I have a csv file 'data.csv'.
I want to import data to a postgresql table 'temp_unicommerce_status' via a python script.</p>
<p>My Script is:</p>
<pre><code>import psycopg2
conn = psycopg2.connect("host='localhost' port='5432' dbname='Ekodev' user='bn_openerp' password='fa05844d'")
cur = conn.cursor()
cur.execute("""truncate table "meta".temp_unicommerce_status;""")
cur.execute("""Copy temp_unicommerce_status from 'C:\Users\n\Desktop\data.csv';""")
conn.commit()
conn.close()
</code></pre>
<p>I am getting this error</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\n\Documents\NetBeansProjects\Unicommerce_Status_Update\src\unicommerce_status_update.py", line 5, in <module>
cur.execute("""Copy temp_unicommerce_status from 'C:\\Users\\n\\Desktop\\data.csv';""")
psycopg2.ProgrammingError: must be superuser to COPY to or from a file
HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.
</code></pre> | 30,059,899 | 8 | 0 | null | 2015-05-05 10:10:39.62 UTC | 9 | 2020-08-10 10:44:34.877 UTC | 2015-05-05 11:18:13.913 UTC | null | 3,682,599 | null | 4,349,666 | null | 1 | 30 | python|postgresql|psycopg2|postgresql-copy | 72,573 | <p>Use the <a href="http://initd.org/psycopg/docs/cursor.html#cursor.copy_from" rel="noreferrer"><code>copy_from</code> cursor method</a></p>
<pre><code>f = open(r'C:\Users\n\Desktop\data.csv', 'r')
cur.copy_from(f, temp_unicommerce_status, sep=',')
f.close()
</code></pre>
<p>The file must be passed as an object.</p>
<p>Since you are coping from a csv file it is necessary to specify the separator as the default is a tab character</p> |
49,786,779 | Error: Program type already present: android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat | <p>After upgrading to Android Studio 3.1, I started to get following error during build. Project uses multidex and DX is enabled by default as you would notice in the error. I tried to check dependency graph to understand what is going on but so far have no clue. Interestingly this only fails on my machine. I cleaned up everything, including reinstall etc but nothing worked. </p>
<p>Anyone had the same issue and how did you solve it? Or any direction that I can take a look?</p>
<pre><code>AGPBI: {
"kind":"error",
"text":"Program type already present: android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat",
"sources":[{}],
"tool":"D8"
}
</code></pre>
<p>This is the task that fails:</p>
<pre><code>transformDexArchiveWithExternalLibsDexMergerForDebug
</code></pre>
<p>I checked similar issues and it seems random things fixes their problem, I'm not sure what is the real cause.</p> | 50,147,985 | 10 | 0 | null | 2018-04-12 01:52:29.803 UTC | 3 | 2018-12-16 06:42:10.883 UTC | null | null | null | null | 579,671 | null | 1 | 13 | android|android-studio|build|android-multidex | 39,983 | <p>I managed to determine the root cause by using the following steps. It may be different use case for each issue, therefore this is the way to determine the root cause.</p>
<ul>
<li>Go to android studio</li>
<li>Navigate -> Class</li>
<li>Check <code>include non-project classes</code></li>
<li>Copy paste full class path with package name. <code>android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat</code> </li>
<li>You should be able to see where it is used. Most probably you may need to remove it from one of them.</li>
</ul>
<p>In my case the issue was ViewPagerIndicator library was downloading support library as jar. Removing it solved the issue.</p> |
29,658,654 | regex to strip leading zeros treated as string | <p>I have numbers like this that need leading zero's removed.</p>
<p>Here is what I need: </p>
<p><code>00000004334300343</code> -> <code>4334300343</code></p>
<p><code>0003030435243</code> -> <code>3030435243</code></p>
<p>I can't figure this out as I'm new to regular expressions. This does not work:</p>
<pre><code>(^0)
</code></pre> | 29,658,664 | 7 | 0 | null | 2015-04-15 19:03:20.673 UTC | 6 | 2022-01-24 20:04:16.693 UTC | 2015-04-15 21:06:31.88 UTC | null | 2,206,004 | null | 1,445,444 | null | 1 | 22 | java|regex | 48,962 | <p>You're almost there. You just need quantifier:</p>
<pre><code>str = str.replaceAll("^0+", "");
</code></pre>
<p>It replaces 1 or more occurrences of 0 (that is what <code>+</code> quantifier is for. Similarly, we have <code>*</code> quantifier, which means 0 or more), at the beginning of the string (that's given by caret - <code>^</code>), with empty string.</p> |
44,883,269 | What is the difference between pm2 restart and pm2 reload | <p>I have a nodejs app running on server.</p>
<p>When should I use <strong>pm2 restart</strong>,and when should <strong>pm2 reload</strong> be used?</p>
<p>Referred to the <a href="https://github.com/Unitech/pm2#reloading-without-downtime" rel="noreferrer">pm2 documention</a> here,but couldn't figure out the difference in use case of the two.</p> | 44,883,787 | 1 | 0 | null | 2017-07-03 10:27:03.253 UTC | 6 | 2022-04-19 05:38:37.19 UTC | null | null | null | null | 3,994,271 | null | 1 | 65 | node.js|pm2 | 41,547 | <p>The difference is documented <a href="http://pm2.keymetrics.io/docs/usage/cluster-mode/#reload" rel="noreferrer">here</a>:</p>
<blockquote>
<p>As opposed to <code>restart</code>, which kills and restarts the process, <code>reload</code> achieves a 0-second-downtime reload.</p>
</blockquote>
<p>The latter means (found <a href="https://pm2.io/docs/runtime/guide/load-balancing/#0-seconds-downtime-reload" rel="noreferrer">here</a>):</p>
<blockquote>
<p>With reload, <code>pm2</code> restarts all processes one by one, always keeping at least one process running.</p>
</blockquote>
<p>It also states that:</p>
<blockquote>
<p>If the reload system hasn’t managed to reload your application, a timeout will fallback to a classic restart.</p>
</blockquote> |
64,304,353 | Main differences between lit-element & React | <p>Looking into React code it seems more similar to "Lit-Element" code, Both can be used to create web components. It is very helpful if someone can explain the main differences between the "React" and "Lit-element"?</p> | 64,307,820 | 1 | 0 | null | 2020-10-11 13:08:42.89 UTC | 12 | 2022-06-14 18:35:57.453 UTC | 2021-03-16 20:46:09.53 UTC | null | 9,263,007 | null | 9,263,007 | null | 1 | 18 | reactjs|web-component|lit-element | 9,748 | <blockquote>
<p>Frameworks <em>create</em> HTML, Web Components <em><strong>are</strong></em> HTML</p>
</blockquote>
<h3>React</h3>
<p>(almost a decade old now, by Facebook), key feature is its <em><strong>virtual</strong></em> DOM. That means all DOM elements are created in memory and React is in charge of delivering them to the (real)<strong>DOM</strong>. That also means you can <strong>NOT</strong> do <strong>any</strong> DOM updates yourself, or use the W3C standard Events system.<br />
<strong>everything in the</strong> (real)<strong>DOM</strong> is handled by React.<br />
Great when, like Facebook, you have to prevent thousands of developers messing around in the same DOM. (<em>There is no slow DOM, only developers writing slow code accessing the DOM</em>)</p>
<p><strong>Update 2022</strong> <a href="https://github.com/reactjs/rfcs/blob/react-18/text/0000-react-18.md" rel="noreferrer">React R18</a> still doesn't mention Custom Elements/native Web Components</p>
<h3>W3C <em>standard</em> Web Components</h3>
<p>(by: Apple, Mozilla, Google, Microsoft)</p>
<p>Are made up of 3 distinct technologies:</p>
<ul>
<li>Custom Elements API</li>
<li>Templates: <code><template></code></li>
<li>shadowDOM</li>
</ul>
<p><strong>each can be used without the other!</strong></p>
<p>You can attach shadowDOM on a regular <code><div></code> to create a DIV on steroids, without using Custom Elements or Templates.</p>
<p>The W3C Web Components standard is <em>defacto</em> developed by Browser builders Apple, Google, Mozilla & Microsoft.</p>
<p>All of them having to agree, makes for slow progress in setting a standard; but <em><strong>once</strong></em> a standard, W3C standards are supported for as long as JavaScript will run in the browser.</p>
<p>Web Components history (starting in 2010):</p>
<ul>
<li><p><strong>must see:</strong> <a href="https://www.youtube.com/watch?v=y-8Lmg5Gobw" rel="noreferrer">Video: Web Components: Just in the Nick of Time</a></p>
</li>
<li><p><strong>should see:</strong> <a href="https://www.youtube.com/watch?v=zfQoleQEa4w" rel="noreferrer">Practical lessons from a year of building web components - Google I/O 2016</a></p>
</li>
<li><p><a href="https://dev.to/this-is-learning/web-components-101-history-2p24" rel="noreferrer">https://dev.to/this-is-learning/web-components-101-history-2p24</a></p>
</li>
</ul>
<p>Microsoft chose to swap Browser-engines and made Edge (january 2020) run on Chromium,<br />
Web Components are supported in <strong>all modern Browsers now</strong>.</p>
<p>Chrome, Safari & FireFox supported Web Components (version V1) <strong>since 2018</strong>.<br />
And some browsers (partially) supported the now deprecated V0 version for longer.<br />
So there is plenty of experience with Web Components.</p>
<p>The <strong>Custom Elements API</strong> is an <strong>API</strong>, nothing more, nothing less, (but a powerful one)<br />
Comparing it to a Framework is like comparing Set and Map to Redux or Vuex.</p>
<p><strong>Templates</strong> are great, yet many developers copy/paste blog examples creating a <code><template></code> with javascript code instead of defining them in HTML</p>
<p><strong>shadowDOM</strong> (and SLOTs and :parts) deserve its own long chapter,<br />
many developers do not understand what it is or how to use it, yet most have a firm opinion on it.</p>
<h3>Lit</h3>
<p>(by Google). Is a library built <strong>on top</strong> of the W3C Web Components technologies</p>
<p>called <em>Lit-Element</em> & <em>Lit-HTML</em> prior to version 2.<br />
<strong>Before</strong> Lit, Google also had <em>Polymer</em></p>
<p><strong>!!! You do NOT need Lit to develop Web Components !!!</strong></p>
<p>Lit is a <strong>tool</strong> It will speed up the development process.<br />
When you learn Lit first, you are learning a <strong>tool</strong> not the Web Components <strong>technology</strong></p>
<p>Lit is <strong>syntactic sugar</strong> (kinda like jQuery was)</p>
<p>(Just like in early jQuery days) There are 50+ Lit alternatives:</p>
<p><a href="https://webcomponents.dev/blog/all-the-ways-to-make-a-web-component/" rel="noreferrer">https://webcomponents.dev/blog/all-the-ways-to-make-a-web-component/</a></p>
<h3>A Future for React?</h3>
<p>The interesting part is React, due to its <strong>virtual</strong> DOM implementation, only supports the W3C Custom Elements API for <strong>71%</strong> (see <a href="https://custom-elements-everywhere.com/" rel="noreferrer">https://custom-elements-everywhere.com/</a>).<br />
<strong>You</strong> need to create a React wrapper <strong>for each and every</strong> W3C component you want to use. (see: <a href="https://reactjs.org/docs/web-components.html" rel="noreferrer">https://reactjs.org/docs/web-components.html</a>)</p>
<p>The <a href="https://reactjs.org/blog/2020/10/20/react-v17.html" rel="noreferrer">React17 update</a> (october 2020) doesn't even mention the words Web Components, Custom Elements, shadowDOM or Templates</p>
<p>[Update 2021]
I don't read React updates no more. But Benny Powers did: <a href="https://dev.to/bennypowers/what-s-not-new-in-react-18-45c7" rel="noreferrer">https://dev.to/bennypowers/what-s-not-new-in-react-18-45c7</a></p>
<p><strong>WHATWG</strong></p>
<p>The very interesting truth is Facebook has no Browser, and isn't a core member of the WHATWG. And <strong>since 2019</strong>, the WHATWG (read: Google, Apple, Microsoft , Mozilla) are in control of what runs in the Browser: <a href="https://techxplore.com/news/2019-06-w3c-whatwg-agreement-version-html.html" rel="noreferrer">https://techxplore.com/news/2019-06-w3c-whatwg-agreement-version-html.html</a></p>
<p><strong>Frameworks</strong></p>
<p><strong>All</strong> other Frameworks (Angular, Vue, Svelte etc.) <strong>do</strong> support the W3C standard 100% <strong>and</strong> can <em>create</em> Web Components</p>
<h3>This makes for an interesting future.</h3>
<ul>
<li><p>Facebook, not developing a Browser, hardly has a stake in what Browsers run.</p>
</li>
<li><p>The WHATWG is <em>by-invitation-only</em>; will Google, Apple, Microsoft and Mozilla <strong>invite</strong> Facebook?</p>
</li>
<li><p>Some say React is the new Flash (<a href="https://www.adobe.com/products/flashplayer/end-of-life.html" rel="noreferrer">End Of Life: December 31, 2020</a>)</p>
</li>
<li><p>Some say FaceBook will merge Whatsapp, insTagram and Facebook,<br />
then will provide a new Browser <strong>everyone</strong> in the world <strong><em>must</em></strong> install</p>
</li>
</ul>
<h3>On Frameworks and Libraries</h3>
<blockquote>
<p>Disclaimer: I built my own motorbikes</p>
</blockquote>
<p>Frameworks and libraries are like the canned and packed ingredients you buy in the supermarket.</p>
<p>Sure, you get a meal on the table.<br />
But go buy groceries, <em>taste</em> spices, learn how to <em>cut</em>, <em>bake</em> and <em>grill</em>,<br />
and you will become a Chef.</p>
<p>One problem with Libraries/Frameworks is: there will always be <strong>breaking changes</strong> in new versions when new features are introduced. OR when features are no longer required because they are now part of the native and thus faster standard (but a different syntax) Think jQuery selectors and the (later implemented) <code>.querySelector</code></p>
<p>It is never a one-click upgrade. And because you most-likely did not write TDD tests for all these new features, <strong>you have to check and test ALL your code again</strong></p>
<p>Or worse, like with the Angular 1 to Angular 2 <strong><em>"upgrade"</em></strong>; you have to rewrite everything...</p>
<p>It is your choice what <em>professional</em> Front-End Developer you want to be</p>
<p><img src="https://i.imgur.com/VZs9RDO.png" alt="" /></p> |
31,711,286 | vscode debug ES6 application | <p>I have VSCode 0.5.0. I set the compilerOptions flag to "ES6" and the editor started recognizing my ES6 code as correct.
I have babel installed.
My Mocha tests use the babel compilers and my tests pass.
My app runs from the command line with no problems when I launch it with babel-node .
When I debug the app from within VSCode, it starts up without the ES6 support, and the app fails for ES6 syntax issues.
Are there debug settings that I missed turning on? </p> | 32,076,826 | 9 | 0 | null | 2015-07-29 21:16:39.533 UTC | 11 | 2019-06-18 18:24:03.287 UTC | 2016-01-31 02:36:44.913 UTC | null | 1,202,461 | null | 3,983,312 | null | 1 | 24 | node.js|debugging|ecmascript-6|babeljs|visual-studio-code | 16,204 | <p>By default VSCode launches node just with a --debug-brk option. This is not enough to enable ES6 support. If you can find out what options 'babel-node' passes to node, you could specify the same options in the VSCode launch config (through the runtimeArgs attribute). But this does not solve the issue that babel-node transpiles your ES6 code before running it.</p>
<p>Alternatively you could try to set the 'runtimeExecutable' in your launch config to 'babel-node'. This approach works with other node wrappers, but I haven't verified that is works with babel-node.</p>
<p>A third option (which should work) is to use the attach mode of VSCode: for this launch babel-node from the command line with the '--debug' option. It should print a port number. Then create an 'attach' launch config in VSCode with that port.</p> |
26,320,677 | Error: Could not resolve SDK path for 'macosx10.8' | <p>So I just installed qt around 5 minutes ago, and when I wanted to code a simple line of text in the Push Button and try to run it, I got this error:</p>
<p>:-1: error: Could not resolve SDK path for 'macosx10.8'</p>
<p>Could anyone help? Also, if you need me to do something, could you explain like I'm five please. (Not actually like I"m five but I hope you know what i mean)</p> | 26,321,074 | 10 | 0 | null | 2014-10-12 00:35:37.43 UTC | 11 | 2018-05-28 12:39:58.653 UTC | 2014-10-12 02:13:12.617 UTC | null | 608,639 | null | 1,501,995 | null | 1 | 38 | c++|qt | 26,674 | <p>The problem is that the online installer for Qt currently supports OSX 10.8 (Mountain Lion) by default, and I'm guessing you are on 10.9 (Mavericks) or greater.</p>
<p>There is a workaround:</p>
<ul>
<li>Navigate to where you installed Qt (default /Users/your username/Qt) using finder</li>
<li>Go to the subdirectory 5.3/clang_64/mkspecs directory</li>
<li>Open the file called qdevice.pri with a text editor</li>
<li>Change the line
<code>!host_build:QMAKE_MAC_SDK = macosx10.8</code>
to:
<ul>
<li><code>!host_build:QMAKE_MAC_SDK = macosx10.9</code> if you are on OS X 10.9 (Mavericks), or</li>
<li><code>!host_build:QMAKE_MAC_SDK = macosx</code> if you are on OS X 10.10 (Yosemite)</li>
</ul></li>
<li>Save the file and restart Qt Creator</li>
</ul> |
47,544,109 | Laravel Cannot delete or update a parent row: a foreign key constraint fails | <p>For some reason a user cannot delete a post if it has been liked, it was working before but when I linked posts with likes I have been getting this error, I can't even delete it in Sequel Pro, unless I delete the likes associated with the post first.</p>
<p><strong>Error</strong></p>
<blockquote>
<p>SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
update a parent row: a foreign key constraint fails
(<code>eliapi8</code>.<code>likes</code>, CONSTRAINT <code>likes_post_id_foreign</code> FOREIGN KEY
(<code>post_id</code>) REFERENCES <code>posts</code> (<code>id</code>)) (SQL: delete from <code>posts</code> where
<code>id</code> = 149)</p>
</blockquote>
<p>Maybe it's my schema?</p>
<p><strong>Posts Schema</strong></p>
<pre class="lang-php prettyprint-override"><code>Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
</code></pre>
<p><strong>Likes Schema</strong></p>
<pre class="lang-php prettyprint-override"><code>Schema::create('likes', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->foreign('user_id')->references('id')->on('users');
$table->softDeletes();
$table->timestamps();
});
</code></pre>
<p>I can like and unlike a post, but a user cannot delete a post that has been liked.</p>
<p><strong>PostController.php</strong></p>
<pre class="lang-php prettyprint-override"><code>public function destroy(Post $post){
$this->authorize('delete', $post);
$postl = Post::with('likes')->whereId($post)->delete();
if ($post->delete()) {
if($postl){
return response()->json(['message' => 'deleted']);
}
};
return response()->json(['error' => 'something went wrong'], 400);
}
</code></pre> | 47,544,195 | 4 | 0 | null | 2017-11-29 02:30:58.693 UTC | 6 | 2022-07-17 20:10:57.237 UTC | 2022-07-17 20:10:57.237 UTC | null | 1,255,289 | null | 7,174,241 | null | 1 | 28 | php|mysql|laravel | 87,115 | <p>Yes, it's your schema. The constraint on <code>likes.post_id</code> will prevent you from deleting records from the <code>posts</code> table.</p>
<p>One solution could be using <code>onDelete('cascade')</code> in the <code>likes</code> migration file:</p>
<pre><code>Schema::create('likes', function (Blueprint $table) {
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});
</code></pre>
<p>This way, when a post is deleted, all related likes will be deleted too.</p>
<p>Or, if you have a relationship from the Post model to the Like model, you can <code>$post->likes()->delete()</code> before deleting the post itself.</p> |
6,080,037 | Reference Component could not be found | <p>i'm trying to develop an application but then these warnings popped out. I have tried disabling my anti-virus (Avira) but it still won't work.</p>
<pre><code>Warning 1 Resolved file has a bad image, no metadata, or is otherwise inaccessible. Could not load file or assembly 'MyAssembly.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded. ConsoleApplication1
Warning 2 The referenced component 'MyAssembly' could not be found.
</code></pre>
<p>Can anybody please help me? Thanks!</p> | 6,080,081 | 1 | 2 | null | 2011-05-21 06:25:31.057 UTC | 0 | 2017-11-29 09:50:18.73 UTC | 2011-05-21 09:53:21.383 UTC | null | 184,025 | null | 387,906 | null | 1 | 7 | c#|dll|reference|warnings | 52,499 | <p>What .NET runtime version is your application being developed with? </p>
<p>If the error is to be trusted, your project is say a .NET 3.5 (2.0 runtime) project but the MyAssembly library is developed in .NET 4.0 resulting in the error you see. </p>
<p>You cannot reference newer runtime version assemblies in an older runtime version project. You'd have to "upgrade" your project to at least match the framework version of the assembly given to you.</p>
<p>Right click on your project file and choose properties. Depending on what version of Visual Studio you are using this screen may look different, but go to the application tab and see what the target framework is.</p>
<p><img src="https://i.stack.imgur.com/7Nnkl.png" alt="Project Properties"></p>
<p>Then go to the assembly you referenced in your references and check the "Runtime Version" in the properties section:</p>
<p><img src="https://i.stack.imgur.com/Ovbxc.png" alt="Ref"></p> |
5,614,238 | HTML Gui designer + code generator | <p>Can anyone suggest a good ui designer for html just like there exist glade , qt designer etc ?? </p>
<p>I have searched on the net but have'nt found anything useful .....</p> | 5,614,249 | 2 | 0 | null | 2011-04-10 19:44:23.093 UTC | 1 | 2011-04-10 21:06:57.487 UTC | null | null | null | user506710 | null | null | 1 | 0 | html | 40,250 | <p>This link should help:</p>
<p><a href="http://webdesign.about.com/od/windowshtmleditors/tp/best_windows_html_editors.htm" rel="nofollow">Best HTML Editors</a></p>
<p>Here is a complete list:</p>
<p><a href="http://en.wikipedia.org/wiki/List_of_HTML_editors" rel="nofollow">List of HTML Editors</a></p>
<p>I use mainly visual studio 2010 for my html but I guess if your more geared towards ui you can aim for Expression Web or Adobe Dreamweaver. HTH</p>
<p><strong>I Recommend</strong> you use Visual Studio or Expression Web because they contain a toolbox with drag and drop html and asp.net controls that generate html code. Really you could possibly do everything in design view without ever having to write html code.</p> |
24,728,591 | How to set name of AAR output from Gradle | <p>I have a project with several modules in it one of which is a Android Library named (poorly) as <code>sdk</code>. When I build the project it outputs an AAR named <code>sdk.aar</code>.</p>
<p>I haven't been able to find anything in the Android or Gradle documentation that allows me to change the name of the AAR output. I would like it to have a basename + version number like the Jar tasks do, but I can't work out how to do the same for the AAR because all the config for it seems to be hidden in the android.library plugin.</p>
<p>Renaming the module isn't an option at this stage and that still wouldn't add the version number to the final AAR.</p>
<p>How can I change the name of the AAR generated by <code>com.android.library</code> in Gradle?</p>
<p><strong>Gradle solution</strong></p>
<pre><code>defaultConfig {
minSdkVersion 9
targetSdkVersion 19
versionCode 4
versionName '1.3'
testFunctionalTest true
project.archivesBaseName = "Project name"
project.version = android.defaultConfig.versionName
}
</code></pre> | 26,555,036 | 8 | 0 | null | 2014-07-14 01:53:17.053 UTC | 17 | 2021-08-31 16:40:50.847 UTC | 2014-07-23 23:58:08.937 UTC | null | 250,455 | null | 250,455 | null | 1 | 69 | android|gradle|android-library | 31,031 | <p>As mentioned in comments below and another answer, the original answer here doesn't work with Gradle 3+. Per the <a href="https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#variant_output" rel="noreferrer">docs</a>, something like the following should work:</p>
<blockquote>
<p>Using the Variant API to manipulate variant outputs is broken with the
new plugin. It still works for simple tasks, such as changing the APK
name during build time, as shown below:</p>
</blockquote>
<pre><code>// If you use each() to iterate through the variant objects,
// you need to start using all(). That's because each() iterates
// through only the objects that already exist during configuration time—
// but those object don't exist at configuration time with the new model.
// However, all() adapts to the new model by picking up object as they are
// added during execution.
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${variant.name}-${variant.versionName}.apk"
}
}
</code></pre>
<p><strong>OLD ANSWER:</strong></p>
<p>I am unable to get archivesBaseName & version to work for me w/ <em>Android Studio 0.8.13 / Gradle 2.1</em>. While I can set archivesBaseName and version in my defaultConfig, it doesn't seem to affect the output name. In the end, adding the following <code>libraryVariants</code> block to my android {} scope finally worked for me:</p>
<pre><code>libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${archivesBaseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
</code></pre> |
35,560,894 | Is Docker ARG allowed within CMD instruction | <p>I have a Dockerfile where an <code>ARG</code> is used in the <code>CMD</code> instruction:</p>
<pre><code>ARG MASTER_NAME
CMD spark-submit --deploy-mode client --master ${MASTER_URL}
</code></pre>
<p>The arg is passed via docker-compose:</p>
<pre><code> spark:
build:
context: spark
args:
- MASTER_URL=spark://master:7077
</code></pre>
<p>However, the <code>ARG</code> does not seem to get expanded for <code>CMD</code>. After I <code>docker-compose up</code>.</p>
<p>Here's what inspect shows:</p>
<pre><code>docker inspect -f "{{.Name}} {{.Config.Cmd}}" $(docker ps -a -q)
/spark {[/bin/sh -c spark-submit --deploy-mode client --master ${MASTER_URL}]}
</code></pre> | 35,562,189 | 1 | 0 | null | 2016-02-22 18:15:08.793 UTC | 5 | 2018-12-28 00:10:46.477 UTC | 2018-12-28 00:10:46.477 UTC | null | 745,868 | null | 1,086,117 | null | 1 | 73 | docker|docker-compose | 31,012 | <p>The thing is that <code>args</code> only can be used at build time, and the <code>CMD</code> is executing at run time. I guess that the only approach now to achieve what you want is setting an environment variable in the Dockerfile with the <code>MASTER_NAME</code> value.</p>
<pre><code>ARG MASTER_NAME
ENV MASTER_NAME ${MASTER_NAME}
CMD spark-submit --deploy-mode client --master ${MASTER_NAME}
</code></pre> |
56,802,815 | React hooks: How do I update state on a nested object with useState()? | <p>I have a component that receives a prop that looks like this:</p>
<pre><code>const styles = {
font: {
size: {
value: '22',
unit: 'px'
},
weight: 'bold',
color: '#663300',
family: 'arial',
align: 'center'
}
};
</code></pre>
<p>I'm trying to update the <code>align</code> property, but when I try to update the object, I wind up replacing the whole object with just the <code>align</code> property.</p>
<p>this is how I'm updating it:</p>
<pre><code>const { ...styling } = styles;
const [style, setStyle] = useState(styling);
return (
<RadioButtonGroup
onChange={(event) => {
setStyle({ ...style, font: { align: event.target.value } });
console.log(style);
}}
/>);
</code></pre>
<p>When I console.log <code>style</code> I just get <code>{"font":{"align":"left"}}</code> back.
I expected to see the whole object with the updated value for <code>align</code>. I'm new to destructuring so what am I doing wrong here?</p> | 56,802,862 | 6 | 0 | null | 2019-06-28 07:40:12.553 UTC | 13 | 2020-06-04 17:56:11.773 UTC | null | null | null | null | 1,394,079 | null | 1 | 24 | javascript|reactjs|destructuring | 41,845 | <p>You need to use spread syntax to copy the font object properties too. Also while trying to update current state based on previous, use the callback pattern </p>
<pre><code><RadioButtonGroup
onChange={(event) => {
setStyle(prevStyle => ({
...prevStyle,
font: { ...prevStyle.font, align: event.target.value }
}));
console.log(style);
}}
/>
</code></pre> |
28,630,253 | UIPickerView best practice? | <p>One short question: on a registration process I would like to ask the user to choose a value from a list of values.</p>
<p>Is it the right way to use a view Controller adding there all text fields and for the values a picker view? As the picker view needs so much space in between the text fields area I wonder what the best practice in this case would be? </p>
<p>this is my code so far:</p>
<pre><code>class RegisterViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{
@IBOutlet weak var gradeTextField: UITextField!
@IBOutlet weak var gradePicker: UIPickerView!
let gradePickerValues = ["5. Klasse", "6. Klasse", "7. Klasse"]
func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return gradePickerValues.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return gradePickerValues[row]
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
gradeTextField.text = gradePickerValues[row]
self.view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
statusMessageLabel.hidden = true
gradePicker.dataSource = self
gradePicker.delegate = self
gradePicker.hidden = true
gradeTextField.inputView = UIPickerView()
gradeTextField.text = gradePickerValues[0]
}
</code></pre>
<p>The pickerview is hidden at the beginning and appears only when I select the text field, this is fine so far... But the the picker view is empty...</p>
<p><img src="https://i.stack.imgur.com/RWP0H.png" alt="controller view with open picker view"></p> | 28,630,417 | 2 | 0 | null | 2015-02-20 13:34:38.217 UTC | 10 | 2020-10-12 23:58:53.533 UTC | 2020-10-12 23:58:53.533 UTC | null | 171,933 | null | 1,555,112 | null | 1 | 27 | ios|swift|uipickerview | 55,151 | <p>It depends on controller appearance. If there only one choose action per screen it will be better to put <code>Table View</code> on it and selected row will be current selection.</p>
<p>If screen has multiply fields, that user should act with, then, in my opinion, it's better to put <code>label</code> + <code>button</code> above it and when user press this <code>button</code> you just shows <code>Picker View</code> from screen bottom. When user select any row in <code>Picker View</code> you change label text, but don't hide picker itself, it should be done by pressing "Done" <code>button</code> you place above.</p>
<p>Hope this helps.</p>
<hr>
<p><strong>Update</strong>:</p>
<p>Your problem because you just forget to set <code>dataSource</code> property of <code>UIPickerView</code></p>
<p>Just do: <code>gradePicker.dataSource = self</code> in <code>viewDidLoad()</code></p>
<p>And don't forget to implements protocol here: <code>class RegisterViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource</code></p>
<hr>
<p><strong>Update 2</strong>:</p>
<p>Finally made it. If you add <code>UIPickerView</code> in inputView of your textFiled, then It should NOT be in IB. So you could remove it from storyboard (or .xib, if you use it).</p>
<p>Then change code to be something like this:</p>
<pre><code>class RegisterViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var gradeTextField: UITextField!
var gradePicker: UIPickerView!
let gradePickerValues = ["5. Klasse", "6. Klasse", "7. Klasse"]
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return gradePickerValues.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return gradePickerValues[row]
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
gradeTextField.text = gradePickerValues[row]
self.view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
gradePicker = UIPickerView()
gradePicker.dataSource = self
gradePicker.delegate = self
gradeTextField.inputView = gradePicker
gradeTextField.text = gradePickerValues[0]
}
}
</code></pre> |
23,934,451 | How to read nodejs internal profiler tick-processor output | <p>I'm interested in profiling my Node.js application.
I've started it with <code>--prof</code> flag, and obtained a <code>v8.log</code> file.
I've taken the windows-tick-processor and obtained a supposedly human readable profiling log.
At the bottom of the question are a few a small excerpts from the log file, which I am completely failing to understand.</p>
<p>I get the ticks statistical approach. I don't understand what <code>total</code> vs <code>nonlib</code> means.
Also I don't understand why some things are prefixed with <code>LazyCompile</code>, <code>Function</code>, <code>Stub</code> or other terms.</p>
<p>The best answer I could hope for is the complete documentation/guide to the tick-processor output format, completely explaining every term, structure etc...</p>
<p>Barring that, I just don't understand what lazy-compile is. Is it compilation? Doesn't every function get compiled exactly once? Then how can compilation possibly be a significant part of my application execution? The application ran for hours to produce this log, and I'm assuming the internal JavaScript compilation takes milliseconds.
This suggests that lazy-compile is something that doesn't happen once per function, but happens during some kind of code evaluation? Does this mean that everywhere I've got a function definition (for example a nested function), the internal function gets "lazy-compiled" each time?</p>
<p>I couldn't find any information on this anywhere, and I've been googling for DAYS...</p>
<p>Also I realize there are a lot of profiler flags. Additional references on those are also welcome.</p>
<pre>
[JavaScript]:
ticks total nonlib name
88414 7.9% 20.1% LazyCompile: *getUniqueId C:\n\dev\SCNA\infra\lib\node-js\utils\general-utils.js:16
22797 2.0% 5.2% LazyCompile: *keys native v8natives.js:333
14524 1.3% 3.3% LazyCompile: Socket._flush C:\n\dev\SCNA\runtime-environment\load-generator\node_modules\zmq\lib\index.js:365
12896 1.2% 2.9% LazyCompile: BasicSerializeObject native json.js:244
12346 1.1% 2.8% LazyCompile: BasicJSONSerialize native json.js:274
9327 0.8% 2.1% LazyCompile: * C:\n\dev\SCNA\runtime-environment\load-generator\node_modules\zmq\lib\index.js:194
7606 0.7% 1.7% LazyCompile: *parse native json.js:55
5937 0.5% 1.4% LazyCompile: *split native string.js:554
5138 0.5% 1.2% LazyCompile: *Socket.send C:\n\dev\SCNA\runtime-environment\load-generator\node_modules\zmq\lib\index.js:346
4862 0.4% 1.1% LazyCompile: *sort native array.js:741
4806 0.4% 1.1% LazyCompile: _.each._.forEach C:\n\dev\SCNA\infra\node_modules\underscore\underscore.js:76
4481 0.4% 1.0% LazyCompile: ~_.each._.forEach C:\n\dev\SCNA\infra\node_modules\underscore\underscore.js:76
4296 0.4% 1.0% LazyCompile: stringify native json.js:308
3796 0.3% 0.9% LazyCompile: ~b native v8natives.js:1582
3694 0.3% 0.8% Function: ~recursivePropertiesCollector C:\n\dev\SCNA\infra\lib\node-js\utils\object-utils.js:90
3599 0.3% 0.8% LazyCompile: *BasicSerializeArray native json.js:181
3578 0.3% 0.8% LazyCompile: *Buffer.write buffer.js:315
3157 0.3% 0.7% Stub: CEntryStub
2958 0.3% 0.7% LazyCompile: promise.promiseDispatch C:\n\dev\SCNA\runtime-environment\load-generator\node_modules\q\q.js:516
</pre>
<pre>
88414 7.9% LazyCompile: *getUniqueId C:\n\dev\SCNA\infra\lib\node-js\utils\general-utils.js:16
88404 100.0% LazyCompile: *generateId C:\n\dev\SCNA\infra\lib\node-js\utils\general-utils.js:51
88404 100.0% LazyCompile: *register C:\n\dev\SCNA\infra\lib\node-js\events\pattern-dispatcher.js:72
52703 59.6% LazyCompile: * C:\n\dev\SCNA\runtime-environment\load-generator\lib\vuser-driver\mdrv-driver.js:216
52625 99.9% LazyCompile: *_.each._.forEach C:\n\dev\SCNA\runtime-environment\load-generator\node_modules\underscore\underscore.js:76
52625 100.0% LazyCompile: ~usingEventHandlerMapping C:\n\dev\SCNA\runtime-environment\load-generator\lib\vuser-driver\mdrv-driver.js:214
35555 40.2% LazyCompile: *once C:\n\dev\SCNA\infra\lib\node-js\events\pattern-dispatcher.js:88
29335 82.5% LazyCompile: ~startAction C:\n\dev\SCNA\runtime-environment\load-generator\lib\vuser-driver\mdrv-driver.js:201
25687 87.6% LazyCompile: ~onActionComplete C:\n\dev\SCNA\runtime-environment\load-generator\lib\vuser-driver\mdrv-logic.js:130
1908 6.5% LazyCompile: ~b native v8natives.js:1582
1667 5.7% LazyCompile: _fulfilled C:\n\dev\SCNA\runtime-environment\load-generator\node_modules\q\q.js:795
4645 13.1% LazyCompile: ~terminate C:\n\dev\SCNA\runtime-environment\load-generator\lib\vuser-driver\mdrv-driver.js:160
4645 100.0% LazyCompile: ~terminate C:\n\dev\SCNA\runtime-environment\load-generator\lib\vuser-driver\mdrv-logic.js:171
1047 2.9% LazyCompile: *startAction C:\n\dev\SCNA\runtime-environment\load-generator\lib\vuser-driver\mdrv-driver.js:201
1042 99.5% LazyCompile: ~onActionComplete C:\n\dev\SCNA\runtime-environment\load-generator\lib\vuser-driver\mdrv-logic.js:130
</pre> | 26,834,673 | 1 | 0 | null | 2014-05-29 13:24:18.307 UTC | 9 | 2017-02-14 12:11:43.937 UTC | 2017-02-01 13:26:33.057 UTC | null | 632,907 | null | 1,009,305 | null | 1 | 43 | node.js|profiling|profiler|v8 | 8,224 | <p>Indeed, you are right in your assumption about time actually spent compiling the code: it takes milliseconds (which could be seen with <code>--trace-opt</code> flag).</p>
<p>Now talking about that <code>LazyCompile</code>. Here is a quotation from Vyacheslav Egorov's (former v8 dev) <a href="http://mrale.ph/blog/2011/12/18/v8-optimization-checklist.html" rel="noreferrer">blog</a>:</p>
<blockquote>
<p>If you are using V8's tick processors keep in mind that LazyCompile:
prefix does <strong>not</strong> mean that this time was spent in compiler, it just
means that the function itself was compiled lazily.</p>
</blockquote>
<p>An asterisk before a function name means that time is being spent in optimized function, tilda -- not optimized. </p>
<p>Concerning your question about how many times a function gets compiled. Actually the JIT (so-called full-codegen) creates a non-optimized version of each function when it gets executed for the first time. But later on an arbitrary (well, to some extent) number or recompilations could happen (due to optimizations and bail-outs). But you won't see any of it in this kind of profiling log. </p>
<p><code>Stub</code> prefix to the best of my understanding means the execution was inside a C-Stub, which is a part of runtime and gets compiled along with other parts of the engine (i.e. it is not JIT-compiled JS code).</p>
<p><code>total</code> vs. <code>nonlib</code>:</p>
<p>These columns simply mean than x% of total/non-lib time was spent there. (I can refer you to a discussion <a href="https://groups.google.com/forum/#!topic/nodejs/oRbX5eZvOPg" rel="noreferrer">here</a>).</p>
<p>Also, you can find <a href="https://github.com/v8/v8/wiki/Using%20V8%E2%80%99s%20internal%20profiler" rel="noreferrer">https://github.com/v8/v8/wiki/Using%20V8%E2%80%99s%20internal%20profiler</a> useful.</p> |
22,906,520 | PowerShell string default parameter value does not work as expected | <pre><code>#Requires -Version 2.0
[CmdletBinding()]
Param(
[Parameter()] [string] $MyParam = $null
)
if($MyParam -eq $null) {
Write-Host 'works'
} else {
Write-Host 'does not work'
}
</code></pre>
<p>Outputs "does not work" => looks like strings are converted from null to empty string implicitly? Why? And how to test if a string is empty or really $null? This should be two different values!</p> | 22,906,543 | 5 | 0 | null | 2014-04-07 07:51:18.28 UTC | 3 | 2017-07-19 22:58:51.943 UTC | 2017-02-04 14:41:03.233 UTC | null | 2,413,303 | null | 1,400,869 | null | 1 | 34 | powershell|powershell-4.0 | 60,379 | <p>Okay, found the answer @ <a href="https://www.codykonior.com/2013/10/17/checking-for-null-in-powershell/" rel="noreferrer">https://www.codykonior.com/2013/10/17/checking-for-null-in-powershell/</a></p>
<p>Assuming:</p>
<pre><code>Param(
[string] $stringParam = $null
)
</code></pre>
<p>And the parameter was not specified (is using default value):</p>
<pre><code># will NOT work
if ($null -eq $stringParam)
{
}
# WILL work:
if ($stringParam -eq "" -and $stringParam -eq [String]::Empty)
{
}
</code></pre>
<p>Alternatively, you can specify a special null type:</p>
<pre><code>Param(
[string] $stringParam = [System.Management.Automation.Language.NullString]::Value
)
</code></pre>
<p>In which case the <code>$null -eq $stringParam</code> will work as expected.</p>
<p>Weird!</p> |
41,832,638 | Angular TypeError: Cannot create property on string '' | <p>Trying to clear the input box after Add is clicked, like the guy is doing in <a href="https://youtu.be/iFsYJG3fGro?t=16m37s" rel="noreferrer">this tutorial</a>.<br>
I have recreated the error without using the API, with this short code.<br>
You can also check out the <a href="https://plnkr.co/edit/kKMm7GkkDrDhcLjIaPv2?p=preview" rel="noreferrer">Plunker</a>.</p>
<p><strong>HTML</strong></p>
<pre><code><input ng-model="contact.name" type="text">
<button ng-click="Add()">Add</button>
<ul ng-repeat="contact in contactList">
<li>{{ contact.name }}</li>
</ul>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>$scope.contactList = [
{name: 'cris'}, {name: 'vlad'}
;]
$scope.Add = function() {
$scope.contactList.push($scope.contact)
$scope.contact = ""
}
</code></pre>
<p>It seems that i can add 1 item, but on the second i get this Error:
<a href="https://i.stack.imgur.com/mswUq.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/mswUq.jpg" alt="enter image description here"></a> </p> | 41,832,749 | 2 | 1 | null | 2017-01-24 15:57:57.807 UTC | 2 | 2017-06-03 11:25:00.573 UTC | 2017-06-03 11:25:00.573 UTC | null | 4,927,984 | null | 4,784,262 | null | 1 | 8 | angularjs | 52,503 | <p>You didn't clean your <code>contact</code> object the right way. In the <code>Add()</code> function, change: </p>
<pre><code>$scope.contact = ""
</code></pre>
<p>To:</p>
<pre><code>$scope.contact = {};
</code></pre>
<h2><a href="https://plnkr.co/edit/3v7PMw8Nge80Dh6sZ40h?p=preview" rel="noreferrer">Forked Plunker</a></h2> |
50,404,761 | AWS API Gateway - using Access Token with Cognito User Pool authorizer? | <p>I am configuring an app with various frontends (mobile and web apps) and a single API backend, powered by Lambda and accessed via AWS API Gateway.</p>
<p>As I'm planning to use Cognito to authenticate and authorize users, I have set up a Cognito User Pool authorizer on my API Gateway and several API methods.</p>
<p>With an architecture like this, it seems logical that my apps (e.g. an iOS or Vue.js app) are the Client applications from an OAuth perspective, and my API Gateway backend is a Resource Server. Based on <a href="https://community.auth0.com/t/clarification-on-token-usage/8447/2" rel="noreferrer">this Auth0 forum post</a> it seems clear that I should therefore use an ID token in my client app, and pass an Access Token to authorize my API Gateway resources.</p>
<p>When I hit the Cognito <code>/oauth2/authorize</code> endpoint to get an access code and use that code to hit the <code>/oauth2/token</code> endpoint, I get 3 tokens - an Access Token, an ID Token and a Refresh Token. So far so good, as I should have what I need.</p>
<p>This is where I've run into difficulties - using the test function on the API Gateway Cognito User Pool Authorizer console, I can paste in the ID token and it passes (decoding the token on-screen). But when I paste in the Access Token, I get <code>401 - unauthorized</code>.</p>
<p>In my Cognito setup, I have enabled <code>Authorization Code Grant</code> flow only, with <code>email</code> and <code>openid</code> scopes (this seems to be the minimum allowed by Cognito as I get an error trying to save without at least these ticked).</p>
<p>Do I need to add some specific scopes to get API Gateway to authorize a request with the Access Code? If so, where are these configured?</p>
<p>Or am I missing something? Will API Gateway only allow an ID token to be used with a Cognito User Pool Authorizer?</p> | 50,617,345 | 4 | 0 | null | 2018-05-18 06:06:23.69 UTC | 10 | 2022-09-09 02:13:13.197 UTC | null | null | null | null | 726,221 | null | 1 | 32 | oauth|oauth-2.0|aws-api-gateway|amazon-cognito | 14,838 | <p>You can use an access token with the same authorizer that works for the id token, but there is some additional setup to be done in the User Pool and the APIG.</p>
<p>Even when this extra setup is done you cannot use the built-in authorizer test functionality with an access token, only an id token. Typical 80% solution from AWS!</p>
<p>To use an access token you need to set up resource servers in the User Pool under <code>App Integration -> Resource Servers</code> it doesn't matter what you use but I will assume you use <code><site>.com</code> for the Identifier and you have one scope called <code>api</code>.</p>
<p>No go to the method in APIG and enter the <code>Method Request</code> for the method. Assuming this is already set up with an authorizer tested with the id token, you then add <code><site>.com/api</code> to the <code>Settings -> OAuth Scopes</code> section.</p>
<p>Just by adding the OAuth Scope it will make sure that the token now has to be an access token and an id token is no longer accepted.</p>
<p>This is detailed here: <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html" rel="noreferrer">https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html</a> </p> |
2,740,191 | NSString stringWithFormat | <p>I don't know what I am missing here. I am trying to concatenate strings using <code>[NSString stringWithFormat]</code> function. This is what I am doing.</p>
<pre><code>NSString *category = [row objectForKey:@"category"];
NSString *logonUser = [row objectForKey:@"username"];
user.text = [NSString stringWithFormat:@"In %@ by %@", category, logonUser];
</code></pre>
<p>The problem here is that it always print only one variable. Say if there is "Sports" in category and "Leo" in logonUser it will print "In Sports" and skip the remaining text. It should print "In Sports by Leo".</p> | 2,740,678 | 4 | 1 | null | 2010-04-29 19:26:37.57 UTC | 6 | 2020-06-10 14:38:38.163 UTC | 2015-10-26 09:14:51.12 UTC | null | 2,725,435 | null | 188,671 | null | 1 | 16 | iphone|nsstring|stringwithformat | 63,531 | <p>Is <code>user</code> a UILabel? Make sure that your text isn't wrapping or being clipped. Try making the UILabel bigger.</p> |
2,504,141 | Calendar add() vs roll() when do we use it? | <p>I know <code>add()</code> adds the specified (signed) amount of time to the given time field, based on the calendar's rules.</p>
<p>And <code>roll()</code> adds the specified (signed) single unit of time on the given time field <strong>without changing larger fields.</strong></p>
<p>I can't think of an everyday usage of <code>roll()</code> I would do everything by <code>add()</code>. </p>
<p>Can you help me out with examples when do we use <code>roll()</code> and when <code>add()</code>?</p>
<p><strong>EDIT 1</strong></p>
<p><strong>Joda</strong> answers are not accepted!</p> | 2,504,251 | 4 | 0 | null | 2010-03-23 22:41:47.103 UTC | 10 | 2016-04-07 12:09:37.903 UTC | 2010-03-23 22:46:49.047 UTC | null | 243,782 | null | 243,782 | null | 1 | 52 | java|calendar | 44,126 | <ul>
<li><code>add()</code> - almost always, as you said</li>
<li><code>roll()</code> - for example you want to "dispense" events in one month. The algorithm may be to proceed a number of days and place the event, then proceed further. When the end of the month is reached, it should start over from the beginning. Hence <code>roll()</code>.</li>
</ul> |
56,754,117 | Programmatically navigate to new view in SwiftUI | <p>Descriptive example:</p>
<p>login screen, user taps "Login" button, request is performed, UI shows waiting indicator, then after successful response I'd like to automatically navigate user to the next screen.</p>
<p>How can I achieve such automatic transition in SwiftUI?</p> | 56,756,628 | 7 | 0 | null | 2019-06-25 12:30:39.643 UTC | 11 | 2021-04-02 22:02:21.72 UTC | 2019-11-14 14:14:33.28 UTC | null | 1,033,581 | null | 454,925 | null | 1 | 29 | swift|swiftui | 32,203 | <p>You can replace the next view with your login view after a successful login. For example: </p>
<pre><code>struct LoginView: View {
var body: some View {
...
}
}
struct NextView: View {
var body: some View {
...
}
}
// Your starting view
struct ContentView: View {
@EnvironmentObject var userAuth: UserAuth
var body: some View {
if !userAuth.isLoggedin {
LoginView()
} else {
NextView()
}
}
}
</code></pre>
<p>You should handle your login process in your data model and use bindings such as <code>@EnvironmentObject</code> to pass <code>isLoggedin</code> to your view. </p>
<blockquote>
<p>Note: <em>In Xcode <strong>Version 11.0 beta 4</strong>, to conform to protocol <strong>'BindableObject'</strong> the <a href="https://developer.apple.com/documentation/swiftui/bindableobject/3345089-willchange" rel="noreferrer"><strong>willChange</strong></a> property has to be added</em></p>
</blockquote>
<pre><code>import Combine
class UserAuth: ObservableObject {
let didChange = PassthroughSubject<UserAuth,Never>()
// required to conform to protocol 'ObservableObject'
let willChange = PassthroughSubject<UserAuth,Never>()
func login() {
// login request... on success:
self.isLoggedin = true
}
var isLoggedin = false {
didSet {
didChange.send(self)
}
// willSet {
// willChange.send(self)
// }
}
}
</code></pre> |
28,624,686 | Get 'spawn cmd ENOENT' when try to build Cordova application (event.js:85) | <p>Get this error in windows cmd when I try to build (emulate) Cordova app.</p>
<pre><code>D:\dev\Cordova\toDoList>cordova build android
Running command: D:\dev\Cordova\toDoList\platforms\android\cordova\build.bat
events.js:85
throw er; // Unhandled 'error' event
^
Error: spawn cmd ENOENT
at exports._errnoException (util.js:746:11)
at Process.ChildProcess._handle.onexit (child_process.js:1046:32)
at child_process.js:1137:20
at process._tickCallback (node.js:355:11)
ERROR building one of the platforms: Error: D:\dev\Cordova\toDoList\platforms\android\cordova\build.bat: Command failed with exit code 1
You may not have the required environment or OS to build this project
</code></pre> | 28,626,189 | 5 | 0 | null | 2015-02-20 08:38:35.113 UTC | 9 | 2020-09-13 15:40:27.28 UTC | 2015-05-25 09:46:25.2 UTC | null | 3,877,938 | null | 3,877,938 | null | 1 | 34 | node.js|cordova|cmd|spawn | 63,405 | <p>I checked system variables one more time and found the cause of the problem:
missing <code>C:\Windows\System32\</code> variable.
I added it and that solved my problem</p>
<p>Hope, it help you too.</p> |
37,463,226 | Using repository pattern to eager load entities using ThenIclude | <p>My application uses Entity Framework 7 and the repository pattern.</p>
<p>The GetById method on the repository supports eager loading of child entities:</p>
<pre><code>public virtual TEntity GetById(int id, params Expression<Func<TEntity, object>>[] paths)
{
var result = this.Set.Include(paths.First());
foreach (var path in paths.Skip(1))
{
result = result.Include(path);
}
return result.FirstOrDefault(e => e.Id == id);
}
</code></pre>
<p>Usage is as follows to retrieve a product (whose id is 2) along with the orders and the parts associated with that product:</p>
<pre><code>productRepository.GetById(2, p => p.Orders, p => p.Parts);
</code></pre>
<p>I want to enhance this method to support eager loading of entities nested deeper than one level. For example suppose an <code>Order</code> has its own collection of <code>LineItem</code>'s.</p>
<p>Prior to EF7 I believe the following would have been possible to also retrieve the LineItems associated with each order:</p>
<pre><code>productRepository.GetById(2, p => p.Orders.Select(o => o.LineItems), p => p.Parts);
</code></pre>
<p>However this doesn't appear to be supported in EF7. Instead there is a new ThenInclude method that retrieves additional levels of nested entities:</p>
<p><a href="https://github.com/aspnet/EntityFramework/wiki/Design-Meeting-Notes:-January-8,-2015" rel="nofollow noreferrer">https://github.com/aspnet/EntityFramework/wiki/Design-Meeting-Notes:-January-8,-2015</a></p>
<p>I am unsure as to how to update my repository to support retrieval of multiple-levels of eager loaded entities using <code>ThenInclude</code>.</p> | 43,928,098 | 2 | 0 | null | 2016-05-26 14:06:23.893 UTC | 10 | 2020-09-10 11:08:54.377 UTC | 2020-09-10 11:08:54.377 UTC | null | 10,758,800 | null | 4,061,307 | null | 1 | 15 | c#|entity-framework|repository-pattern|eager-loading|entity-framework-core | 6,824 | <p>This is a bit of an old question, but since it doesn't have an accepted answer I thought I'd post my solution to this.</p>
<p>I'm using EF Core and wanted to do exactly this, access eager loading from outside my repository class so I can specify the navigation properties to load each time I call a repository method. Since I have a large number of tables and data I didn't want a standard set of eagerly loading entities since some of my queries only needed the parent entity and some needed the whole tree.</p>
<p>My current implementation only supports <code>IQueryable</code> method (ie. <code>FirstOrDefault</code>, <code>Where</code>, basically the standard lambda functions) but I'm sure you could use it to pass through to your specific repository methods.</p>
<p>I started with the source code for EF Core's <a href="https://github.com/aspnet/EntityFramework/blob/b6897b01fc19f0119216aca78c9911f5882cc792/src/EFCore/EntityFrameworkQueryableExtensions.cs" rel="noreferrer"><code>EntityFrameworkQueryableExtensions.cs</code></a> which is where the <code>Include</code> and <code>ThenInclude</code> extension methods are defined. Unfortunately, EF uses an internal class <code>IncludableQueryable</code> to hold the tree of previous properties to allow for strongly type later includes. However, the implementation for this is nothing more than <code>IQueryable</code> with an extra generic type for the previous entity.</p>
<p>I created my own version I called <code>IncludableJoin</code> that takes an <code>IIncludableQueryable</code> as a constructor parameter and stores it in a private field for later access:</p>
<pre><code>public interface IIncludableJoin<out TEntity, out TProperty> : IQueryable<TEntity>
{
}
public class IncludableJoin<TEntity, TPreviousProperty> : IIncludableJoin<TEntity, TPreviousProperty>
{
private readonly IIncludableQueryable<TEntity, TPreviousProperty> _query;
public IncludableJoin(IIncludableQueryable<TEntity, TPreviousProperty> query)
{
_query = query;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<TEntity> GetEnumerator()
{
return _query.GetEnumerator();
}
public Expression Expression => _query.Expression;
public Type ElementType => _query.ElementType;
public IQueryProvider Provider => _query.Provider;
internal IIncludableQueryable<TEntity, TPreviousProperty> GetQuery()
{
return _query;
}
}
</code></pre>
<p>Note the internal <code>GetQuery</code> method. This will be important later.</p>
<p>Next, in my generic <code>IRepository</code> interface, I defined the starting point for eager loading:</p>
<pre><code>public interface IRepository<TEntity> where TEntity : class
{
IIncludableJoin<TEntity, TProperty> Join<TProperty>(Expression<Func<TEntity, TProperty>> navigationProperty);
...
}
</code></pre>
<p>The <code>TEntity</code> generic type is the <strong>interface</strong> of my EF entity. The implmentation of the <code>Join</code> method in my generic repository is like so:</p>
<pre><code>public abstract class SecureRepository<TInterface, TEntity> : IRepository<TInterface>
where TEntity : class, new()
where TInterface : class
{
protected DbSet<TEntity> DbSet;
protected SecureRepository(DataContext dataContext)
{
DbSet = dataContext.Set<TEntity>();
}
public virtual IIncludableJoin<TInterface, TProperty> Join<TProperty>(Expression<Func<TInterface, TProperty>> navigationProperty)
{
return ((IQueryable<TInterface>)DbSet).Join(navigationProperty);
}
...
}
</code></pre>
<p>Now for the part that actually allows for multiple <code>Include</code> and <code>ThenInclude</code>. I have several extension methods that take and return and <code>IIncludableJoin</code> to allow for method chaining. Inside which I call the EF <code>Include</code> and <code>ThenInclude</code> methods on the DbSet:</p>
<pre><code>public static class RepositoryExtensions
{
public static IIncludableJoin<TEntity, TProperty> Join<TEntity, TProperty>(
this IQueryable<TEntity> query,
Expression<Func<TEntity, TProperty>> propToExpand)
where TEntity : class
{
return new IncludableJoin<TEntity, TProperty>(query.Include(propToExpand));
}
public static IIncludableJoin<TEntity, TProperty> ThenJoin<TEntity, TPreviousProperty, TProperty>(
this IIncludableJoin<TEntity, TPreviousProperty> query,
Expression<Func<TPreviousProperty, TProperty>> propToExpand)
where TEntity : class
{
IIncludableQueryable<TEntity, TPreviousProperty> queryable = ((IncludableJoin<TEntity, TPreviousProperty>)query).GetQuery();
return new IncludableJoin<TEntity, TProperty>(queryable.ThenInclude(propToExpand));
}
public static IIncludableJoin<TEntity, TProperty> ThenJoin<TEntity, TPreviousProperty, TProperty>(
this IIncludableJoin<TEntity, IEnumerable<TPreviousProperty>> query,
Expression<Func<TPreviousProperty, TProperty>> propToExpand)
where TEntity : class
{
var queryable = ((IncludableJoin<TEntity, IEnumerable<TPreviousProperty>>)query).GetQuery();
var include = queryable.ThenInclude(propToExpand);
return new IncludableJoin<TEntity, TProperty>(include);
}
}
</code></pre>
<p>In these methods I am getting the internal <code>IIncludableQueryable</code> property using the aforementioned <code>GetQuery</code> method, calling the relevant <code>Include</code> or <code>ThenInclude</code> method, then returning a new <code>IncludableJoin</code> object to support the method chaining.</p>
<p>And that's it. The usage of this is like so:</p>
<pre><code>IAccount account = _accountRepository.Join(x=>x.Subscription).Join(x=>x.Addresses).ThenJoin(x=>x.Address).FirstOrDefault(x => x.UserId == userId);
</code></pre>
<p>The above would load the base <code>Account</code> entity, it's one-to-one child <code>Subscription</code>, it's one-to-many child list <code>Addresses</code> and it's child <code>Address</code>. Each lambda function along the way is strongly typed and is supported by intellisense to show the properties available on each entity.</p> |
38,242,462 | Internet check, where to place when using MVP, RX and Retrofit | <p>I have went through <a href="https://stackoverflow.com/questions/37589008/android-internet-check-layer">this</a> and <a href="https://stackoverflow.com/questions/37007994/android-mvp-where-check-internet-connection#">this</a> post. So I really agree with the second post that presenter should not be aware of android specific thing. So what I am thinking is putting internet check in service layer.
I am using Rx Java for making network calls, so I can either place the network check before making a service call, so this way I need to manually throw and IOException because I need to show an error page on view when network is not available, the other option is I create my own error class for no internet</p>
<pre><code>Observable<PaginationResponse<Notification>> response = Observable.create(new Observable.OnSubscribe<PaginationResponse<Notification>>() {
@Override
public void call(Subscriber<? super PaginationResponse<Notification>> subscriber) {
if (isNetworkConnected()) {
Call<List<Notification>> call = mService.getNotifications();
try {
Response<List<Notification>> response = call.execute();
processPaginationResponse(subscriber, response);
} catch (IOException e) {
e.printStackTrace();
subscriber.onError(e);
}
} else {
//This is I am adding manually
subscriber.onError(new IOException);
}
subscriber.onCompleted();
}
});
</code></pre>
<p>The other way I though of is adding interceptor to OkHttpClient and set it to retrofit</p>
<pre><code>OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
if (!isNetworkConnected()) {
throw new IOException();
}
final Request.Builder builder = chain.request().newBuilder();
Request request = builder.build();
return chain.proceed(request);
}
});
</code></pre>
<p>Now the 2nd approach is more scalable, but I am not sure it will be efficient as I would be unnecessarily calling service method and call.execute() method.</p>
<p>Any suggestion which way should be used?
Also my parameter for judging the way is</p>
<ul>
<li><p>Efficiency</p></li>
<li><p>Scalability</p></li>
<li><p>Generic : I want this same logic can be used across apps who are following the similar architecture where MVP and Repository/DataProvider (May give data from network/db)</p></li>
</ul>
<p><strong>Other suggestions are also welcome, if you people are already using any other way.</strong></p> | 38,281,335 | 1 | 0 | null | 2016-07-07 09:52:57.927 UTC | 9 | 2017-08-20 08:15:41.163 UTC | 2017-05-23 12:10:39.227 UTC | null | -1 | null | 1,651,286 | null | 1 | 11 | android|architecture|rx-java|mvp|retrofit2 | 5,848 | <p>First we create a utility for checking internet connection, there are two ways we can create this utility, one where the utility emits the status only once, which looks like this, </p>
<pre><code>public class InternetConnection {
public static Observable<Boolean> isInternetOn(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return Observable.just(activeNetworkInfo != null && activeNetworkInfo.isConnected());
}
}
</code></pre>
<p>Other way of creating this utility is, where the utility keeps emitting the connection status if it changes, which looks like this,</p>
<pre><code>public class InternetConnection {
public Observable<Boolean> isInternetOn(Context context) {
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
return Observable.create(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(final Subscriber<? super Boolean> subscriber) {
final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
subscriber.onNext(netInfo != null && netInfo.isConnected());
}
};
context.registerReceiver(receiver, filter);
subscriber.add(unsubscribeInUiThread(() -> context.unregisterReceiver(receiver)));
}
}).defaultIfEmpty(false);
}
private Subscription unsubscribeInUiThread(final Action0 unsubscribe) {
return Subscriptions.create(() -> {
if (Looper.getMainLooper() == Looper.myLooper()) {
unsubscribe.call();
} else {
final Scheduler.Worker inner = AndroidSchedulers.mainThread().createWorker();
inner.schedule(() -> {
unsubscribe.call();
inner.unsubscribe();
});
}
});
}
}
</code></pre>
<p>Next, in your dataSource or Presenter use switchMap or flatMap to check for internet connection before doing any network operation which looks like this,</p>
<pre><code>private Observable<List<GitHubUser>> getGitHubUsersFromRetrofit() {
return isInternetOn(context)
.filter(connectionStatus -> connectionStatus)
.switchMap(connectionStatus -> gitHubApiInterface.getGitHubUsersList()
.map(gitHubUserList -> {
gitHubUserDao.storeOrUpdateGitHubUserList(gitHubUserList);
return gitHubUserList;
}));
}
</code></pre>
<p>Note that, we are using switchMap instead of flatMap. why switchMap? because, we have 2 data stream here, first is internet connection and second is Retrofit. first we will take connection status value (true/false), if we have active connection, we will create a new Retrofit stream and return start getting results, down the line if we the status of the connection changes, switchMap will first stop the existing Retrofit connection and then decide if we need to start a new one or ignore it.</p>
<p>EDIT:
This is one of the sample, which might give better clarity <a href="https://github.com/viraj49/Realm_android-injection-rx-test/blob/master/app-safeIntegration/src/main/java/tank/viraj/realm/dataSource/GitHubUserListDataSource.java" rel="noreferrer">https://github.com/viraj49/Realm_android-injection-rx-test/blob/master/app-safeIntegration/src/main/java/tank/viraj/realm/dataSource/GitHubUserListDataSource.java</a></p>
<p>EDIT2:</p>
<p>So you mean switch map will try it itself once internet is back? </p>
<p>Yes and No, let's first see the difference between flatMap & switchMap. Let's say we have an editText and we search some info from network based on what user types, every time user adds a new character we have to make a new query (which can be reduced with debounce), now with so many network calls only the latest results are useful, with <strong>flatMap</strong> we will receive all the results from all the calls we made to the network, with <strong>switchMap</strong> on the other hand, the moment we make a query, all previous calls are discarded.</p>
<p>Now the solution here is made of 2 parts, </p>
<ol>
<li><p>We need an Observable that keeps emitting current state of Network, the first InternetConnection above sends the status once and calls onComplete(), but the second one has a Broadcast receiver and it will keep sending onNext() when network status changes. IF you need to make a reactive solution go for case-2</p></li>
<li><p>Let's say you choose InternetConnection case-2, in this case use switchMap(), cause when network status changes, we need to stop Retrofit from whatever it is doing and then based on the status of network either make a new call or don't make a call.</p></li>
</ol>
<p>How do I let my view know that the error is internet one also will this be scalable because I need to do with every network call, any suggestions regarding writing a wrapper?</p>
<p>Writing a wrapper would be excellent choice, you can create your own custom response which can take multiple entries from a set of possible responses e.g. SUCCESS_INTERNET, SUCCESS_LOGIN, ERROR_INVALID_ID</p>
<p>EDIT3: Please find an updated InternetConnectionUtil here <a href="https://github.com/viraj49/Realm_android-injection-rx-test/blob/master/app-safeIntegration/src/main/java/tank/viraj/realm/util/InternetConnection.java" rel="noreferrer">https://github.com/viraj49/Realm_android-injection-rx-test/blob/master/app-safeIntegration/src/main/java/tank/viraj/realm/util/InternetConnection.java</a></p>
<p>More detail on the same topic is here: <a href="https://medium.com/@Viraj.Tank/android-mvp-that-survives-view-life-cycle-configuration-internet-changes-part-2-6b1e2b5c5294" rel="noreferrer">https://medium.com/@Viraj.Tank/android-mvp-that-survives-view-life-cycle-configuration-internet-changes-part-2-6b1e2b5c5294</a></p>
<p>EDIT4: I have recently created an Internet utility using Android Architecture Components - LiveData, you can find full source code here,
<a href="https://github.com/viraj49/Internet-Utitliy-using-AAC-LiveData" rel="noreferrer">https://github.com/viraj49/Internet-Utitliy-using-AAC-LiveData</a></p>
<p>A detailed description of the code is here,
<a href="https://medium.com/@Viraj.Tank/internet-utility-using-android-architecture-components-livedata-e828a0fcd3db" rel="noreferrer">https://medium.com/@Viraj.Tank/internet-utility-using-android-architecture-components-livedata-e828a0fcd3db</a></p> |
159,456 | Pivot Table and Concatenate Columns | <p>I have a database in the following format:</p>
<pre><code> ID TYPE SUBTYPE COUNT MONTH
1 A Z 1 7/1/2008
1 A Z 3 7/1/2008
2 B C 2 7/2/2008
1 A Z 3 7/2/2008
</code></pre>
<p>Can I use SQL to convert it into this:</p>
<pre><code>ID A_Z B_C MONTH
1 4 0 7/1/2008
2 0 2 7/2/2008
1 0 3 7/2/2008
</code></pre>
<p>So, the <code>TYPE</code>, <code>SUBTYPE</code> are concatenated into new columns and <code>COUNT</code> is summed where the <code>ID</code> and <code>MONTH</code> match.</p>
<p>Any tips would be appreciated. Is this possible in SQL or should I program it manually?</p>
<p>The database is SQL Server 2005. </p>
<p>Assume there are 100s of <code>TYPES</code> and <code>SUBTYPES</code> so and 'A' and 'Z' shouldn't be hard coded but generated dynamically.</p> | 159,803 | 2 | 0 | null | 2008-10-01 20:03:57.72 UTC | 9 | 2012-01-02 16:14:55.747 UTC | 2012-01-02 16:14:55.747 UTC | Brandon | 722,783 | Brandon | 23,133 | null | 1 | 15 | sql|sql-server|database|pivot | 23,288 | <p>SQL Server 2005 offers a very useful PIVOT and UNPIVOT operator which allow you to make this code maintenance-free using PIVOT and some code generation/dynamic SQL</p>
<pre><code>/*
CREATE TABLE [dbo].[stackoverflow_159456](
[ID] [int] NOT NULL,
[TYPE] [char](1) NOT NULL,
[SUBTYPE] [char](1) NOT NULL,
[COUNT] [int] NOT NULL,
[MONTH] [datetime] NOT NULL
) ON [PRIMARY]
*/
DECLARE @sql AS varchar(max)
DECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique
DECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique
SELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + PIVOT_CODE + ']'
,@select_list = COALESCE(@select_list + ', ', '') + 'ISNULL([' + PIVOT_CODE + '], 0) AS [' + PIVOT_CODE + ']'
FROM (
SELECT DISTINCT [TYPE] + '_' + SUBTYPE AS PIVOT_CODE
FROM stackoverflow_159456
) AS PIVOT_CODES
SET @sql = '
;WITH p AS (
SELECT ID, [MONTH], [TYPE] + ''_'' + SUBTYPE AS PIVOT_CODE, SUM([COUNT]) AS [COUNT]
FROM stackoverflow_159456
GROUP BY ID, [MONTH], [TYPE] + ''_'' + SUBTYPE
)
SELECT ID, [MONTH], ' + @select_list + '
FROM p
PIVOT (
SUM([COUNT])
FOR PIVOT_CODE IN (
' + @pivot_list + '
)
) AS pvt
'
EXEC (@sql)
</code></pre> |
1,290,576 | How to calculate a monthly average when the month is not finished | <p>Let's say I have a 12 cells on column A with the sales for each month last year. To calculate a monthly I can do a simple formula like this in A13 =sum(A1:A12)/12. But in column B I have the sales for this year, not a complete year, and August is not finished, but I have the running amount of sales for this month, so far. What kind of formula can I use to return a more accurate average?</p>
<p>Eduardo</p> | 1,290,587 | 3 | 1 | null | 2009-08-17 21:32:04.987 UTC | 1 | 2014-11-12 21:32:29.473 UTC | null | null | null | null | 147,493 | null | 1 | 0 | excel|formula|average | 84,575 | <p>Divide the current total by the total number of days in the month that have passed so far. Then multiply by the total number of days in the month.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.