text:
Q: Is it guaranteed that pthread_cond_signal will wake up a waiting thread? This is a general question. For example, currently two child threads have called pthread_cond_wait(&cond1,&mutex), and they are both waiting. Then, the parent thread calls
pthread_cond_signal(&cond1);
pthread_cond_signal(&cond1);

Next, my question is, is it guaranteed that both of the two waiting threads will get woken up?(Suppose the first thread woken up releases mutex later at certain stage of execution so that the second thread can acquire it).
The reason for me to ask this question is because, for the Unix system level signal, the signal (say SIGCHLD) is not queued so that multiple signal of same type may be lost if they are delivered consecutively. So I wonder is pthread_cond_signal implemented differently so that they will not get lost if the scheduler happen to let the parent thread signal twice in a row?

A: The quick answer:
pthread_cond_signal() will wake up at least one of the threads that is blocked on the condition variable - but more than that is not guaranteed (for reference, use pthread_cond_broadcast() to wake up all blocked threads).
From here:

The pthread_cond_signal() call unblocks at least one of the threads
  that are blocked on the specified condition variable cond (if any
  threads are blocked on cond).
The pthread_cond_broadcast() call unblocks all threads currently
  blocked on the specified condition variable cond.

The longer answer:
So, according to the specification, I'd presume the unblocking to happen synchronously, that is, a thread that has been unblocked by the first call to pthread_cond_signal() will be seen as unblocked by the second call to pthread_cond_signal(), and thus the other thread will be waken up.
However, I do not know whether this is the case for your specific pthread implementation or not (and the glibc website is pretty dodgy at the moment, so can't get access to code to look at).
The probably-not-yet-implemented-but-it-is-in-the-specification answer:
It should be noted though, that the specification recently got slightly reworded regarding how the pthread_cond_signal() and pthread_cond_broadcast() determine which threads are actually blocked on a given condition variable, but I presume that not all implementations have caught up yet.
A long discussion on the subject can be found here, with the new specification being:

The pthread_cond_broadcast() and pthread_cond_signal() functions
  shall atomically determine which threads, if any, are blocked
  on the specified condition variable cond. This determination
  shall occur at an unspecified time during the
  pthread_cond_broadcast() or pthread_cond_signal() call.
  The pthread_cond_broadcast() function shall then unblock all of
  these threads. The pthread_cond_signal() function shall unblock at
  least one of these threads.

So, the conclusion:
Without being an expert interpreter of specifications, I'd say that the new text supports the assumption of this happening synchronously - so that two consecutive calls to pthread_cond_signal() with two blocked threads available, will wake up both threads.
I'm not 100% sure on this though, so if anyone can elaborate, feel free to do so.

A: Looking at the pthread_cond_signal() implementation, there is a comment briefly explaining what the code does:

Load the waiter sequence number, which represents our relative ordering to any waiters.  Relaxed MO is sufficient for that because:

*

*We can pick any position that is allowed by external happens-before constraints.  In particular, if another __pthread_cond_wait call happened before us, this waiter must be eligible for being woken by us.  The only way do establish such a happens-before is by signaling while having acquired the mutex associated with the condvar and ensuring that the signal's critical section happens after the waiter.  Thus, the mutex ensures that we see that waiter's __wseq increase.

*Once we pick a position, we do not need to communicate this to the program via a happens-before that we set up: First, any wake-up could be a spurious wake-up, so the program must not interpret a wake-up as an indication that the waiter happened before a particular signal; second, a program cannot detect whether a waiter has not yet been woken (i.e., it cannot distinguish between a non-woken waiter and one that has been woken but hasn't resumed execution yet), and thus it cannot try to deduce that a signal happened before a particular waiter.

As mentioned, there is more information about the algorithm in the pthread_cond_wait() implementation:

This condvar implementation guarantees that all calls to signal and broadcast and all of the three virtually atomic parts of each call to wait (i.e., (1) releasing the mutex and blocking, (2) unblocking, and (3) re- acquiring the mutex) happen in some total order that is consistent with the happens-before relations in the calling program.  However, this order does not necessarily result in additional happens-before relations being established (which aligns well with spurious wake-ups being allowed).
All waiters acquire a certain position in a 64b waiter sequence (__wseq).  This sequence determines which waiters are allowed to consume signals.  A broadcast is equal to sending as many signals as are unblocked waiters.  When a signal arrives, it samples the current value of __wseq with a relaxed-MO load (i.e., the position the next waiter would get).  (This is sufficient because it is consistent with happens-before; the caller can enforce stronger ordering constraints by calling signal while holding the mutex.)  Only waiters with a position less than the __wseq value observed by the signal are eligible to consume this signal.
This would be straight-forward to implement if waiters would just spin but we need to let them block using futexes.  Futexes give no guarantee of waking in FIFO order, so we cannot reliably wake eligible waiters if we just use a single futex.  Also, futex words are 32b in size, but we need to distinguish more than 1<<32 states because we need to represent the order of wake-up (and thus which waiters are eligible to consume signals); blocking in a futex is not atomic with a waiter determining its position in the waiter sequence, so we need the futex word to reliably notify waiters that they should not attempt to block anymore because they have been already signaled in the meantime.  While an ABA issue on a 32b value will be rare, ignoring it when we are aware of it is not the right thing to do either.
Therefore, we use a 64b counter to represent the waiter sequence (on architectures which only support 32b atomics, we use a few bits less).  To deal with the blocking using futexes, we maintain two groups of waiters:

*

*Group G1 consists of waiters that are all eligible to consume signals; incoming signals will always signal waiters in this group until all waiters in G1 have been signaled.

*Group G2 consists of waiters that arrive when a G1 is present and still contains waiters that have not been signaled.  When all waiters in G1 are signaled and a new signal arrives, the new signal will convert G2 into the new G1 and create a new G2 for future waiters.

We cannot allocate new memory because of process-shared condvars, so we have just two slots of groups that change their role between G1 and G2.  Each has a separate futex word, a number of signals available for consumption, a size (number of waiters in the group that have not been signaled), and a reference count.
The group reference count is used to maintain the number of waiters that are using the group's futex.  Before a group can change its role, the reference count must show that no waiters are using the futex anymore; this prevents ABA issues on the futex word.
To represent which intervals in the waiter sequence the groups cover (and thus also which group slot contains G1 or G2), we use a 64b counter to designate the start position of G1 (inclusive), and a single bit in the waiter sequence counter to represent which group slot currently contains G2.  This allows us to switch group roles atomically wrt. waiters obtaining a position in the waiter sequence.  The G1 start position allows waiters to figure out whether they are in a group that has already been completely signaled (i.e., if the current G1 starts at a later position that the waiter's position).  Waiters cannot determine whether they are currently in G2 or G1 -- but they do not have too because all they are interested in is whether there are available signals, and they always start in G2 (whose group slot they know because of the bit in the waiter sequence.  Signalers will simply fill the right group until it is completely signaled and can be closed (they do not switch group roles until they really have to to decrease the likelihood of having to wait for waiters still holding a reference on the now-closed G1).
Signalers maintain the initial size of G1 to be able to determine where G2 starts (G2 is always open-ended until it becomes G1).  They track the remaining size of a group; when waiters cancel waiting (due to PThreads cancellation or timeouts), they will decrease this remaining size as well.
To implement condvar destruction requirements (i.e., that pthread_cond_destroy can be called as soon as all waiters have been signaled), waiters increment a reference count before starting to wait and decrement it after they stopped waiting but right before they acquire the mutex associated with the condvar.
pthread_cond_t thus consists of the following (bits that are used for flags and are not part of the primary value of each field but necessary to make some things atomic or because there was no space for them elsewhere in the data structure):
__wseq: Waiter sequence counter

*

*LSB is index of current G2.

*Waiters fetch-add while having acquire the mutex associated with the condvar.  Signalers load it and fetch-xor it concurrently.
__g1_start: Starting position of G1 (inclusive)

*LSB is index of current G2.

*Modified by signalers while having acquired the condvar-internal lock and observed concurrently by waiters.
__g1_orig_size: Initial size of G1

*The two least-significant bits represent the condvar-internal lock.

*Only accessed while having acquired the condvar-internal lock.
__wrefs: Waiter reference counter.

*Bit 2 is true if waiters should run futex_wake when they remove the last reference.  pthread_cond_destroy uses this as futex word.

*Bit 1 is the clock ID (0 == CLOCK_REALTIME, 1 == CLOCK_MONOTONIC).

*Bit 0 is true iff this is a process-shared condvar.

*Simple reference count used by both waiters and pthread_cond_destroy.  (If the format of __wrefs is changed, update nptl_lock_constants.pysym and the pretty printers.)
For each of the two groups, we have:
__g_refs: Futex waiter reference count.

*LSB is true if waiters should run futex_wake when they remove the last reference.

*Reference count used by waiters concurrently with signalers that have acquired the condvar-internal lock.
__g_signals: The number of signals that can still be consumed.

*Used as a futex word by waiters.  Used concurrently by waiters and signalers.

*LSB is true iff this group has been completely signaled (i.e., it is closed).
__g_size: Waiters remaining in this group (i.e., which have not been
signaled yet.

*Accessed by signalers and waiters that cancel waiting (both do so only when having acquired the condvar-internal lock.

*The size of G2 is always zero because it cannot be determined until the group becomes G1.

*Although this is of unsigned type, we rely on using unsigned overflow rules to make this hold effectively negative values too (in particular, when waiters in G2 cancel waiting).

A PTHREAD_COND_INITIALIZER condvar has all fields set to zero, which yields a condvar that has G2 starting at position 0 and a G1 that is closed.
Because waiters do not claim ownership of a group right when obtaining a position in __wseq but only reference count the group when using futexes to block, it can happen that a group gets closed before a waiter can increment the reference count.  Therefore, waiters have to check whether their group is already closed using __g1_start.  They also have to perform this check when spinning when trying to grab a signal from __g_signals.  Note that for these checks, using relaxed MO to load __g1_start is sufficient because if a waiter can see a sufficiently large value, it could have also consume a signal in the waiters group.
Waiters try to grab a signal from __g_signals without holding a reference count, which can lead to stealing a signal from a more recent group after their own group was already closed.  They cannot always detect whether they in fact did because they do not know when they stole, but they can conservatively add a signal back to the group they stole from; if they did so unnecessarily, all that happens is a spurious wake-up.  To make this even less likely, __g1_start contains the index of the current g2 too, which allows waiters to check if there aliasing on the group slots; if there wasn't, they didn't steal from the current G1, which means that the G1 they stole from must have been already closed and they do not need to fix anything.
It is essential that the last field in pthread_cond_t is __g_signals[1]: The previous condvar used a pointer-sized field in pthread_cond_t, so a PTHREAD_COND_INITIALIZER from that condvar implementation might only initialize 4 bytes to zero instead of the 8 bytes we need (i.e., 44 bytes in total instead of the 48 we need).  __g_signals[1] is not accessed before the first group switch (G2 starts at index 0), which will set its value to zero after a harmless fetch-or whose return value is ignored.  This effectively completes initialization.
Limitations:

*

*This condvar isn't designed to allow for more than __PTHREAD_COND_MAX_GROUP_SIZE * (1 << 31) calls to __pthread_cond_wait.

*More than __PTHREAD_COND_MAX_GROUP_SIZE concurrent waiters are not supported.

*Beyond what is allowed as errors by POSIX or documented, we can also return the following errors:

*

*EPERM if MUTEX is a recursive mutex and the caller doesn't own it.

*EOWNERDEAD or ENOTRECOVERABLE when using robust mutexes.  Unlike for other errors, this can happen when we re-acquire the mutex; this isn't allowed by POSIX (which requires all errors to virtually happen before we release the mutex or change the condvar state), but there's nothing we can do really.

*When using PTHREAD_MUTEX_PP_* mutexes, we can also return all errors returned by __pthread_tpp_change_priority.  We will already have released the mutex in such cases, so the caller cannot expect to own MUTEX.

Other notes:

*

*Instead of the normal mutex unlock / lock functions, we use __pthread_mutex_unlock_usercnt(m, 0) / __pthread_mutex_cond_lock(m) because those will not change the mutex-internal users count, so that it can be detected when a condvar is still associated with a particular mutex because there is a waiter blocked on this condvar using this mutex.

From that documentation we learn you can call the pthread_cond_signal() and pthread_cond_broadcast() from anywhere. If you call these functions from outside a lock, then you don't have a very strong guarantee other than:

*

*The pthread_cond_signal() will wake up at least one thread, but if two calls get there simultaneously, then the same thread could be picked up twice.

*The pthread_cond_broadcast() will wake up all the threads, no matter what.

However, if you are using a mutex and calling the pthread_cond_signal() from within the locked area, then it will wake up one thread per call. (Note, however, that all your pthread_cond_signal() should be protected.)
So the following code would be considered safe:
pthread_mutex_lock(mutex);
...
pthread_cond_signal(cond1);    // no mutex reference, these calls could happen
pthread_cond_signal(cond1);    // while the mutex is not locked...
pthread_cond_unlock(mutex);

And the wait also using a lock:
pthread_mutex_lock(mutex);
...
pthread_cond_wait(cond1, mutex);
...
pthread_mutex_unlock(mutex);

Since we're using a mutex which is locked, the signal & the wait are internally processed sequentially and thus it works exactly as expected.
There are limits, though, but probably nothing we can ever really reach in a normal app. For example __PTHREAD_COND_MAX_GROUP_SIZE which represents the maximum number of waiters and is a crazy large number:
#define __PTHREAD_COND_MAX_GROUP_SIZE ((unsigned) 1 << 29)

A: I know this is an old thread (no pun intended), but a typical implementations works like this:
A condition variable will have within it a queue of threads which are currently asleep, waiting for it to get signalled.
A lock will have a queue of threads which have been put to sleep because they attempted to acquire it but it was held by another thread.
cond_wait adds the running thread to the condition variable's queue, releases the lock, and puts itself to sleep.
cond_signal simply moves one sleeping thread from the queue of the condition variable to the queue of the lock.
When the running thread releases the lock, a sleeping thread is removed from the lock's queue, ownership of the lock is transferred to that sleeping thread, and that sleeping thread is woken up.
Don't ask my why the spec says that a cond_signal might wake up more than one thread...


text:
Q: Designing L-System data structures (C++) I'm trying to design data structure for an implementation of L-System rewriting engine in C++ and I just can't seem to get anywhere :(.
I need to store a string of symbols (characters). There are be several types of symbols (that's specified by the LSystem's alphabet). Let's say we have types "A", "B", "C". Now each type of symbol can have different parameters. For example symbol of type A will have some distance and symbol B an angle. C symbol has no parameters. The string then could look like "ABABC".
Then I need to iterate through the string and do some actions that are also connected to each type of symbol. "A" could mean "draw line of 'distance' length" (distance is parameter of A), B "turn 'angle' degrees" and C finish painting.
I tried to have class Symbol and a child for each symbol type (class SymbolA, class SymbolB, class SymbolC), but I don't know how to create the string. I would like to avoid type casts and stuff like that.
Is there somebody who had a similar problem or has an idea that can help me, please?

A: If you want to implement something as complicated as full L-systems, I'd suggest using a higher-level language than C++, such as Python or Common Lisp. Then you can profile the entire piece of code and implement the speed bottlenecks in C/C++.
I implemented L-systems a long time ago for a course in Chaos Theory and Fractals, using Common Lisp. It wasn't too hard to do - just used a list of symbols. I've been trying to find the code for it, but it's been more than 7 years, so no luck so far.
Anyway, this seems like a much more reasonable approach to me. Even if you make a slow implementation in a high-level language, it will give you a better idea of how to implement it in C++, which takes a lot more developer time to do.

A: Seems to me you're on the right track: You need a SymbolBase class that define pure virtual functions for the kind of operations that need to be implemented, and then have SymbolA, SymbolB, etc. derived classes that each implement the specific functionality. For painting the elements to the screen, each class would implement some function that takes a graphics object or similar as argument and paints itself to the graphics object.
In order to represent these in a 'string', you need a linear collection of some kind, STL vector or linked list most likely, a linked list is more efficient if you're going to rearrange the symbols using the L-system productions. You will then be able to iterate over the list in order to display it on the screen. You'll get into the usual problem of holding instances of various classes in a collection, where the element type is pointers to the base class. You can usually get it working without too many type cast (and always use dynamic_cast when you do need it). If you design your base class correctly, then the calling code should be able to call the pure abstract functions in the base class without ever caring which particular symbol class it's actually interacting with.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where is Codeigniter system's core file prefix that is 'CI'? How prefix work in PHP? I learned from start that to use the same name of class as of file name. For that reason I started to look for 'CI_Controller' file in my codeigniter that I usually extends. I found a controller file with a class named 'CI_Controller'. After research I found out that codeigniter is using prefix mechanism.
I tried to find out where codeigniter has declared 'CI' as its prefix but I was unable to find it?
One more the thing; how at backend this prefix mechanism works? Is it prefixed 'CI' with file name before compilation or it just keeps track of every class with respect to 'CI'?
This point is getting quite confusing for me.


text:
Q: Execution failed for task ':app:compileDevDebugAndroidTestJavaWithJavac' I am trying to run a command ./gradlew app:assembleAndroidTest inside android directory of my app in order to build an app-debug-androidTest.apk under androidTest directory.
But my build is failed with the following errors:
> Task :app:compileDevDebugAndroidTestJavaWithJavac
C:\Users\Noyruto\sources\repos\limitless-app\android\app\src\androidTest\java\ph\phoenixfuels\limitless\MainActivityTest.java:11: error: cannot find symbol
  public ActivityTestRule<MainActivity> rule = new ActivityTestRule<>(MainActivity.class, true, false);
                          ^
  symbol:   class MainActivity
  location: class MainActivityTest
C:\Users\Noyruto\sources\repos\limitless-app\android\app\src\androidTest\java\ph\phoenixfuels\limitless\MainActivityTest.java:11: error: cannot find symbol
  public ActivityTestRule<MainActivity> rule = new ActivityTestRule<>(MainActivity.class, true, false);
                                                                      ^
  symbol:   class MainActivity
  location: class MainActivityTest
2 errors

> Task :app:compileDevDebugAndroidTestJavaWithJavac FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDevDebugAndroidTestJavaWithJavac'.

I don't think there's a problem with my MainActivityTest.java because I tried this in other flutter app, and it build successfully.
Is it because my project has a flavor?


text:
Q: Error trying to load ODBC connection to dataset I am trying to connect to an ODBC connection.
This works.
    Dim cn As OdbcConnection
    cn = New OdbcConnection("DRIVER={SQL Server};SERVER=ServerName;UID=UserName;" &
                            "PWD=Password;DATABASE=dbName;")

    Dim mystring As String = "SELECT * FROM dbo_lData WHERE S_DT > #3/18/2018#"
    Dim cmd As OdbcCommand = New OdbcCommand(mystring)
    cn.Open()
    MsgBox("Connected")
    cn.Close()

I've tried a couple of variations using different code that I've found on the internet, but I keep getting the same error. Error 42000, incorrect syntax near #.  Here is the code.
    Dim selectSQL As String = "SELECT * FROM dbo_lData WHERE S_DT > #3/18/2018#"
    cn = New OdbcConnection("DRIVER={SQL Server};SERVER=ServerName;UID=UserName;" &
                            "PWD=Password;DATABASE=dbName;")
    Dim custDA As New OdbcDataAdapter
    Dim selectCMD As OdbcCommand = New OdbcCommand(selectSQL, cn)
    custDA.SelectCommand = selectCMD

    Dim custDS As DataSet = New DataSet
    custDA.Fill(custDS, "lData")

    DataGridView1.Visible = True
    DataGridView1.DataSource = custDA

I'm pretty lost on this, but what I am trying to do is just...

*

*Make ODBC Connection

*Load results, preferable into a datatable

*Set datagridview.datasource = datatable

A: The error you are getting is referring to your Select statement. As the comments said use parameters. First double check the data type of S_DT column. I wonder why you are using ODBC when the SQL server native provider SQLClient will yield better results.
Dim cn As New OdbcConnection("connection string")
Dim cmd As New OdbcCommand("SELECT * FROM dbo_lData WHERE S_DT > @sdate", cn)
cmd.Parameters.Add("@sdate", OdbcType.Date)


text:
Q: Connect to rails server remotely from raspberry pi I have ssh'd into my rasberry pi and built a rails application.
Now how do I load the rails app from another machine?
I have tried IP:port in a web browser, but this fails.
Can I use ssh from a web browser to load the rails server process?
Are there gems I need to install to do this?
Is there any good documentation that I have missed?
SOLUTION
use ngrok to tunnel https://medium.com/@karimbutt/using-ngrok-to-create-a-publicly-accessible-web-facing-raspberry-pi-server-35deef8c816a#.sraso7zar

A: Maybe the problem is with the IP address you're trying to use. Servers don't necessarily forward their public IP traffic to localhost automatically.
Perhaps you could configure the IP address somehow, I don't know (others might?). Alternatively, you have a use a "local tunnel" service like ngrok or localtunnel. What these do is create a public URL for your localhost (i.e. your "loopback" address), so anyone can access it.
I spoke with a Ngrok author via email. He ensured me that I shouldn't need to expect any downtime from the service or to have to manually restart it. Although keep in mind that if you're on the free plan, whenever you restart Ngrok you're going to get a different URL. He also described it as kind of like a "souped up SSH -R"


text:
Q: How is glb property implied from lub for set of all numbers of the format 1/n? Consider the set
$$ S = { \frac{1}{x} : x \in \mathbb{N} } $$
This set has the Least upper bound property since every non empty subset has a least upper bound in S. How is the greatest lower bound property implied in this case? Consider the subset $E = S$, and since $0 \notin S $, it doesn't have a lower bound in $S$, so by definition, glb property does not hold true.
Rudin says on page 4 that, every ordered set with the least-upper bound property also has the greatest-lower bound property.


text:
Q: Explanation of LED driver circuit I've been reading up on LED drivers and found some common connection schemes. Yet, I recently came across the following LED driver circuit at this URL:

I tried to find out what exactely was going on here but I do not understand why the LEDs are fed back to the input voltage (usually they are connected to ground). What I understand from the schematic so far:
We have an AC voltage source, this is rectified by diodes D3,D4,D5,D6. CTRL (which sets the current in conjunction to RS2) is set to a fixed level, defined by 1M and 69.8k. SHDN is set to high to enable the device. D2 makes sure that CVIN is constantly charged, thereby keeping VIN enabled (even when there is a zero crossing on the input). OPENLED is pulled up to INTVCC and PWM high enables the device (as well).
Now, the current is driven into L1 (and switched on/off using M1 to achieve a constant current), through D1, through the current sense resistor RS2 (connected to Pins ISP and ISN) and then (and this is the part I really don't get) back to PVIN.
So, actually there's three parts I do not understand:

*

*Why is the string of LEDs not terminated at ground (I have seen this multiple times with other LED drivers and also the application note for this LED driver has a similar connection scheme). What would the voltage before the first LED be (since there is a voltage drop across the 4 LEDs)

*What exactely is the purpose of the FB. The datasheet mentions "Voltage Loop Feedback Pin". But I do not understand the use of the transistor and the 392k resistor.

*What is the use of RS1 (being 40mR)
It would be really nice if you could shed some light on this specific configuration.
This is the link to the datasheet of the LT3755.

A: *

*It's a buck-boost configuration. If it was connected in boost then the input voltage could not exceed the LED voltage or they would burn out. There's more voltage across the inductor and the switch has to withstand more voltage with buck-boost.

simulate this circuit – Schematic created using CircuitLab

*The voltage feedback is to protect the IC if the LED string should become open circuit for some reason, otherwise the voltage at Cout would quickly rise to destructive levels. The transistor effectively level shifts the overvoltage protection so that it measures the voltage above the positive rail (more than about 20V plus one Vbe above PVin will cause 50uA to flow, which will drop 1.25V across the 24.9K resistor, which in turn will cause it to shut down).

*RS2 is the sense resistor for measuring the LED current. RS1 is the sense resistor for measuring the inductor current.


text:
Q: "Cannot utime: Bad file descriptor" when upgrading ubuntu 8.04 to 10.04 After running do-release-upgrade --proposed on my Ubuntu Server 8.04, I got the message:
The upgrade is completed but there were errors during the upgrade process.

Searching up the upgrade output, I found this:
Setting up tar (1.22-2) ...

tar: ./md5sums: Cannot utime: Bad file descriptor
tar: ./control: Cannot utime: Bad file descriptor
tar: .: Cannot utime: Bad file descriptor
tar: Exiting with failure status due to previous errors
dpkg-deb: subprocess tar returned error exit status 2
dpkg: error processing /var/cache/apt/archives/diff_1%3a2.8.1-18_all.deb (--unpack):
 subprocess dpkg-deb --control returned error exit status 2
Errors were encountered while processing:
 /var/cache/apt/archives/diff_1%3a2.8.1-18_all.deb
Exception during pm.DoInstall():  E:Sub-process /usr/bin/dpkg returned an error code (1)

Could not install the upgrades

The upgrade is now aborted. Your system could be in an unusable
state. A recovery will run now (dpkg --configure -a).

Apparenly, this is a known bug. More details are here and here.
I will post the workaround I found as an answer.

A: As a workaround, you can create a wrapper for tar that will add the --touch option:
create a file named tar under /usr/local/sbin with the following content:
#!/bin/sh
exec /bin/tar --touch -"$@"

Do:
chmod +x /usr/local/sbin/tar

Now run aptitude dist-upgrade to continue the upgrade process.
Delete this file after installation has completed.

A: Sometimes the /usr/local/sbin/tar trick doesn't work.
But I found this option helped for me. Run
export TAR_OPTIONS='--touch'

Then continue with your
apt-get upgrade

A: I got this same error, and I couldn't install anything with aptitude either because of tar being broken. I had to leave /usr/local/sbin/tar so that aptitude would continue to work correctly.


text:
Q: Is it possible to have a countable subset of $ \ell_2 $ that spans it? The original question I was given was

Let $\mathbf{H}$ be an infinite Hilbert space. Is it possible that a countable subset of $\mathbf{H}$ spans it?

Assuming $\mathbf{H} = \mathrm{Sp}B$ where $B$ is a countable set, $\mathbf{H}$ is separable and therefore isomorphic to $\ell_2$, and $\left \{ Au\mid u\in B \right \}$ (where $A$ is the isomorphism between $\mathbf{H}$ and $\ell_2$) is a countable subset of $\ell_2$ that spans it. I want to say that this is not possible, which will make it impossible in the general case.
If I knew this subset is also linearly independent, I could use Gram-Schmidt to obtain an orthonormal basis $\left ( \varphi_k \right)_{k=0}^\infty$ such that $\mathrm{Sp}\left \{ \varphi_k\right \} = \ell_2$, and then the vector $\sum\limits_{k=0}^\infty \frac{1}{k^2}\varphi_k$ would be in $\ell_2$ but not in $\mathrm{Sp}\left \{ \varphi_k\right \}$. However I can't find a way to do it without the set being linearly independent. Does it necessarily have a linearly independent subset? I know this is a thing in finite dimensional spaces, but is it true also in (countably) infinite dimensions?

A: In any vector space any set of vectors $B$  contains a maximal linearly independent subset $C$ (by Zorn's Lemma). It then follows by maximality that $B$ and $C$ span the same subspace of $V$. Of course the isomorphism $A$ preserves linear independence. Incidentally, no Banach space can be spanned by countable number of elements. (This is proved using Baire Category Theorem).


text:
Q: Finding the Pre-image $\ f^{-1}([0,+\infty))\ $
I am trying to find the pre-image of $f$, $\ f^{-1}([0,+\infty))\ $, where $f:\mathbb{R^2}\rightarrow\mathbb{R}$ and $f(x,y)=y(x-y).$

From a previous post, I was told to solve $f(x,y)\geq0$, but when I try to do this, I get
$$
y\geq0
$$
and
$$
y\leq x
$$
This does not match the answer provided in the book, which also states that
$$
y\leq 0
$$
$$
y\leq x
$$
Why is this the case? It seems like a trivial question, but I don't understand.

A: Remember that the resilt is positive also when the things you're multiplying are negative.
We want solve $y(x-y) \ge 0$. This happens $\iff (y \ge 0$ and $x-y \ge 0)$ or $(y \le 0$ and $x-y \le 0)$
From the first case we get $y \ge 0$ and $x \ge y$.
From the second case we get $y \le 0 $ and $x \le y$

A: It all goes back to the same thing : the product of two numbers is non-negative if and only if both of them have the same sign (or any one is zero).
Therefore, if $f(x,y) \geq 0$ then $y(x-y) \geq 0$, which means that the product of $y$ and $x-y$ is non-negative. So :

*

*Either $y$ is non-negative and $x - y$ is non-negative i.e. $y \geq 0, x \geq y$.

*Or, $y$ is non-positive and $x-y$ is non-positive i.e. $y \leq 0, x \leq y$.
Consequently, $f^{-1}([0,\infty)) = \{(x,y) : 0 \geq y \geq x\} \cup \{(x,y) : 0 \leq y \leq x\}$.

A: The pre-image of $[0,+\infty)$ is defined as:
$$\{(x,y)\in\mathbb{R}^2\,\colon y(x-y)\geq 0\}.$$
Working on this expression we have:
$$y(x-y)\geq 0\iff xy-y^2\geq 0\iff y^2\leq xy.$$
If $y\geq 0$, we need $x\geq y$.
If $y<0$, we need $x\leq y$.


text:
Q: Oracle: how to calculate running total Oracle 19.3 on Windows.
Trying to figure out how to show a running total.
Inner table shows unique sku_id and its qty sold.
I am trying to show a running total, but in some instances, when I sold the same number of items, running total is not changing.
What am I doing wrong?
select sku_id, sku_qty, sum(sku_qty) over (ORDER BY sku_qty desc) running_total
from (
                -- April sales
                select
                    sku_id
                    ,sum(item_qty) sku_qty
                from ecomm_order_item
                where extract(YEAR from created_date) = 2021
                  and extract(MONTH from created_date) = 4
                group by sku_id
                order by sku_qty desc
)
order by sku_qty desc

A: You are ordering by sku_qty and if you have two rows with the same sku_qty then they will have the same rank in the ordering and the SUM will count them both at the same time.
If you want them to be counted separately then you need to give them a unique ordering.
For example, you could add sku_id to the ORDER BY clause:
select sku_id,
       sku_qty,
       sum(sku_qty) over (ORDER BY sku_qty desc, sku_id) running_total
from  ...

Or, could use ROWNUM
select sku_id,
       sku_qty,
       sum(sku_qty) over (ORDER BY sku_qty desc, ROWNUM) running_total
from  ...

Or anything else unique.

Or, you could change the windowing clause from the default RANGE window to use ROWS:
select sku_id,
       sku_qty,
       sum(sku_qty) over (
         ORDER BY sku_qty desc
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) running_total
from  ...

db<>fiddle here


text:
Q: How to display the login username and the search text field under each other I have the following layout html to show the login username and a search input text:-

 @User.Identity.Name.Substring(User.Identity.Name.IndexOf("\\") + 1)

<form  method="GET" action="@Url.Action("Search", "Home")">

<input  placeholder=".." name="searchTerm2" data-autocomplete-source= "@Url.Action("AutoComplete", "Home")" type="text"  />

</form>

and the related css class:-
.navbar-search {
  position: relative;
  float: right;
  margin-top: 6px;
  margin-bottom: 0;
}

Currently I am having the following layout issue; is that the username will be out of the layout as follow:-

So my question is how I can modify my current layout to show the text search field under the login username, and to have the username to the right side of the screen .
Thanks

A: Specify a width for your section login (large enough to contain input search or the display name), put your span with username display as a block and float it right. Something like this
#login{ width: 300px }
.navbar-search{width: 300px}
.username{
  display: block;
  float: right;

}

Should do the trick


text:
Q: Remove empty paragrapf and change h3 element css I have some blog on a wordpress webpage. These blogs can be added from dashboard. The problem is that the new blogs generates some html elements that mess up the design.
This is the hml that is generated:

Creating a Culture of Innovation

      Last week, I had the opportunity...

       Read more

The problem is with the two paragraphs

 and that the text is in a h3 element. The text should be in a

It should be:

Creating a Culture of Innovation
      Last week, I had the opportunity...

       Read more

Can you please advise how can I resolve this by css? Can I do this with pure css? Thanks!

A:
Can I do this with pure css?

I doubt that, but below jQuery may help
jQuery(function($){
  $(document).ready(function(){
  $('h3').each(function(){
    $(this).replaceWith('
'+$(this).text()+'
');
  });
  $('p').each(function(){
    if(!$(this).text().length){
    $(this).remove();
  }
  });

});
});

See the fiddle [ here ].


text:
Q: Submitting form in JS using enter key instead of a submit button I am inexperienced with forms but want to pass the text from an input field to the rest of my code whenever the user presses the enter key in the input field (I am testing it with an alert at the moment but can't get it to fire). I am using the following JS:

$(document).ready(function() {
  $("#task").keypress(function(event) {
    if (event.which == 13) {
      event.preventDefault();
      alert("test");
    }
  });
});

<form class="form" action=" " method="get" autocomplete="off" role="form" autofocus>

    <input class="form-control input-lg" type="text" autofocus id="task" placeholder="Enter your task:">

</form>

Is it possible that I need to adjust the "action" field?

A: Solution:
<input id="task" class="form-control input-lg" type="text" autofocus
    placeholder="Enter your task:">

document.getElementById("task").onkeydown = function (event) {
    event = event || window.event;
    if(event.keyCode == 13) {
         // Enter was pressed
    }
}

Demo:

document.getElementById("task").onkeydown = function(event) {
  event = event || window.event;
  document.getElementById("exampleOutput").innerHTML = event.keyCode
  if (event.keyCode == 13) {
    // Enter was pressed
    // Example:
    document.getElementById("exampleOutput").innerHTML += " Enter"
  }
}
<input id="task" class="form-control input-lg" type="text" autofocus id="task" placeholder="Enter your task:">

A:

$(document).ready(function() {
  $('input[type=text]').on('keyup', function(e) {
    if (e.which == 13) {
      e.preventDefault();
    }
  });
});

<form class="form" action=" " method="get" autocomplete="off" role="form" autofocus>

    <input class="form-control input-lg" type="text" autofocus id="task" placeholder="Enter your task:">

</form>

A: EDIT: Just tried your code in a jsfiddle and it works. Did you include JQuery before the scripts?
You can bind the keypress event to the form instead like this.  This way there won't be an event tied to every input you have.  This event will fire when enter is pressed on any input in the form.

$(document).ready(function() {
  $(".form").on("keypress", ":input", function(e) {
    if (e.which == 13) {
      e.preventDefault();
      alert("form submitted");
    }
  });
});

<form class="form" action=" " method="get" autocomplete="off" role="form" autofocus>

    <input class="form-control input-lg" type="text" autofocus id="task" placeholder="Enter your task:">

</form>

A: used your code in Fiddle ..it is working fine..find a fiddle demo of the same below
$("#task").keypress(function (event) {
    var key = event.which;
    if (key == 13) {
        event.preventDefault();
        alert($(this).val());

        }
    });

Demo


text:
Q: insertar datos ajax laravel Hola tengo el siguente codigo:
$('#newsletterbutton').on('click',function(){
       event.preventDefault();
       var email = $('#emailnews').val();
       $.ajax({
                   type:"ajax",
                   url: '/newsletter',
                   type: 'POST',
                   data: {email: email},
                   dataType: 'json',
                   success: function(){
                        alert('bien');
                   },
                   error: function(){
                       alert('mal');
                   },
               })
           }
      })

Mi controllador:
function newsletter(Request $request)
    {
        $insert = DB::table('newsletter')
              ->insert(['email' => $request->email]);
        return response()->json ($insert);
    }

y mi ruta:
Route::post('/newsletter', 'MainController@newsletter');

mi problema que es siempre esta entrado en error no estaria entendiendo que estaria haciendo mal.
en mi head esta definido el crsf token.

A: En laravel, se tiene un token, para evitar ataques csrf y que siempre son requeridos al momento de hacer una petición post.
Puedes agregarlo en una etiqueta meta o simplemente en un input hidden.
Ej:
<input type="hidden" value="{{csrf_token()}}" name="_token" id="token">

O podrias añadirlo con {{ csrf_field() }}, que tan solo es su equivalente, lo que faltaria es enviarlo en tu ajax:
   var email = $('#emailnews').val();
   var _token = $('#token').val();
   $.ajax({
               type:"ajax",
               url: '/newsletter',
               type: 'POST',
               data: {email: email,_token:_token},
               dataType: 'json',
               success: function(){
                    alert('bien');
               },
               error: function(){
                   alert('mal');
               },
           })
       }
  })

Con eso tu problema debería de solucionarse.


text:
Q: How to make the TypeScript path maps useful in the production code? I've been working on my TypeScript project and wanted to tackle the relative import ../../../ hell problem. I found out that in tsconfig.json I can specify the baseUrl and paths fields so that my ../../../../interface can become simply @interface when I add such a snippet to the tsconfig.json:
    "baseUrl": ".",
    "paths": {
      "@interface" : ["src/interface"],
    },

and that worked great... for a while. I exchanged the long paths in import statements with shorter versions. VSCode was kind enough to understand the path mapping and coding became easier. When I finally wanted to test the app, I compiled the code with tsc command. When I wanted to run it, I got the error:
Error: Cannot find module '@interface'

I inspected the output JavaScript code and saw that the path in the import has not been exchanged by the compiler, as I would expect, but it was just used in the same form as in the .ts file:
const _interface_1 = require("@interface");

I found an issue on TS GitHub from August 2018 asking about the exact same thing. Until now there has not been a satisfying solution to the problem.
My question is: what is the use case for the path mapping in TypeScript as described in the manual? What's the point of using them if they in the end make the production code not runnable?

A: I also agree with the comment Aviad has put but without judging. If you must do this, then here is a way:
Add module module-alias to your dependencies. then add mapping to package.json too:
"_moduleAliases": {
    "@interface": "dist/interface", // note its referencing dist folder
},

Then in your main ts file. e.g. index.ts, register the module alias using import "module-alias/register";
Here you can read more about it


text:
Q: JRJC not recognized in project I'm building a rest client that should hook up with JIRA.
I'm trying to use JRJC (https://ecosystem.atlassian.net/wiki/display/JRJC) in my project. I'm using Intellij 15.0.4 and gradle and having trouble using the library as it seems like it's not recognized.
my build.gradle file looks like this:
apply plugin: 'java'
apply plugin: 'idea'

sourceCompatibility = 1.5
version = '1.0'

repositories {
    mavenCentral()
    maven {url "https://maven.atlassian.com/public/"}
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile 'com.google.guava:guava:19.0'
    compile 'com.google.inject:guice-parent:4.0'
    compile 'com.google.inject.extensions:guice-assistedinject:4.0'
    compile 'com.google.inject.extensions:guice-multibindings:4.0'
    compile 'org.apache.commons:commons-lang3:3.4'
    compile 'org.apache.commons:commons-math3:3.6'
    compile 'com.atlassian.jira:jira-rest-java-client-parent:3.0.0'
}

I keep getting this error from Intellij saying that https://maven.atlassian.com/public/ is an unindexed repository.
When I try to call the classes in the project I can't seem to use the relevant imports. Intellij marks an error and says it cannot resolve the symbols.
I have tried to index the repository (it takes about an 40 minutes but it does not seem to make a difference). I've refreshed, reimported and cleaned the project multiple times and still no go. The installation guide in the link I've added above mentions using the Atlassian Plugin SDK however since I'm not using maven directly I'm not sure how relevant it is for me.
Any help would be most appreciated

A: After some time here's what has worked for me.
I've added https://maven.atlassian.com/content/repositories/atlassian-public/ to my repositories list and I've added the following dependencies to my gradle.build:
compile 'com.atlassian.jira:jira-rest-java-client-core:3.0.0'
compile 'com.atlassian.jira:jira-rest-java-client-api:3.0.0'
compile 'com.atlassian.jira:jira-rest-java-client-plugin:3.0.0'

My gradle.build file now looks like this:
apply plugin: 'java'
apply plugin: 'idea'

sourceCompatibility = 1.5
version = '1.0'

repositories {
    maven {
        url 'https://maven.atlassian.com/content/repositories/atlassian-public/'
    }
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile 'com.google.guava:guava:19.0'
    compile 'com.google.inject:guice-parent:4.0'
    compile 'com.google.inject.extensions:guice-assistedinject:4.0'
    compile 'com.google.inject.extensions:guice-multibindings:4.0'
    compile 'org.apache.commons:commons-lang3:3.4'
    compile 'org.apache.commons:commons-math3:3.6'
    compile 'com.atlassian.jira:jira-rest-java-client-parent:3.0.0'
    compile 'com.atlassian.jira:jira-rest-java-client-core:3.0.0'
    compile 'com.atlassian.jira:jira-rest-java-client-api:3.0.0'
    compile 'com.atlassian.jira:jira-rest-java-client-plugin:3.0.0'
}


text:
Q: stuck in Clojure recursion I am trying to write a recursive function in clojure. The function returns the greatest number of given collection. If the collection is emty then it should return nil.
My code is:
(defn gum [coll]
 (if (empty? coll)
  0
  (max (first coll)
   (gum (rest coll)))))

Expected result:
(gum [1 2 98 -3]) => 98
(gum [1 9]) => 9
(gum []) => nil

But I am getting:
(gum [1 2 98 -3]) => 98
(gum [1 9]) => 9
(gum []) => 0 (not desired result - should be `nil`)

This is because I have kept the value of (empty? coll) as 0. If I keep it as nil then (gum [1 2 98 -3]) won't work. Any suggestion as how to bring the value of (gum []) as nil and (gum [1 2 98 -3]) as 98 at the same time?

A: I think you want something like this:
(defn gum [[head & tail]]
  (if (empty? tail)
      head
      (max head (gum tail))))

I'm using destructuring here instead of first and rest, but it's the same as:
(defn gum [coll]
  (let [head (first coll)
        tail (rest coll)]
    (if (empty? tail)
        head
        (max head (gum tail)))))

But you should try to avoid constructions like (max head (gum tail)), because Clojure can't optimize it. Try using tail recursion with recur whenever possible:
(defn gum [[head & tail]]
  (if (empty? tail)
      head
      (recur (cons (max head (first tail))
                   (rest tail)))))

recur allows Clojure to use Tail Call Optimization to convert your recursive call into an iterative one, allowing it to be run in a constant stack space. It not only makes your code faster, but also protects it from stack overflow.
You should also consider using Higher Order Functions instead of recursion (as SaltyEgg suggested):
(defn gum [coll]
  (if-let [s (seq coll)]
    (reduce max s)))

In most cases they provide an easier solution. And they are pretty good optimized.

A: Try this:
(defn gum [coll]
 (if (empty? coll)
  nil
  (reduce max coll)))

A: Looks like you are trying to redefine the max function ?
Now if you are looking to understand how the max function works, it ususally a good idea to look at the source (source max) in a repl :
(defn max
  "Returns the greatest of the nums."
  {:added "1.0"
   :inline-arities >1?
   :inline (nary-inline 'max)}
  ([x] x)
  ([x y] (. clojure.lang.Numbers (max x y)))
  ([x y & more]
   (reduce1 max (max x y) more)))

Note that (apply max []) will throw an exception rather than returning nil : ArityException Wrong number of args (0) passed to: core/max  clojure.lang.AFn.throwArity (AFn.java:429)

Edit :
That's why the approach to check first if we want to apply max and then (maybe) apply, as suggested by other answers :
(defn gum [coll]
  (if-let [s (seq coll)]
    (reduce max s)))

A: You should not call the same function inside because Clojure does not have tail recursion optimization (TRO). Use (recur arg1 arg2 etc) to iterate on the next step. And don't forget to add an if statement to leave the recursion.

A: This would work, using same logic as you have described, returning singleton elements instead of zero:
(defn gum [coll]
  (if (or (empty? coll)
          (singleton? coll))
    (first coll)
    (max (first coll) (gum (rest coll)))))

with:
(defn singleton? [coll]
  (if (first coll) (empty? (rest coll)) false))


text:
Q: Why the download and upload speed in an application like WhatsApp is different? The download speed of documents, images, videos etc is faster as compared to the upload speed no matter how fast the net connection is.
The above statement was made in general but tried specifically in WhatsApp.
Is there any specific advantage or technical reason for it?

A: There are several reasons for this.
One of the most significant is that whatsapp will compress the assets before uploading to save data, this takes time. Also less bandwidth is used for uploads as compared to downloads.

A: The download is everytime faster than the upload. In Whatsapp all assets like documents, images, videos etc. will be compressed (Arvindsinc2) said it.
The disadvantage is the quality from this assets. The compression for videos and images is so strong that you just can use this files for your phone. Images that you send via whatsapp are not suitable for printing or similar projects.
The video files are very compressed. Looking at the TV is almost impossible. On the handy but enough
The reason for the compression is that the bandwidth on mobile terminals is kept low.


text:
Q: How to use for-each in XQuery in OSB? Hi I want to select all from table to another table through Oracle service bus so that I am using X Query for transformation but it is transfer only one row so i need for-each function for all record but i do not how to use for-each?
  please provide me methods to use for-each in X Query?

A: The graphical XQuery editor might help. See samples here:
https://docs.oracle.com/cd/E29542_01/dev.1111/e15866/examples.htm#OSBDV749
(esp Example 7-6)


text:
Q: Changing core functionality of Shopping Cart Price Rule To suite my Payment terms i have considered using Shopping Cart Price Rules since they are easy way out. What the default Shopping Cart Price Rule does is that it applies a fix or percentage based discount (whatever we set it to)-and then it subtracts that discount from subtotal amount BUT i want it to ADD the 'discount'* to subtotal amount and Grand-Total be based on ' Subtotal + discount* '. The discount* in my case would be shipping as i would change the word 'discount' by 'Shipping'. And so the Grand-Total would now be turned as 'Subtotal + Shipping'. So basically all that needs to be done is change the subtraction sign - to addition sign + , to perform addition of Subtotal + discount-turned-into-Shipping
You guys must be wondering why i am not using the default shipping options-well i tried them but they are not suiting my needs.
Anyone please?just need to know where can i perform maths.


text:
Q: Loading Byte Array Assembly I'm experimenting with loading an assembly using just byte arrays, but I can't figure out how to get it to work properly. Here is the setup:
public static void Main()
{
    PermissionSet permissions = new PermissionSet(PermissionState.None);
    AppDomainSetup setup = new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory };
    AppDomain friendlyDomain = AppDomain.CreateDomain("Friendly", null, setup, permissions);

    Byte[] primary = File.ReadAllBytes("Primary.dll_");
    Byte[] dependency = File.ReadAllBytes("Dependency.dll_");

    // Crashes here saying it can't find the file.
    friendlyDomain.Load(dependency);

    AppDomain.Unload(friendlyDomain);

    Console.WriteLine("Stand successful");
    Console.ReadLine();
}

I created two mock dlls, and renamed their extension to '.dll_' intentionally so the system wouldn't be able to find the physical files. Both primary and dependency fill correctly, but when I try to call the AppDomain.Load method with the binary data, it comes back with:
Could not load file or assembly 'Dependency, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Why would it be searching the system for a file?
UPDATE
This on the other hand seems to work:
public class Program {
    public static void Main() {
        PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);
        AppDomainSetup setup = new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory };
        AppDomain friendlyDomain = AppDomain.CreateDomain("Friendly", null, setup, permissions);

        Byte[] primary = File.ReadAllBytes("Primary.dll_");
        Byte[] dependency = File.ReadAllBytes("Dependency.dll_");

        // Crashes here saying it can't find the file.
        // friendlyDomain.Load(primary);

        Stage stage = (Stage)friendlyDomain.CreateInstanceAndUnwrap(typeof(Stage).Assembly.FullName, typeof(Stage).FullName);
        stage.LoadAssembly(dependency);

        Console.WriteLine("Stand successful");
        Console.ReadLine();
    }

}

public class Stage : MarshalByRefObject {
    public void LoadAssembly(Byte[] data) {
        Assembly.Load(data);
    }
}

So it appears there is a difference between AppDomain.Load and Assembly.Load.

A: There is no difference between these two methods (you can check the official source code if you want).
In the MSDN page for AppDomain.Load Method (Byte[]) it is remarked that this method is loading the assembly in the current application domain:

This method should be used only to load an assembly into the current
  application domain. This method is provided as a convenience for
  interoperability callers who cannot call the static Assembly.Load
  method. To load assemblies into other application domains, use a
  method such as CreateInstanceAndUnwrap.

the line:
friendlyDomain.Load(dependency);

behaves exactly the same with:
Assembly.Load(dependency);

The reason it works in your updated sample code, is because the Stage object is actually calling Assembly.Load inside the child AppDomain.
Note: This answer complements the answers by Hans Passant and colinsmith.

A: This is normal, the CLR doesn't consider the "dependency" you loaded to be a suitable assembly when it searches for the assembly that "primary" needs.  A problem associated with "loading context", there isn't one for assemblies loaded like this.  This is intentional, the CLR cannot ensure that DLL Hell won't be an issue since it has no idea where the assembly came from.  Since you opened the door to DLL Hell, you also have to avoid hell yourself.
You'll need to implement the AppDomain.AssemblyResolve event.  It will fire when the CLR cannot find "dependency", you can return the assembly you get from Assembly.Load(byte[]).  You will however have to do so consistently when it fires more than once for the same assembly, in other words return the exact same Assembly, or you'll have more problems induced by .NET type identity.  Producing hard to understand casting exceptions, "can't cast Foo to Foo" style.
There are other problems, it is rather inefficient.  The virtual memory for the assembly cannot be backed by a file on disk so it is backed by the paging file.  Which increases the commit size for your process.
It is certainly better to not do this.

A: If you use FusionLogViewer you can see more details about the particular problem the CLR is having in loading an assembly .... it can show you which locations it's trying to probe to give you a clue, etc.

*

*http://msdn.microsoft.com/en-us/library/e74a18c4(v=vs.71).aspx

*http://www.shujaat.net/2012/04/fusion-log-viewer-fuslogvw-for-assembly.html
You could also handle the AssemblyLoad / AssemblyResolve / ResourceResolve events on your AppDomain in your code, to trace through the sequence.

*

*http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx
This is a handy example that uses a custom MSBuild step to embed any of your project dependent assemblies as Resources into your EXE program, and then use AssemblyResolve to load them from a ResourceStream (doing Assembly.Load() on the byte[] array).

*

*http://www.digitallycreated.net/Blog/61/combining-multiple-assemblies-into-a-single-exe-for-a-wpf-application

A: So I was doing a bunch of research I came a across a few answers on stackoverflow and the solution I put together is as follows:
using System;
using System.Windows.Forms;
using System.Reflection;

public partial class MainForm : Form
{
    private AppDomain = AppDomain.CreateDomain("asmDomain");

    public MainForm()
    {
        InitializeComponent();
    }

    /// <summary>
    /// Loads a Byte array as raw assmebly then loads and creates defined object from
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    [LoaderOptimizationAttribute(LoaderOptimization.MultiDomain)]
    private void loadAsmObject(object sender, TileItemEventArgs e)
    {
        Byte[] rawAssembly = getFileAsm(); // Load the bytes however you wish.

        try
        {
            AppDomain.Unload(appDomain);

            appDomain = AppDomain.CreateDomain("asmDomain");

            AppDomainBridge isolationDomainLoadContext = (AppDomainBridge)appDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof (AppDomainBridge).ToString());

            // Form is MarshalByRefObject type for the current AppDomain
            MyObject obj = isolationDomainLoadContext.ExecuteFromAssembly(rawAssembly, "MyNamespace.MyObject"/*, new object[] { "Arg1", "Arg2" } Optional args*/) as MyObject;

            obj.callMethod();
        }

        catch (Exception Ex)
        {
            MessageBox.Show("Failed to load Object!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    /// <summary>
    /// Acts as a shared app domain so we can use AppDomain.CurrentDomain.Load without errors.
    /// </summary>
    private class AppDomainBridge : MarshalByRefObject
    {
        public Object ExecuteFromAssembly(Byte[] rawAsm, string typeName, params object[] args)
        {
            Assembly assembly = AppDomain.CurrentDomain.Load(rawAssembly: rawAsm);

            return Activator.CreateInstance(assembly.GetType(typeName), args);
        }
    }
}


text:
Q: Right triangle problem (Analytic geometry)
In the figure AD=BD
B(-3,0),D(0,3) are given find
Coordinates of point C
I am new to analytic geometry I have tried to solve this and I found coordinates of point A
I think for solving this question we may need to use formula or theorems which I haven't studied yet that's why this question seems hard for me can you please help?

A: COMMENT
►Let $A=(x,y)$ You have $(x,y)=(3,6)$ (Why?)
►Slope of ligne $\overline{BA}=1$ therefore slope of ligne $\overline{AC}=-1$ (Why?).
►ligne $AC: y=-x+9$ (Why?).
►Point $C$ has coordinates $(9,0)$ (Why?)

A: Note that D is the midpoint of AB thus
$$D=\frac{A+B}{2}\implies A=2D-B=2(0,3)-(-3,0)=(3,6)$$
Since $\angle B=45°$ C is symmetric to B with respect to A thus
$$x_A=\frac{x_B+x_C}{2}\implies x_C=2x_A-x_B=6-(-3)=9$$
therefore
$$C=(9,0)$$

A: we get $$\vec{BD}=[3;3]$$ then $$\vec{BA}=[x_A+3;y_A-0]=2\vec{BD}$$
from here you will get $A(x_A,y_A)$

A: You say you have already found the coordinates of $A.$
There are formulas you could use such as the formula for the slope of a line perpendicular to a known line and the formula of a line of known slope through a known point, but you do not really need even those formulas for this question.
Try drawing a line through $A$ parallel to the $y$ axis. Let $E$ be the intersection of that line with the $x$ axis.
You now should be able to identify at least four right triangles in your diagram (though you do not really need that many).
You can use similar triangles or any other tool you find convenient to find the lengths of edges of triangles parallel to the $x$ or $y$ axes.
Eventually you want to find enough lengths so that you can determine the coordinates of $D$.

A: Hint: If to go from D to A you move $x$ across and $y$ up, then to move from A to C which is perpendicular you move by $\lambda y$ across and $-\lambda x$ up (in this case down, hence the negative). Find the proportionality ratio $\lambda$ that makes you meet the x-axis.


text:
Q: Camera projection of mesh using opengl I have a set of camera parameters (rotation, translation, focal length etc) that I have obtained from SFM pipeline. I also have a mesh in the form of ply file. For each camera, I want the projection of the mesh onto an image with respect to that camera. In other words, the output is an image of how the camera looks at the mesh. I know that I can use openGL for that, but unfortunately I have no knowledge in openGL. I looked up this page for an answer, but I don't know how I can use the camera parameters in here.

A: Just in case if someone has the same problem. I found an interesting article over the internet that solved my problem.
http://ksimek.github.io/2013/06/03/calibrated_cameras_in_opengl/
The same article also describes how we can decompose a camera matrix to intrinsic and extrinsic parameters, and how we can plug them into opengl paradigm.


text:
Q: How can we override a class in prestashop without placing it in the override folder? i would like to override the HTMLTemplate class but my customer customizes prestashop core elements directly (which is a bad practiceà and his disabled overrides from BO so that any developed modules cannot override any prestashop class or template. my question is can we override a class in prestashop without insert it into override folder in our module? and if yes how can we do it?

A: You can modify load method in PrestaShopAutoload class, ignore default behavior and require your override class from your path if $className parameter == HTMLTemplate
It is bad practice too, but if you need to override more classes you only touch one core file, not several.
If overrides have been disabled you must use workarounds.


text:
Q: Click button inside listview then trigger gridview to load its button list on android studio I have a listview, from database (category list) and i want to load gridview (product gridview) when i click any button in the category listview, i'm able to make the listview and gridview, but cannot connect them, since im still new at android programming and have no clue to do it.
my main purpose is:

*

*List category

*on click on the category button will load gridview of product button

*on click product button will add the product id to table cart

ps: if you notice i do SQL query in the mainActivity class, i still new at the code so i tried my best first before convert into better practice.
Any suggestion to do it?
Here i include my snippet:
Category.java (setter and getter)
public class Category {
    private int _id;
    private String _name;

    public Category() {

    }

    public Category(int id, String name) {
        this._id = id;
        this._name = name;
    }

    public Category(String name) {
        this._name = name;
    }

    public int getID() {
        return this._id;
    }
    public void setID(int id) {
        this._id = id;
    }

    public String get_name()
    {
        return this._name;
    }
    public void set_name(String name)
    {
        this._name = name;
    }

}

CategoryListAdapter.java
public class CategoryListAdapter extends BaseAdapter {
    private ArrayList<Category> listData;
    private LayoutInflater layoutInflater;

    public CategoryListAdapter(Context aContext, ArrayList<Category> listData) {
        this.listData = listData;
        layoutInflater = LayoutInflater.from(aContext);
    }

    @Override
    public int getCount() {
        return listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        CategoryListAdapter.ViewHolder holder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.listview_category, null);
            holder = new CategoryListAdapter.ViewHolder();
            holder.btnCategory = (Button) convertView.findViewById(R.id.btnCategory);

            convertView.setTag(holder);
        } else {
            holder = (CategoryListAdapter.ViewHolder) convertView.getTag();
        }

        holder.btnCategory.setText(listData.get(position).get_name());

        return convertView;
    }

    static class ViewHolder {
        Button btnCategory;
    }
}

listview_category.xml (layout that will be repeated)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:textStyle="bold"
        android:textSize="16dp"
        android:id="@+id/btnCategory"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:background="@drawable/button_category"/>

</LinearLayout>

listview inside MainActivity
<ListView
        android:id="@+id/listviewCategory"
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

java inside MainActivity
protected void onCreate(Bundle savedInstanceState) {
...
/* LIST CATEGORY TO LOAD PRODUCT */
        ArrayList list_category = getListCategory();
        final ListView listview_category = (ListView) findViewById(R.id.listviewCategory);
        listview_category.setAdapter(new CategoryListAdapter(this, list_category));
listview_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position,
                                    long id) {
                Log.d(TAG, "click cat");
                //Give product list an id from category_id get from here
            }
        });
...
}

/* List Category for selecting category product */
    private ArrayList getListCategory() {
        SQLiteDatabase mydatabase = openOrCreateDatabase("posDb",MODE_PRIVATE,null);
        Cursor resultSet = mydatabase.rawQuery("Select * from categories",null);

        ArrayList<Category> results = new ArrayList<Category>();
        if (resultSet.moveToFirst()) {
            do {
                Category categoriesData = new Category();
                categoriesData.set_name(resultSet.getString(1));
                results.add(categoriesData);
            } while (resultSet.moveToNext());
        }
        return results;
    }

The grid of product mostly the same as category, but load product from database which later i want to onclick the product button to save record to cart table

A: on Click on button will add the product id in to table_cart

*

*MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   // ArrayList list_category = getListCategory();

    int id[]={1, 2, 3, 4, 5};
    String categoryName[]={"category1","category2","category3","category4","category5"};
    ArrayList<Category> listData=new ArrayList<>();
    Category category;
    for (int i=0; i<id.length; i++)
    {
        category=new Category();
        category.set_id(id[i]);// setting Id
        category.set_name(categoryName[i]);// setting category name
        listData.add(category);
    }
    final ListView listview_category = (ListView) findViewById(R.id.listviewCategory);
    listview_category.setAdapter(new CategoryListAdapter(this, listData ));

}

}

*CategoryListAdapter.java
public class CategoryListAdapter extends BaseAdapter {
    private ArrayList listData;
    private LayoutInflater layoutInflater;
    ArrayList table_cart = new ArrayList();
    private static final String TAG = "CategoryListAdapter";
public CategoryListAdapter(Context aContext, ArrayList<Category> listData) {
    this.listData = listData;
    layoutInflater = LayoutInflater.from(aContext);
}

@Override
public int getCount() {
    return listData.size();
}

@Override
public Object getItem(int position) {
    return listData.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    final CategoryListAdapter.ViewHolder holder;
    if (convertView == null) {
        convertView = layoutInflater.inflate(R.layout.listview_category, null);
        holder = new CategoryListAdapter.ViewHolder();
        holder.btnCategory = (Button) convertView.findViewById(R.id.btnCategory);

        convertView.setTag(holder);
    } else {
        holder = (CategoryListAdapter.ViewHolder) convertView.getTag();
    }

    holder.btnCategory.setText(listData.get(position).get_name());

    holder.btnCategory.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // getting product id
            int product_id = listData.get(position).getID();
            Log.e(TAG, "product_id: " + product_id);

            // now you can get category name as well
            String category_name = listData.get(position).get_name();
            Log.e(TAG, "category_name: " + category_name);

            // now adding product id in to table_cart
            table_cart.add(listData.get(position).getID());
        }
    });

    return convertView;
}

static class ViewHolder {
    Button btnCategory;
}

}

*Category.java
public class Category {
    private int _id;
    private String _name;
public int getID() {
    return this._id;
}

public void setID(int id) {
    this._id = id;
}

public String get_name() {
    return this._name;
}

public void set_name(String name) {
    this._name = name;
}

public void set_id(int _id) {
    this._id = _id;
}

}

*there is no need to change layouts

A: Add on click listener for category button, add grid view in fragment and open fragment on button click.
 holder.btnCategory.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ProductFragment nextFrag= new ProductFragment();
 this.getFragmentManager().beginTransaction()
 .replace(R.id.Layout_container, nextFrag,TAG_FRAGMENT)
 .commit();
        }
    });


text:
Q: Angular animation not working (no transition between state) I'm trying to implement a shadow background when a menu is opened.
Here is a stackblitz https://stackblitz.com/edit/angular-xve6ju
I don't understand what's missing, it should be working but there is no transition between the states.

A: You have a few problems in your code.
Firstly, isMenuOpen is supposed to have states of 'out' and 'in' but you've defined it as a boolean?
Secondly, you've specified your trigger [@fadeInOutAnimation] twice in your html.
You're also setting isMenuOpen to true with your Animate button, which will achieve nothing.
Take a look at this amended working StackBlitz of your example.

A: ts:
import { Component } from '@angular/core';
import {animate, state, style, transition, trigger} from '@angular/animations';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  animations: [
    trigger('fadeInOutAnimation', [
        state('out', style({
          opacity: 0
        })),
        state('in',  style({
          opacity: 1
        })),
        transition('out=>in', [
          animate('5s')
        ])
    ])
  ]
})
export class AppComponent  {
  name = 'Angular';

  currentState = 'out';
  changeState() {
    this.currentState = this.currentState === 'in' ? 'out' : 'in';
  }
}

html:
<div
*ngIf="isMenuOpen"
(click)="changeState()"
[@fadeInOutAnimation]="currentState"
class="shadow-background"
></div>

<button (click)="isMenuOpen = true">Animate</button>

stackblitz : https://stackblitz.com/edit/angular-qzn3es


text:
Q: How to resolve Missing Powerpoint 15 Object Library Error I have written a macro that exports from excel to powerpoint and have gotten it to work properly in Excel/Powerpoint 2013, 2010.
However I tested it on another version of Excel 2010 and got a VBA error that it was missing powerpoint object library 15. I tried running the macro with powerpoint library 14 and was able to but it wasn't reformatting the slides or doing a lot of the formatting that I was doing.
What is the best way/easiest way to install an object library. Can I browse and import the file from the reference tab? If so how can I locate a dl file for the object library? I need to tell a client so i'm trying to make this as easy as possible.
Note My code is below. I am having a hard time changing this to early binding per adam's feedback below.
  Sub CopyDataToPPT()
'Const ppLayoutBlank = 12
Dim objWorkSheet As Worksheet
Dim objRange As Range
Dim objPPT As Object
Dim objPresentation As Object
Dim shapePPTOne As Object
Dim intLocation, intHeight, inLayout As Integer
Dim strRange As String
Dim boolOK As Boolean

Application.ScreenUpdating = False
'Set objWorkSheet = ThisWorkbook.ActiveSheet

Set objPPT = CreateObject("PowerPoint.Application")

objPPT.Visible = True
inLayout = 1

Set objPresentation = objPPT.Presentations.Add

    boolOK = False
        strRange = "p19:y48"  '<- here
        intHeight = 430
        boolOK = True

    If boolOK = True Then
        Set objslide = objPresentation.Slides.Add(1, inLayout)
        objPresentation.Slides(1).Layout = ppLayoutTitleOnly

        objPresentation.Slides(1).Shapes.Title.TextFrame.TextRange.Text = "Reebok- " & Sheets("Brand Personality").Cells(3, 2)

        Set objRange = Sheets("Brand Personality").Range(strRange)
        objRange.Copy

        DoEvents
        Set shapePPTOne = objslide.Shapes.PasteSpecial(DataType:=ppPasteEnhancedMetafile, Link:=msoFalse)

        shapePPTOne(1).Left = 220
        shapePPTOne(1).Top = 100
        shapePPTOne(1).Height = intHeight

        Application.CutCopyMode = False
    End If

A: The library can not be installed just by itself. The simpler way in this situation is to use late binding in your code which should remove the library dependency. Here is a good primer on the differences between early and late binding.


text:
Q: Right click contextMenu on QPushButton For my app I have created a GUI in Qt Designer and converted it into python(2.6) code.
On some of the QPushButton (created with the designer) I want to add a right click context menu. The menu options depend on the application status.
How to implement such a context menu ?

A: Check if an example below would work for you. The key thing is to set context menu policy for your widget to CustomContextMenu and connect to the widget's customContextMenuRequested signal:
import sys
from PyQt4 import QtGui, QtCore

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        # create button
        self.button = QtGui.QPushButton("test button", self)
        self.button.resize(100, 30)

        # set button context menu policy
        self.button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.button.customContextMenuRequested.connect(self.on_context_menu)

        # create context menu
        self.popMenu = QtGui.QMenu(self)
        self.popMenu.addAction(QtGui.QAction('test0', self))
        self.popMenu.addAction(QtGui.QAction('test1', self))
        self.popMenu.addSeparator()
        self.popMenu.addAction(QtGui.QAction('test2', self))

    def on_context_menu(self, point):
        # show context menu
        self.popMenu.exec_(self.button.mapToGlobal(point))

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()


text:
Q: How to Use Neo4j Load CSV on Azure? I've followed this tutorial to deploy Neo4j on Azure:
https://neo4j.com/blog/deploy-neo4j-microsoft-azure-part-2/
Does anyone know how to use Load CSV? Or something similar.
I have 2 Mi Nodes that I tested locally, but I'd like to test the performance in the cloud.


text:
Q: GPO cannot copy MSI from NETLOGON share - but when the file is renamed it can be copied I have a Computer GPO in a Windows Active Directory based network (with on-premises Domain Controllers) that currently installs an application from \\MYDOMAIN\NETLOGON\...\application.msi at startup. This works well for all my machines that are network connected at boot, but I have a growing number of Windows users connecting via VPN, which means that the machine is not network connected until some point after user login.
In the absence of any obvious best practice alternative my proposed solution is to copy the application.msi to a hidden dedicated folder C:\localapps and to install from there.
The top-level folder creation works well. Copying the configuration file works well. Inherited permissions on the folder tree work well. What doesn't work is that the application.msi file cannot be copied.
Frustratingly, if I rename application.msi to application.msi.zzz the same GPO can - and does - copy the file to the local machine quite happily.
Further research, psexec -i -s explorer.exe gives me an Explorer window running as the GPO's SYSTEM account. Indeed, I can navigate to the appropriate place on \\MYDOMAIN\NETLOGIN and I can copy files from there unless they are named as executables or installers. All files in the folder have inherited permissions and I have confirmed they are the same. All files are "unblocked". All files have the same owner (MYDOMAIN\Administrators). I'm not trying to execute the MSI from the network share, just to copy it.
Empirical conclusion: the SYSTEM account used by the GPO cannot copy *.msi or *.exe files from the \\MYDOMAIN\NETLOGON\ share.
This doesn't seem to be a reasonable state of affairs, so how do I get my GPO to copy the application.msi as is, so that at the next opportunity it can be installed from the local disk?

A: Embarassingly, it turned out to be the Intrusion Detection System in my client antivirus, ESET Endpoint Security, blocking any access to executables on what it thought was an untrusted SMB network connection.
I've modified the organisational policy to disable this particular test for files on the Domain Controllers (none of which is on the same LAN as any of the client computers) and all seems well.


text:
Q: What is the initial condition of the current in the capacitor? I have a problem solving this circuit using differential equations:

For t>0 we have

$$\frac{V_c}{2}+i=4$$
$$\frac{1}{2\times 2}\int_{t_0}^{t}i({\tau})\,d\tau+i(t)=4$$
$$\frac{di(t)}{dt}+\frac{1}{4}i(t)=0$$
Solving the differential equation gives me
$$i(t)=I_0 e^{-0.25t}$$
where \$I_0=i(0)\$.
The problem is that \$I_0\$ gives me 0. I know if I solve for \$v_c\$ then I can get \$i(t)\$, deriving, and finally I get
$$I_0=-6\,\mbox{A}$$
How do I know this is true?

A: Hint: At \$t=0^+\$, what's the voltage across the 6 Ω resistor? Therefore how much current is flowing through it?
And what's the voltage across the 3 Ω resistor? Therefore how much current is flowing through it?
Using those results and KCL, you can get the current through the capacitor.

Alternative solution: what is the Thévenin equivalent circuit of the source and two resistors? Given the voltage across the capacitor at \$t=0^+\$, what then is the current through the capacitor?

A: Let's say that the circuit was running for a long time before the switch alters its state (from 60V source to 24V source). This means that capacitor was fully charged. But what was its voltage?
In DC circuits, caps are considered open-circuits (and inductors short-circuits) in steady-state. Hence, we have a voltage divider - 60V source, R1 = 6 Ω and R2 = 3 Ω. So
\$V_{3Ω} = V_C = \frac{3}{3+6}60=20V\$
We conclude that \$V_C(0) = 20V\$
Now, based on the second figure, let's say that the current of 6Ω resistor is entering the node Vc and current of 3Ω resistor is exiting. KCL:
\$\frac{V_C-24}{6}=\frac{V_C}{3}+I_C\$
but
\$I_C=C\frac{dV_C}{dt}\$
Now we have the D.E. and can solve it to find every voltage and current of the circuit.


text:
Q: Aptana Studio 3 No local history available for selected resource This problem is happening under OSX 10.11.2 with Aptana Studio 3.6.1 "AS3"
I created a folder on my hard drive named it projectFolder, and some subfolders with some html/css/js files. Then using a different editor, I did some coding. Then started AS3, right click on projectFolder and did Promote to Project, accepted the default with Project Type = Web, then edited my.html file and saved it.
In the Project Explorer on my.html, RightClick > Compare With > Local History...
but a pop up window saying "No local history available for selected resource".
Please help me find what I am doing wrong in order to get this functionality to work.
Thanks


text:
Q: Testing ruby superclass inherited functionality with rspec Given that I have an abstract class which provides inherited functionality to subclasses:
class Superclass
  class_attribute :_configuration_parameter

  def self.configuration_parameter config
    self._configuration_parameter = config
  end

  def results
    unless @queried
      execute
      @queried = true
    end

    @results
  end

  private

  # Execute uses the class instance config
  def execute
    @rows = DataSource.fetch self.class._configuration_parameter
    @results = Results.new @rows, count
    post_process
  end

  def post_process
    @results.each do |row|
      # mutate results
    end
  end
end

Which might be used by a subclass like this:
class Subclass < Superclass
  configuration_parameter :foo

  def subclass_method
  end
end

I'm having a hard time writing RSpec to test the inherited and configured functionality without abusing the global namespace:
RSpec.describe Superclass do
  let(:config_parameter) { :bar }

  let(:test_subclass) do
    # this feels like an anti-pattern, but the Class.new block scope
    # doesn't contain config_parameter from the Rspec describe

    $config_parameter = config_parameter

    Class.new(Superclass) do
      configuration_parameter $config_parameter
    end
  end

  let(:test_instance) do
    test_subclass.new
  end

  describe 'config parameter' do
    it 'sets the class attribute' do
      expect(test_subclass._configuration_parameter).to be(config_parameter)
    end
  end

  describe 'execute' do
    it 'fetches the data from the right place' do
      expect(DataSource).to receive(:fetch).with(config_parameter)
      instance.results
    end
  end
end

The real world superclass I'm mocking here has a few more configuration parameters and several other pieces of functionality which test reasonably well with this pattern.
Am I missing something obviously bad about the class or test design?
Thanks

A: I'm just going to jump to the most concrete part of your question, about how to avoid using a global variable to pass a local parameter to the dummy class instantiated in your spec.
Here's your spec code:
let(:test_subclass) do
  # this feels like an anti-pattern, but the Class.new block scope
  # doesn't contain config_parameter from the Rspec describe

  $config_parameter = config_parameter

  Class.new(Superclass) do
    configuration_parameter $config_parameter
  end
end

If you take the value returned from Class.new you can call configuration_parameter on that with the local value and avoid the global. Using tap does this with only a minor change to your existing code:
let(:test_subclass) do
  Class.new(SuperClass).tap do |klass|
    klass.configuration_parameter config_parameter
  end
end

As to the more general question of how to test functionality inherited from a superclass, I think the general approach of creating a stub subclass and writing specs for that subclass is fine. I personally would make your _configuration_parameter class attribute private, and rather than testing that the configuration_parameter method actually sets the value, I'd instead focus on checking that the value is different from the superclass value. But I'm not sure that's in the scope of this question.


text:
Q: Quick question on abundant numbers is this correct?
1) Show that if $\sigma (n) > 2n$ it follows $ \sigma (kn) > 2(kn)$.
Proof: $\sigma (kn) \ge \sum_{d|n} kd = k\cdot \sigma(n) > k2n = 2kn$.
How can I show  $\sigma (kn) \ge \sum_{d|n} kd$?
2) Show that if $\sigma (n) = 2n$ it follows $ \sigma (kn) = 2kn$.
???

A: Statement 2 is not true, indeed
If $\sigma(n)=2n$, it follows that $\sigma(kn)>2kn$
Proof:
$$\sigma(kn)=\sum_{x|kn}x\ge\color{red}1+\sum_{y|n}ky=1+k\sigma(n)=1+2kn>2kn
$$
(Since $\color{red}1$ is not of the form $ky$ for a divisor $y$ of $n$, but $\color{\red}1$ certainly divided $kn$.)
This proof also can prove statement 1.


text:
Q: How to sort / display Reviews based on rating - Magento 2 I want to display reviews but by sorting them (displaying the highest rating to the lowest rating).
This is how I got the reviews for each product
// Get reviews for each product
    public function getReviewCollection($productId){
        $product = $this->productRepository->getById($productId);
        $collection = $this->_reviewCollection->create()
            ->addStatusFilter(
            \Magento\Review\Model\Review::STATUS_APPROVED
            )->addEntityFilter(
            'product',
            $productId
            )->setDateOrder()
            ->addRateVotes();

        return $collection->getItems(); //Get all review data of product
    }

In my phtml file:
$reviews = $block->getReviewCollection($_item->getID());
if (count($reviews) > 0) {
    foreach ($reviews->getItems() as $review) {
        foreach( $review->getRatingVotes() as $vote ) {
            $ratings[] = $vote->getPercent();
        }
    }
}

How can I sort the reviews based on the $ratings?


text:
Q: Remove commas within numbers only I have a list of product sales (and their cost) which have frustratingly been concatenated into a single string, separated by commas. I ultimately need to separate out each product into unique rows which is easy enough with stringr::str_split.
However, the cost associated with each product has comma to show thousands e.g. 1,000.00 or 38,647.89. Therefore str_split is splitting products incorrectly as it hits commas within a product's cost.
I was wondering what the best tidyverse solution would be to remove all commas which are surrounded by numbers so that 1,000.00 becomes 1000.00 and 38,647.89 becomes 38647.89. Once these commas are removed I can str_split on the commas which delimit the products and thus split each unique product into its own row.
Here is a dummy dataset:
df<-data.frame(id = c(1, 2), product = c("1 Car at $38,678.49, 1 Truck at $78,468.00, 1 Motorbike at $5,634.78", "1 Car at $38,678.49, 1 Truck at $78,468.00, 1 Motorbike at $5,634.78"))

df

  id                                                              product
1 1 Car at $38,678.49, 1 Truck at $78,468.00, 1 Motorbike at $5,634.78
2 1 Car at $38,678.49, 1 Truck at $78,468.00, 1 Motorbike at $5,634.78

Expected outcome:
  id                                                              product
1  1 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78
2  2 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78

A: df %>%
  mutate(product = product %>% str_replace_all("([0-9]),([0-9])", "\\1\\2"))

Result
  id                                                           product
1  1 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78
2  2 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78

A: > apply(df,1,function(x){gsub(",([0-9])","\\1",x[2])})

[1] "1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78"
[2] "1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78"

A: A way via base R can be,
sapply(strsplit(as.character(df$product), ' '), function(i)paste(sub(',', '', i), collapse = ' '))
#[1] "1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78" "1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78"

A: library(tidyverse)
df$product <- str_replace_all(df$product, "(?<=\\d),(?=\\d)", "")
df
  id                                                           product
1  1 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78
2  2 1 Car at $38678.49, 1 Truck at $78468.00, 1 Motorbike at $5634.78


text:
Q: Evidence-preserving LUB constraint for HList I think I need a HList that is constrained to have all of its elements being a subtype of a certain type. LUBConstraint seems to be what I want, and indeed it does constrain the construction of such a HList - but I can't see how to get the evidence out again, so that I can map (actually, traverse, because it needs to be monadic) over the HList and call a method (that exists in the LUB type) on each of the elements.
In addition, I want the type of the HList resulting from the traverse operation to be exactly the same type as the type of the input HList.
The use case is a kind of functional "listener list" - all of the elements of the HList are "listeners" which must be notified of "events", accept or reject them, and return new versions of themselves with updated "internal state". If that was all I needed, then I could just use an ordinary immutable Scala collection. But I also want direct typed access to individual elements without using asInstanceOf - hence the motivation for trying to use HList.

A: In general if you have some operation that you want to perform on all of the elements in an HList, you'll want to map a polymorphic function value over the HList. For example, suppose I have the following setup:
trait Listener[L <: Listener[L]] {
  def handle(s: String): Option[L]
}

class FooListener extends Listener[FooListener] {
  def handle(s: String) =
    if (s.size == 3) Some(this) else None
}

class BarListener extends Listener[BarListener ]{
  def handle(s: String) = Some(this)
}

import shapeless._

val listeners = new FooListener :: new BarListener :: HNil

Now I want to send a String to each of these listeners and gather the results. If I just wanted to send a fixed value, this would be easy:
object event123 extends Poly1 {
  implicit def listener[L <: Listener[L]] = at[L](_.handle("123"))
}

val result = listeners.map(event123)

Which will be appropriately typed as an Option[FooListener] :: Option[BarListener] :: HNil. If I'm using shapeless-contrib, I can sequence this HList:
import scalaz._, Scalaz._, shapeless.contrib.scalaz._

val sequenced: Option[FooListener :: BarListener :: HNil] = sequence(result)

Or just use traverse:
traverse(listeners)(event123)

Unfortunately there are restrictions on how polymorphic function values can be defined that mean that partial application isn't convenient, so if we don't know the String we're sending at compile time, this is a lot more complicated:
object event extends Poly1 {
  implicit def listener[L <: Listener[L]] = at[(L, String)] {
    case (listener, string) => listener.handle(string)
  }
}

traverse(listeners.zip(listeners.mapConst("123")))(event)

Where we've zipped the elements with the string and then mapped a polymorphic function that takes tuples over the result. There are other ways you could do this using more or less the same approach, but none of them are terribly clear.
A completely different approach is just to skip the polymorphic function values and define a new type class:
trait Notifiable[L <: HList] {
  def tell(s: String)(l: L): Option[L]
}

object Notifiable {
  implicit val hnilNotifiable: Notifiable[HNil] = new Notifiable[HNil] {
    def tell(s: String)(l: HNil) = Some(HNil)
  }

  implicit def hconsNotifiable[H <: Listener[H], T <: HList](implicit
    tn: Notifiable[T]
  ): Notifiable[H :: T] = new Notifiable[H :: T] {
    def tell(s: String)(l: H :: T) = for {
      h <- l.head.handle(s)
      t <- tn.tell(s)(l.tail)
    } yield h :: t
  }
}

def tell[L <: HList: Notifiable](s: String)(l: L) =
  implicitly[Notifiable[L]].tell(s)(l)

And then:
val sequenced: Option[FooListener :: BarListener :: HNil] =
  tell("123")(listeners)

This is less generic (it only works on Option, not arbitrary applicatives), but it doesn't require an extra dependency for sequencing, and it's arguably a little less muddled than jumping through hoops to partially apply a polymorphic function value because of weird limitations of the compiler.


text:
Q: how to get selected item in pyqt Qmenu is there any way to get the selected item in a qmenu ?
i want to bind all items in that list to one function and get the item once user click it .
i've been looking for a way to get the item's label or index for 3 days , but couldn't find it .
any ideas ?
thanks in advance

A: You can achieve this with signals.
Connect all triggered slots of your menu items to your function. Then, in this function, use the static function QObject::sender to retrieve the menu item which has sent the signal.


text:
Q: SwiftUI preview fails when using UIHostingController when creating UIHostingController outside viewDidLoad I have some code that causes SwiftUI previews to fail but will run successfully in the simulator and on a device. The SwiftUI previews failure diagnostics message is:
PreviewUpdateTimedOutError: Updating took more than 5 seconds

Updating a preview from ViewControllerPreviews in NestedTest.app (9218) took more than 5 seconds.

I have boiled the issue down to a minimal amount of code:
import SwiftUI
import UIKit

let createHostInInit = true

class ViewController: UIViewController {
    private var host: TestViewHost? = nil

    init() {
        if createHostInInit {
            host = TestViewHost()
        }

        super.init(nibName: nil, bundle: nil)
    }

    // Note: this is here to satisfy the compiler and to allow running this
    // in the simulator as part of a default new project.
    required init?(coder: NSCoder) {
        if createHostInInit {
            host = TestViewHost()
        }

        super.init(coder: coder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if !createHostInInit {
            host = TestViewHost()
        }

        if let host = self.host {
            addChild(host)
            self.view.addSubview(host.view)
            host.didMove(toParent: self)
            host.view.frame = self.view.bounds
        }
    }
}

class TestViewHost: UIHostingController<TestView> {
    init() {
        super.init(rootView: TestView())
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

struct TestView: View {
    var body: some View {
        Text("Hi there!")
    }
}

struct UIViewControllerPreviewer: UIViewControllerRepresentable {
    let viewController: UIViewController

    init(viewController: UIViewController) {
        self.viewController = viewController
    }

    func makeUIViewController(context: Context) -> some UIViewController {
        return viewController
    }

    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        // Do nothing because this is only for previews
    }
}

struct ViewControllerPreviews: PreviewProvider {
    static var previews: some View {
        return UIViewControllerPreviewer(viewController: ViewController())
    }
}

If createHostInInit = true then the previews fail. If createHostInInit = false then the previews work. In either of these cases the UI looks correct in the simulator or on a device. So it would seem that something about the preview environment gets cranky about when a UIHostingController is created before viewDidLoad().
Did I miss some documentation for UIHostingController describing these limitations? Is this a bug?
This can be tested in Xcode by creating a new iOS single view project and dropping this code into ViewController.swift.
Thanks


text:
Q: How to sign points on graphics in pyqtgraph? I need your help in pyqtgraph library.
This is what I need:

It is my code. I plot pg.ScatterPlotItem.
w1 = view.addPlot()
w1.setXRange(0, 10)
w1.setYRange(6, 7)
s1 = pg.ScatterPlotItem(size=3, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 255))
dur1 = np.arange(0.1, 5, 2)
data = np.arange(0.1, 5, 2)
s1.setData(x= dur1, y = data) # text = ['A1','A2','A3']
w1.addItem(s1 )