text:
Q: Why does a class weight fraction improve precision compared to undersampling approach where precision drops? I have an imbalanced data where the ratio between positive to negative samples is 1:3 (positive samples are 3 times higher than negative). For my case it is is important to have a higher precision (and lower FPR) even if it comes at the cost of low recall (higher FNs). I intend to reach this goal by training a random forest with a class weight of negative class many times more than the positive class and observe that precision increases (lesser FPs) as I increase the weight of negative class and recall drops (more FNs). This was kind of what I expected. See a sample table below:

Next I also try to see if I can also train the model using an intentionally imbalanced data to introduce a bias towards classification of negative class. I try to achieve this by under-sampling my negative class with different fractions. So 1:10 means my negative samples are ten times more than positive in the training phase. What I observe now is that both the precision and recall go lower as I keep decreasing the number of positive samples in the training (hence making the negative class majority). Why is that Precision drops in this case although the FPR is decreasing? Should precision and FPR not be inversely proportional? Thanks

A: The problem with the second approach is that you're heavily undersampling your positive class. Knowing that your starting ratio of positive:negative is 3:1, it means that in order to get to a 1:1 you are removing exactly 50% of your starting dataset! Once you get to 1:10 you have removed 78% of the starting data... you see the trend here.

In general yes, changing the balance of the classes will result in better classification performance for the majority class. However, if you are also reducing your sample size a lot you will have a generalized decrease in performance, so both your Precision AND Recall will drop.
Finally, you're better off using the first approach, as weighting the classes does not have this type of inconvenients!


text:
Q: Given matrix $A$, find matrix $X$ such that $e^X = A$ Given the following matrix
$$A = \begin{bmatrix} -2 & 2 & 1\\ 2 & -3 & -2\\ -5 & 6 & 4\end{bmatrix}$$
how can we show that there exists a complex matrix $X$ such that $e^X = A$.
I have struggled to find the information about workaround the problem. However, the determinant of matrix $A$ is non-zero and its eigenvalues are $-1$ and $1$.

A: The Jordan form of $A$ is given by $$J = \begin{bmatrix} -1 & 1 & 0 \\ 0 & -1 & 0 \\ 0 & 0 & 1\end{bmatrix}$$
with $A = PJP^{-1}$ where $P = \begin{bmatrix} 1 & 1 & 0 \\ 0 & 1 & -1 \\ 1 & 0 & 2\end{bmatrix}$.
First we can try to find $\log J$ blockwise. Searching for the logarithm of $\begin{bmatrix} -1 & 1 \\ 0 & -1\end{bmatrix}$ again as some Jordan block, if we set $f(x) = e^{-x}$ then
$$\exp\left(\begin{bmatrix} i\pi & -1 \\ 0 & i\pi\end{bmatrix}\right) = f\left(\begin{bmatrix} -i\pi & 1 \\ 0 & -i\pi\end{bmatrix}\right) = \begin{bmatrix} f(-i\pi) & f'(-i\pi) \\ 0 & f(-i\pi)\end{bmatrix} = \begin{bmatrix} -1 & 1 \\ 0 & -1\end{bmatrix}$$
so we can set (clearly it's not unique)
$$\log J = \begin{bmatrix} i\pi & -1 & 0 \\ 0 & i\pi & 0 \\ 0 & 0 & 0\end{bmatrix}$$
and finally we get
$$\log A = P(\log J) P^{-1} = \begin{bmatrix} 1 & -2 & -1 \\ 0 & 0 & 0 \\ 1 & -2 & -1\end{bmatrix}+i\pi \begin{bmatrix} 1 & 0 & 0 \\ -1 & 2 & 1 \\ 2 & -2 & -1\end{bmatrix}.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: 1D wave equation with Boundary Conditions: Fourier Transform solution I am considering the 1D wave equation with $c=1$ for the sake of simplicity:
$$u_{tt}-u_{xx}=0,\quad \forall x\in\mathbb R,\; \forall t\in\mathbb R\tag{1}\label{eq:1}$$
with the following boundary conditions (initial conditions are ignored for now)
$$
\begin{align}
&u(0,t)=0\tag{2}\label{eq:2}\\
&u(L,t)=0\tag{3}\label{eq:3}
\end{align}
$$
for some strictly positive $L$. The boundary conditions are just seen as constraints on the sought solution $u(x,t)$ [By this I mean that the solution $u(x,t)$ is still defined for all $x\in\mathbb R$]. I am using the Fourier Transform approach to solve, that is
$$\hat{u}(x,\omega)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{+\infty}u(x,t)\mathrm{e}^{-i\omega t} \mathrm{d}t$$
When plugged into the wave equation, the ODE governing $\hat{u}(x)$ reads
$$\omega^2\hat{u}(x,\omega)+\hat{u}_{xx}(x,\omega)=0$$
whose general solution is
$$\hat{u}(x,\omega)=A\cos \omega x+B\sin\omega x$$
The Fourier Transform of (2) implies $\hat{u}(0,\omega)=A=0$ while the Fourier Transform of (3) implies $B\sin \omega L=0$, that is
$$ \omega_k=k\pi/L,\quad k=1,2,\ldots\tag{4}\label{eq:4}$$
if we decide to discard vanishing solutions. As a consequence:
$$\hat{u}(x,\omega)=\sum_{k=1}^{\infty}B_k\sin\omega_k x\tag{5}\label{eq:5}$$
which satisfies (1), (2) and (3).

Question My question is on the inverse transform, whose usual definition is
  $$u(x,t)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{+\infty}\hat{u}(x,\omega)\mathrm{e}^{i\omega t}\mathrm{d}\omega,\quad k=1,2,\ldots\tag{6}$$
  Since $\omega$ now takes discrete values $\omega_k$ through (5), what is the meaning of the integral in (6) so that the Inverse Fourier Transform makes sense. In other words, through which mathematical argument can we deduce the definition of the discrete Inverse Fourier Transform from the continuous Inverse Fourier Transform?

Possible "wrong" answer
Solution (5) can we expressed as:
$$\hat{u}(x,\omega)=\sum_{k=1}^{\infty}B_k \langle\delta_{\omega_k} , \sin\omega x\rangle\tag{7}$$
where $\delta_{\omega_k}$ denotes the usual Dirac distribution at $\omega_k$, that is $\delta_{\omega_k}=\delta(\omega-\omega_k)$.
Inserting (7) into (6) yields
$$u(x,t)=\frac{1}{\sqrt{2\pi}}\sum_{k=1}^{\infty}B_k\int_{-\infty}^{+\infty}\langle \delta_{\omega_k} , \sin\omega x\,\mathrm{e}^{i\omega t}\rangle \mathrm{d}\omega\tag{8}$$
which becomes (even though the integral itself is not well defined)
$$u(x,t)=\sum_{k=1}^{\infty}B_k\sin\omega_k x\,\mathrm{e}^{i\omega_k t}$$
as expected (The $B_k$ have been scaled by a factor $\sqrt{2\pi}$). However (8) is not right, mathematically speaking. I'd be interested in a mathematically sound formulation.

A: Equation (5) is wrong. The correct is
$$
\hat{u}(x,\omega) = \sum_{k=1}^{\infty} B_k \sin\omega_k x \, \delta(\omega-\omega_k)
\label{new5}
\tag{5'}
.
$$
Then,
$$\begin{align}
u(x,t)
&= \mathcal{F}^{-1}\{ \hat{u}(x,\omega) \} \\
&= \mathcal{F}^{-1}\left\{ \sum_{k=1}^{\infty} B_k \sin\omega_k x \, \delta(\omega-\omega_k) \right\} \\
&= \sum_{k=1}^{\infty} B_k \, \sin\omega_k x \, \mathcal{F}^{-1}\left\{ \delta(\omega-\omega_k) \right\} \\
&= \sum_{k=1}^{\infty} B_k \, \sin\omega_k x \, \frac{1}{\sqrt{2\pi}} \, e^{i\omega_k t}
.
\end{align}$$
Note:
Equation \eqref{new5} can also be written as
$$
\hat{u}(x,\omega)
= \sum_{k=1}^{\infty} B_k \sin\omega x \, \delta(\omega-\omega_k)
= \sin\omega x \, \sum_{k=1}^{\infty} B_k \delta(\omega-\omega_k)
= B(\omega) \sin\omega x \, \sum_{k=1}^{\infty} \delta(\omega-\omega_k)
,
$$
where $B(\omega_k) = B_k.$ The last sum is called the Dirac comb.


text:
Q: How to prevent foreign key lookup in django I am trying to do the following query:
SELECT * FROM catalog WHERE master_id IS NULL

The master field is a ForeignKey, but in this case, I just need to know whether it is NULL or not so I don't need to do a foreign key lookup. However, if I do:
Catalog.objects.filter(master_id=None).values_list('is_tv', flat=True).count()

Here is the example statement it does:
SELECT ••• FROM `catalog` LEFT OUTER JOIN `main_titlemaster`
    ON (`main_catalog`.`master_id` = `main_titlemaster`.`id`)
    WHERE `main_titlemaster`.`id` IS NULL

How can I prevent this useless FK lookup without diving into raw SQL?

A: You should use __isnull lookup keyword.
Catalog.objects.filter(master__isnull=True).values_list('is_tv', flat=True).count()


text:
Q: Excluding posts from search results page with meta query not working On my search results page I have two loops. First loop displays post by meta value and second loop is "regular" loop that display posts by search query:

            <?php // a "static" custom loop displaying posts by meta value
            $featured_posts = new WP_Query( array(
                'post_type' => array( 'cpt-1', 'cpt-2', 'cpt-3' ),
                'post_status' => 'publish',
                'posts_per_page' => -1,
                'meta_query' => array(
                    array(
                        'key'   => 'highlight', // this is a name of ACF field
                        'value' => '1',
                    )
                )
            ) );

            echo '
';

            if ( $featured_posts ) {
                    echo '
Highlighted posts (' . $featured_posts->found_posts . '):
';

                    while ( $featured_posts->have_posts() ) : $featured_posts->the_post();
                        get_template_part( 'template-parts/content', 'search' );
                    endwhile;

                    wp_reset_postdata();
            } else {
                echo 'No any highlighted post.';
            }

            echo '
';
            ?>

                <?php
                global $wp_query;
                //$allsearch = new WP_Query( 's=' . $s . '&showposts=0' ); ?>

The search results (<?php echo $wp_query->found_posts; //echo $allsearch->found_posts; ?>):

                <?php
                if ( have_posts() ) :
                    //echo '
';

                    while ( have_posts() ) : the_post();
                        get_template_part( 'template-parts/content', 'search' );
                    endwhile;
                    //echo '
'; ?>

                                <?php
                                global $wp_query;

                                $big = 999999999; // need an unlikely integer

                                echo paginate_links( array(
                                    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
                                    'format' => '?paged=%#%',
                                    'current' => max( 1, get_query_var('paged') ),
                                    'total' => $wp_query->max_num_pages,
                                    'prev_text'    => __( '«' ),
                                    'next_text'    => __( '»' ),
                                ) );
                                ?>

                <?php
                else :

                    echo 'No search results.';

                endif; ?>

The highlighted posts are displaying in both loops. Now I want to exclude them from regular search results loop with pre_get_posts :
function my_custom_search_query( $query ) {
    if( ! is_admin() || $query->is_search() ) {
        $query->set('meta_query', array(
            array(
                'key'   => 'highlight',
                'value' => '0'
            )
        ) );
    }

}
add_action('pre_get_posts','my_custom_search_query');

This code does not work properly, because:

*

*it removes posts from both loops on search results page, not from only "regular" loop

*it removes more than highlighted posts...

I also tried to use here $query->is_main_query() with no success.


text:
Q: validation is not working in javaScript <!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Insert title here</title>

    <form>
        Name:<input type="text" id="t1">
 Gender: <input
            type="radio" name="sex" value="male">male <input type="radio"
            name="sex" value="female">female
 <input
            type="submit" value="submit" onClick="myFunction()">
    </form>

I want to validate when there is no input from user and if user is pressing submit button then it should alert "enter any thing" but it is not working.......why I don't know

A: Your function isn't preventing the form from submitting. To do that, you need to return false when you want the form submission to stop, and also use onClick="return myFunction()" to make sure it's passed correctly.
Note however that in up-to-date browsers you can just do this:
<input type="text" required />

The browser will automatically stop form submission if nothing was entered.


text:
Q: How do I produce functional dependencies and corresponding relations from a case study? I need some help with a project I'm doing. I need to clarify the meaning of some of the requirements which I don't get at all. The bold parts are the ones causing me trouble.
I've got a case study, and there are requirements like "create the Entity Relationship diagram", etc. One of the requirements says"

*

*Produce the functional dependencies, and,

*using normalization, a set of corresponding relations for each of the manual records

By the manual records, it means some records that were supposedly filled manually before implementing the system.
Does anyone know what should I create or do with this?, does it ask me for some sort of diagram?.
Then, on another requirement, it says: "combine the sets of relations to produce an overall set of relations(tables) in third normal form" and it also tells me to ensure the relations are consistent with my Entity relationship diagram. So, does anyone know what is asking me to do?

A: "Producing" the functional dependencies requires knowledge of the business domain.
As an IT systems designer, you will always need input from the business side before you can successfully do this task.  What is the business-side input that is available to you ?


text:
Q: How to convert 2D point to 3D using SceneKit's unprojectPoint without having a depth value? Is it possible to use SceneKit's unprojectPoint to convert a 2D point to 3D without having a depth value?
I only need to find the 3D location in the XZ plane. Y can be always 0 or any value since I'm not using it.
I'm trying to do this for iOS 8 Beta.
I had something similar with JavaScript and Three.js (WebGL) like this:
function getMouse3D(x, y) {
    var pos = new THREE.Vector3(0, 0, 0);
    var pMouse = new THREE.Vector3(
        (x / renderer.domElement.width) * 2 - 1,
       -(y / renderer.domElement.height) * 2 + 1,
       1
    );
    //
    projector.unprojectVector(pMouse, camera);

    var cam = camera.position;
    var m = pMouse.y / ( pMouse.y - cam.y );

    pos.x = pMouse.x + ( cam.x - pMouse.x ) * m;
    pos.z = pMouse.z + ( cam.z - pMouse.z ) * m;

    return pos;
};

But I don't know how to translate the part with unprojectVector to SceneKit.

What I want to do is to be able to drag an object around in the XZ plane only. The vertical axis Y will be ignored.
Since the object would need to move along a plane, one solution would be to use hitTest method, but I don't think is very good in terms of performance to do it for every touch/drag event. Also, it wouldn't allow the object to move outside the plane either.
I've tried a solution based on the accepted answer here, but it didn't worked. Using one depth value for unprojectPoint, if dragging the object around in the +/-Z direction the object doesn't stay under the finger too long, but it moves away from it instead.
I need to have the dragged object stay under the finger no matter where is it moved in the XZ plane.

A: First, are you actually looking for a position in the xz-plane or the xy-plane? By default, the camera looks in the -z direction, so the x- and y-axes of the 3D Scene Kit coordinate system go in the same directions as they do in the 2D view coordinate system. (Well, y is flipped by default in UIKit, but it's still the vertical axis.) The xz-plane is then orthogonal to the plane of the screen.
Second, a depth value is a necessary part of converting from 2D to 3D. I'm not an expert on three.js, but from looking at their library documentation (which apparently can't be linked into), their unprojectVector still takes a Vector3. And that's what you're constructing for pMouse in your code above — a vector whose z- and y-coordinates come from the 2D mouse position, and whose z-coordinate is 1.
SceneKit's unprojectPoint works the same way — it takes a point whose z-coordinate refers to a depth in clip space, and maps that to a point in your scene's world space.
If your world space is oriented such that the only variation you care about is in the x- and y-axes, you may pass any z-value you want to unprojectPoint, and ignore the z-value in the vector you get back. Otherwise, pass -1 to map to the far clipping plane, 1 for the near clipping plane, or 0 for halfway in between — the plane whose z-coordinate (in camera space) is 0. If you're using the unprojected point to position a node in the scene, the best advice is to just try different z-values (between -1 and 1) until you get the behavior you want.
However, it's a good idea to be thinking about what you're using an unprojected vector for — if the next thing you'd be doing with it is testing for intersections with scene geometry, look at hitTest: instead.


text:
Q: How to prevent Game Center from altering icon badge? I have an iOS app that until a few months ago used Game Center for turn-based multiplayer functionality. It now uses a custom-built server instead, and I have turned off Game Center for the last versions of the app in iTunes Connect. However, each time I start some other app that does use Game Center, the system removes whatever badge number I have on my icon. As if my app was still Game Center enabled and had no current matches where there was my turn to act.
Is there any way to prevent this lingering Game Center behavior, i.e. to tell Game Center to mind its own business and not to mess with the icon badge anymore?

A: Forgetting to disable Game Center on your app on the iTunes Connect back end can cause this issue


text:
Q: $post->ID and the_id() always return the wrong value I have a site where I display the same exact footer on every page. There is one exception, though. On one certain page I need to change one small part of the footer.
I figure the simplest way to do this is to check, within the footer, whether I'm on that page or not. It wouldn't make sense to change the whole entire footer for that page since I'm only changing a tiny part of the footer, deep within the footer.
The problem is that whenever I call $post->ID or the_id() from within the footer, it gives me an ID that clearly doesn't match the post I'm on. It always gives me 89, no matter what page I'm on in the site.
I figure I must be doing something wrong. Can anyone tell me what it is?

A: It sounds like you are altering the global $post data somewhere (usually another loop). Be sure to call wp_reset_postdata() after you are finished with something that sets up post data in an alternate loop.

A: the_ID just echo the post , it doesn't return the ID,
if you want the ID for the particular post ,
use  <?php get_the_ID(); ?>

A: It may be more reliable to test the status of $the_wp_query, which is the main query for the active page. The value of $post is simply whatever the last loop ended with, so you may have plugins affecting the value.

A: Codex says (emphasis mine):

Displays the numeric ID of the current post. This tag must be within The Loop.

You try to use it in the footer, so failure is very well documented.
Let me suggest this: write a small plugin with its own post ID array (class member or uniquely named global; should be an array in order to deal with pages containing multiple posts).
Create a shortcode that adds the ID of the current post to this array. In the footer, you can read all IDs you need from it and you can be sure no one has tempered with them.

A: My issue was I has assigning other values to the $post. I renamed $post to something else and it works.


text:
Q: Remove last line from string How do I remove the last line "\n" from a string, if I dont know how big the string will be?
var tempHTML = content.document.body.innerHTML;
var HTMLWithoutLastLine = RemoveLastLine(tempHTML);

function RemoveLastLine(tempHTML)
{
   // code
}

A: A regex will do it. Here's the simplest one:
string.replace(/\n.*$/, '')

See regex101 for how it works
\n matches the last line break in the string
.* matches any character, between zero and unlimited times (except for line terminators). So this works whether or not there is content on the last line
$ to match the end of the string

A: Try:
if(x.lastIndexOf("\n")>0) {
    return x.substring(0, x.lastIndexOf("\n"));
} else {
    return x;
}

A: You can use a regular expression (to be tuned depending on what you mean by "last line"):
return x.replace(/\r?\n?[^\r\n]*$/, "");

A: In your specific case the function could indeed look like:
function(s){
  return i = s.lastIndexOf("\n")
    , s.substring(0, i)
}

Though probably you dont want to have spaces at the end either; in this case a simple replace might work well:
s.replace(/s+$/, '')

Keep in mind however that new versions of Javascript (ES6+) offer shorthand ways of doing this with built-in prototype functions (trim, trimLeft, trimRight)
s.trimRight()

Cheers!

A: Make the string to an array and pop away the last line.
The value from the pop is not used, so it go to the void.
function RemoveLastLine(x) {
    x = x.split('\n');
    x.pop();
    return x.join('\n')
}

Make it back to a string with Array.join()


text:
Q: Ref workbook by path and name - VBA Sub Quack()

Dim LookupWB As Workbook
Set LookupWB = Application.Workbooks("C:\Users\user1\Desktop\Book1.xlsx")

End Sub

This code gives an error:

Subscript out of range
  I think it's because of the "Set" line.
  How do you correctly reference a workbook by path?

If I write: Set LookupWB = Application.Workbooks("Book1.xlsx") (without full path) it work perfectly.
Thanks a lot!

A: I think you need to use the Open function first:
Workbooks.Open Filename:="C:\Users\user1\Desktop\Book1.xlsx"
Set LookupWB = Application.Workbooks("Book1.xlsx")

A: If the workbook is already open, you don't need to include the path. That's why Set LookupWB = Application.Workbooks("Book1.xlsx") works.
If the workbook is closed, then you have to include the Open function (see @thornomad's answer).


text:
Q: How to Update value in MultiValueMap for a specific key I have a MultiValueMap like
{3=[c-2, c-2], 2=[b-1, b-1], 1=[a-1, a-2, a-3]}

At one point I have to update a single value of a specific key
for example I have to update the key 2 like
2=[u-1,u-2]

how can i do this?

A: I've never used that library - but I would expect these two examples to do what you need:
multiMap.getCollection(2).clear();
multiMap.putAll(2, Arrays.asList("u-1", "u-2"));

Or
Collection c = multiMap.getCollection(2);
c.clear();
Collections.addAll(c, "u-1", "u-2");

A: The safest way is to call getCollection() to retrieve the current mapping, remove(key) to clear that mapping, iterate the retrieved collection to re-insert values that you want to keep, and/or add the new values.
If you know the type of collection used for a mapping (because you've called the constructor that takes collectionFactory), you could get the collection and update it directly.


text:
Q: Django validating time slot This is my models to store availability of particular time when a new booking there
class TimeSlot(models.Model):
day = models.ForeignKey(
    Day,
    on_delete=models.CASCADE,
    related_name="time"
)
booking = models.ForeignKey(
    Booking,
    on_delete=models.CASCADE,
    related_name="time"
)
start_hour = models.TimeField()
end_hour = models.TimeField()

class Meta:
    unique_together = [('end_hour', 'start_hour',)]

def clean(self):
    pass

Currently it's allowing booking even those are considered as duplicate in terms of end_hour and start_hour. I want to prevent the slot, so that no new booking shouln't placed between a range that already booked.
Can anyone know how to do it with the range?

A: I assume the problem is that start_hour and end_hour that fall within an already existing time range are allowed to be added. Of course the unique_together constraint cannot handle this as it only deals with uniqueness not uniqueness in a range. Instead you can override your models clean method and perform this validation there:
from django.db.models import Q
from django.core.exceptions import ValidationError

class TimeSlot(models.Model):
    day = models.ForeignKey(
        Day,
        on_delete=models.CASCADE,
        related_name="time"
    )
    booking = models.ForeignKey(
        Booking,
        on_delete=models.CASCADE,
        related_name="time"
    )
    start_hour = models.TimeField()
    end_hour = models.TimeField()

    class Meta:
        unique_together = [('end_hour', 'start_hour',)]

    def clean(self):
        start_hour_in_range = Q(start_hour__lte=self.start_hour, end_hour__gte=self.start_hour)
        end_hour_in_range = Q(start_hour__lte=self.end_hour, end_hour__gte=self.end_hour)
        # Queryset that finds all clashing timeslots with the same day
        queryset = self._meta.default_manager.filter(start_hour_in_range | end_hour_in_range, day=self.day)
        if self.pk:
            queryset = queryset.exclude(pk=self.pk) # Exclude this object if it is already saved to the database
        if queryset.exists():
            raise ValidationError('An existing timeslot clashes with the given one!')

Next if you are using a ModelForm this method would be called automatically or if you are not you can call instance.full_clean() which will call this method and all other cleaning methods on the model (clean_fields and validate_unique).


text:
Q: Create Serial Number with a String in oracle I am using the following code in oracle on create record trigger to create a serial number. I want my serial number like LM0001 . Using LM000 STRING WITH NUMBER and concat both to generate the serial number. I am getting error ora-06502. Need help where i am doing wrong. Where should i modify the code
DECLARE
VCAN varchar2(40);
L number (10);
BEGIN
 SELECT MAX(SL_NO)INTO VCAN FROM LAND_MANAGEMENT;
IF VCAN > 0 THEN
  L := VCAN + 1;
  :LAND_MANAGEMENT.SL_NO := 'LM000' || L;
ELSE
    :LAND_MANAGEMENT.SL_NO := 'LM000' || 1;
END IF;
EXCEPTION
 WHEN NO_DATA_FOUND THEN
  :LAND_MANAGEMENT.SL_NO := 'LM000'|| 1;
END;

A: Solved the problem using sequence

create a sequence

 CREATE SEQUENCE LMANAGEMENT_SEQ
  START WITH 21
 MAXVALUE 9999999999999999999999999999
 MINVALUE 0
 NOCYCLE
 CACHE 20
 NOORDER;

sql query in when-create-record trigger
select 'LM' || to_char(lmanagement_seq.nextval, '000000') INTO
:land_management.sl_no
from dual;


text:
Q: Calculating error for $\pi$ in an expansion I have the following equation: $\quad\pi = 4\arctan(1/2) + 4\arctan(1/3).$

I want to calculate how many terms of the expansion ($n$) I have to calculate in order for the error to be less than  $10^{-10}$.

I have an idea for the method to be used:
Taking the power series of $\arctan(x)$ and using the remainder integral of the form $$R_n \;=\; \int\frac{{(-1)^n t^{2n}}}{1+t^2}\,dt.$$
So I want the sum of the two remainders from the expansion of each $\arctan(x)$ to be $<$ $\frac{10^{-10}}{4}$.
$$\int_0^{1/2}\frac{{(-1)^n t^{2n}}}{1+t^2}\,dt \;+\; \int_0^{1/3}\frac{{(-1)^n t^{2n}}}{1+t^2}\,dt\;<\; \frac{10^{-10}}{4}.$$
Now to solve this, I can't do without making approximations since $t^{2n} > \frac{{(-1)^n t^{2n}}}{1+t^2}$ on my intervals; I approximate using this, getting $$\int_0^{1/2}t^{2n}\,dt \;+\; \int_0^{1/3}t^{2n}\,dt.$$
Evaluating, I get $$\frac{(1/2)^{2n+1}}{2n+1} + \frac{(1/3)^{2n+1}}{2n+1} < \frac{10^{-10}}{4}.$$
I have no idea how to solve this. Would I make another approximation? Or is my method completely wrong to start with.
Edit:
After making some huge approximations i.e. getting rid of the $2n+1$'s on the denominator and setting $1/3$ to be $1/2$, I got that $2n+1 =36.$ However, I am not sure whether this is correct.

A: As the Taylor expansion of $\arctan=\sum _{n=1}^{\infty } \frac{(-1)^{n+1} x^{2 n-1}}{2 n-1}$ is an alternating series, the error is less than the abs value of the first term neglected, that is equivalent to find an $n$ such that
$$\frac{4 \left(\frac{1}{2}\right)^{2 n-1}}{2 n-1}+\frac{4 \left(\frac{1}{3}\right)^{2 n-1}}{2 n-1}=\frac{1}{10^{10}}$$
Using Mathematica I got an approximated value of $n=16$. Indeed
$$4 \sum _{n=1}^{16} \frac{(-1)^{n+1} \left(\frac{1}{2}\right)^{2 n-1}}{2 n-1}+4 \sum _{n=1}^{16} \frac{(-1)^{n+1} \left(\frac{1}{3}\right)^{2 n-1}}{2 n-1}\approx 3.14159 265357$$
While $\pi\approx 3.14159265358$.
Error is $1.14\times10^{-11}<10^{-10}$

A: Making the problem more general, you want to find $n$ such that $$R_n=\frac{4 \left(\frac{1}{2}\right)^{2 n-1}}{2 n-1}+\frac{4 \left(\frac{1}{3}\right)^{2 n-1}}{2 n-1}\leq{10^{-k}}$$
$$\frac{8 \left(\frac{1}{3}\right)^{2 n-1}}{2 n-1} < R_n <\frac{8 \left(\frac{1}{2}\right)^{2 n-1}}{2 n-1}$$ So, let us try to find the solution for
$$\frac{8\, x^{2 n-1}}{2 n-1}\leq{10^{-k}}\implies2n-1 \geq 8 \,x^{2 n-1}\, 10^k$$ The only explicit solution is
$$n=\frac{1}{2} \left(1-\frac{W\left(-8\, 10^k \log (x)\right)}{\log (x)}\right)$$ where $W(.)$ is Lambert function.
For your case $(k=10)$ : with $x=\frac 12$, it gives, as a real, $n=16.1267$ and for $x=\frac 13$, it gives $n=10.5598$. In fact, using algebra, the exact value would be $15.6491$


text:
Q: asynchronous method executing I have a delegate method with the following tasks:

*

*get something from the internet (ex: some image from a web site);

*process that image in a certain way;

*display the result in a subview ;

getting the image takes some time, depending on the network's speed so the result of its processing is displayed in the subview after that little while.
my problem: during the time between getting the image and showing the result the device looks unresponsive. any attempt to put some spinner, or any other method which is called inside this main procedure has no effect until the result is processed. how should I change this behaviour? I would like to put a big spinner during that waiting time.
thank you.

A: See iphone-dev-tips for a very basic approach on asynchronous fetching of a UIImage.

A: I found the LazyTableImages to be very instructive on how to best implement this behavior.  In my opinion, the spinner is to be avoided at all costs.
We also make use of NSOperationQueue to handle background loading of upwards of 500 images without slowing the UI down much.
Cheers,
-dan


text:
Q: Finding out the value of $\angle DQC$ in a trapezium $ABQD$ where $\angle DCB$ = 30$^\circ$ In this below diagram, $\angle ABC=60^\circ, \angle DCB=30^\circ $, $AD$ is parallel to $BC$ and $AP$ is perpendicular to $BC$. Both the area and perimeter of $ABCD$ and $APQD$ are equal . What is the value of /angle $DQC$?

At first, I started with the condition of area of the both the trapezium (mentioned in the question) being equal. As $AD$ is parallel to $BC$, So we can show that,
$\frac{1}{2}(AD+BC)$ ×$AP$ = $\frac{1}{2}(AD+PQ)$ ×$AP$
$AD$+$BC$ = $AD$+$PQ$
$BC$ = $PQ$ ..................              (1)
And now, we can show their perimeter are equal with the below equation:
$AB+BC+CD+AD$ = $AP+PQ+DQ+AD$
$AB+BC+CD$ = $AP+PQ+DQ$
$AB+PQ+CD$ = $AP+PQ+DQ$............(from 1)
$CD+AB$ = $AP+DQ$.............(2)

I drew a vertical line $DE$ which is parallel to $AP$. $DE$ is equal to $AP$ as $AD$ and $BC$ are parallel to each other. Here /angle $APB$ and /angle $DEQ$ are respectively right-angle. So, we get two right-angled triangle $APB$ and $DEQ$.
By trigonometry and from the traingle $APB$, we can write that:-
$\frac{AB}{AP}$ = $\mathrm{cosec} 60^\circ$
$AB$ = $\frac{2AP}{\sqrt 3}$..........(3)
Similarly, from $DEC$, we can write that:-
$\frac{DC}{DE}$ = $\mathrm{cosec} 30^\circ$
$DC$ = 2$DE$
$CD$ = 2$DE$..........(4)
Let us denote the $\angle DQE = $$\theta$
So, now from the equation (2), we can get:-
$2AP$ + $\frac{2AP}{\sqrt 3}$ = $AP+ DQ$.........(from 3 and 4)
$\frac{2\sqrt 3AP + 2AP - \sqrt 3AP}{\sqrt 3} $ = $DQ$
$AP × \frac{2+ \sqrt 3}{\sqrt 3} $ = $DQ$
$\frac{2+ \sqrt 3}{\sqrt 3} $ = $\frac{DQ}{AP} $
$\frac{DQ}{DE} $ = $\frac{2+ \sqrt 3}{\sqrt 3} $......($AP = DE$  according to the diagram)
$\frac{DE}{DQ} $ = $\frac{\sqrt 3}{2 +\sqrt 3} $
$\sin \theta$ = $\frac{\sqrt 3}{2} + 1 $.................(5)
We know that if function of x is described as f(x) = $\sin^\text{-1} $x, than function of x will be real and valid if and only if its domain is [-1,1]. But there is a little bit problem in my calculation.
(5) is invalid because the real value of $\sin \theta$ is above 1 which is impossible in this case. For this reason, the value of $\theta$ is unreal. So, there is an extensive mistake either in my calculation or in the question. I have been unable to find my error. So, I need some help to identify the mistake to solve the problem properly.
EDIT: My fault is making equation (5) from the past.

A: The problem has no solution. Let's assume that there is one. Then we notice that increasing or decreasing the length of $AD$ will not change the fact that areas/ perimeters are the same. Indeed, if we increase the length by $x$, the perimeter of both trapezoids will increase by $2x$, and the areas will both increase by $x\cdot AE$. Then let's do $x=-|AD|$. Then in your picture $A=D$ and $P=E$. I will therefore drop any reference to $D$ and $E$ from now on.
$ABC$ is a right angle triangle, with the acute angles $30^\circ$ and $60^\circ$. Then $$AC=\frac{\sqrt 3}2 BC$$ and $$AB=\frac 12 BC$$
In the right angle triangle $ABC$ I can write the area in two ways to get $$BC\cdot AP=AB\cdot AC=BC^2\frac{\sqrt 3}{4}$$
Therefore $AP=BC \frac{\sqrt 3}{4}$. You already showed that $PQ=BC$. So in the right angle triangle $APQ$ you can write $$\tan\theta=\frac{AP}{PQ}=\frac{\sqrt 3}4$$
Now lets see that this does not verify equal perimeter requirement: $$AB+AC+BC=BC\left(\frac 12+\frac{\sqrt 3}2+1\right)$$
$$AP+PQ+QA=BC\left(\frac{\sqrt 3}{4}+1+\sqrt{1^2+\left(\frac{\sqrt 3}{4}\right)^2}\right)$$
You can see that there is something with $\sqrt{19}$ in the second equation, that it's not there in the first.
Note: you could get to the same conclusion even if you explicitly carry around $AD\ne 0$.

A:
\begin{align}
   \operatorname{perimeter}(APQD) &= \operatorname{perimeter}(ABCD) \\
   (3+\sqrt 3)x + 2y + CQ+DQ &= (6+2\sqrt 3)x + 2y \\
   CQ +DQ &= (3+\sqrt 3)x
\end{align}
\begin{align}
   \operatorname{area}(APQD) &= \operatorname{area}(ABCD) \\
   \frac 12(3x+2y+CQ)(\sqrt 3x) &= \frac 12(4x+2y)((\sqrt 3x)) \\
   CQ &= x \\
\hline
   DQ &= (2+\sqrt 3)x \\
   (DQ)^2 &= (7+4\sqrt 3)x^2
\end{align}
But, then, $(7+4\sqrt 3)x^2=(DQ)^2 = (\sqrt 3x)^2+(4x)^2=19x^2$
So, by contradiction, there is no solution.


text:
Q: Weird date-time format on x-axis plot I'm currently plotting several datasets of one day in R. The format of the dates in the datasets is yyyymmmdddhh. When I plot this, the formatting fails gloriously: on the x-axis, I now have 2016060125, 2016060150, etc. and a very weirdly shaped plot. What do I have to do to create a plot with a more "normal" date notation (e.g. June 1, 12:00 or just 12:00)??
Edit: the dates of these datasets are integers
The dataset looks like this:
> event_1
         date    P ETpot       Q    T     fXS GRM_SintJorisweg
1  2016060112  0.0 0.151 0.00652 19.6 0.00477          0.39250
2  2016060113  0.0 0.134 0.00673 20.8 0.00492          0.38175
3  2016060114  0.0 0.199 0.00709 22.6 0.00492          0.36375
4  2016060115  0.0 0.201 0.00765 21.2 0.00492          0.36850
5  2016060116 19.4 0.005 0.00786 19.5 0.00492          0.36900
6  2016060117  2.8 0.005 0.00824 18.1 0.00492          0.36625
7  2016060118  2.6 0.017 0.00984 18.0 0.00508          0.35975
8  2016060119  9.7 0.000 0.01333 16.7 0.00555          0.34750
9  2016060120  7.0 0.000 0.01564 16.8 0.00524          0.33550
10 2016060121  4.1 0.000 0.01859 17.1 0.00524          0.32000
11 2016060122  9.5 0.000 0.02239 17.2 0.00539          0.30250
12 2016060123  2.6 0.000 0.03330 17.5 0.00555          0.27050
13 2016060200 11.6 0.000 0.03997 17.4 0.00555          0.23800
14 2016060201  0.9 0.000 0.04928 17.3 0.00555          0.21725
15 2016060202  0.0 0.000 0.05822 17.2 0.00555          0.20350
16 2016060203  2.3 0.002 0.06547 16.4 0.00555          0.18575
17 2016060204  0.0 0.016 0.07047 16.5 0.00555          0.16950
18 2016060205  0.0 0.027 0.07506 16.7 0.00555          0.16475
19 2016060206  0.0 0.070 0.07762 18.0 0.00555          0.16525
20 2016060207  0.0 0.285 0.08006 19.5 0.00555          0.14500
21 2016060208  0.0 0.224 0.08109 20.3 0.00555          0.15875
22 2016060209  0.0 0.362 0.07850 21.3 0.00555          0.17825
23 2016060210  0.0 0.433 0.07441 22.0 0.00524          0.19175
24 2016060211  0.0 0.417 0.07380 23.9 0.00492          0.19050

I want to plot the date on the x-axis and the Q on the y-axis

A: Create a minimal verifiable example with your data:
date_int <- c(2016060112,2016060113,2016060114,2016060115,2016060116,2016060117,2016060118,2016060119,2016060120,2016060121,2016060122,2016060123,2016060200,2016060201,2016060202,2016060203,2016060204,2016060205,2016060206,2016060207,2016060208,2016060209,2016060210,2016060211)
Q <- c(0.00652,0.00673,0.00709,0.00765,0.00786,0.00824,0.00984,0.01333,0.01564,0.01859,0.02239,0.0333,0.03997,0.04928,0.05822,0.06547,0.07047,0.07506,0.07762,0.08006,0.08109,0.0785,0.07441,0.0738)
df <- data.frame( date_int, Q)

So, now we have a dataframe 'df'
With the dataframe 'df' you can convert your date_int column to a date format with hours and update the dataframe:
date_time <- strptime(df$date_int, format = '%Y%m%d%H', tz= "UTC")
df$date_int <- date_time

Finally,
plot(df)

You will see a nice plot! Like the following:

Ps.: Please note that you need to use abbreviations specified on "Date and Times in R" (e.g. "%Y%m%d%H" in this case)
Ref.: https://www.stat.berkeley.edu/~s133/dates.html

A: Here a lubridate answer:
library(lubridate)
event_1$date <- ymd_h(event_1$date)

or base R:
event_1$date <- as.POSIXct(event_1$date, format = "%Y%d%d%H")

A: What is happening is the dates are getting interpreted as numeric classes. As indicated, you need to convert. To get the formatting correct, you need to do a little more:
set.seed(123)
library(lubridate)
##     date
x <- ymd_h(2016060112)
y <- ymd_h(2016060223)

dfx <- data.frame(
  date = as.numeric(format(seq(x, y, 3600), "%Y%m%d%H")),
  yvar = rnorm(36))

dfx$date_x <- ymd_h(dfx$date)

# plot 1
plot(dfx$date, dfx$yvar)

Now using date_x which is POSIXct:
#plot 2
# converted to POSIXct
class(dfx$date_x)
## [1] "POSIXct" "POSIXt"
plot(dfx$date_x, dfx$yvar)

You will need to fix your date axis to get the format you desire:
#plot 3
# using axis.POSIXct to help things

with(dfx, plot(date_x, yvar, xaxt="n"))
r <- round(range(dfx$date_x), "hours")
     axis.POSIXct(1, at = seq(r[1], r[2], by = "hour"), format = "%b-%d %H:%M")


text:
Q: How to hide the url in my PWA in windows? I turned my site into a pwa, but the slash with the URL still appears, I made some changes to my manifest.json but so far I couldn't hide it, how to do it correctly?

This is my manifest.json
"lang": "pt",
"dir": "ltr",
"name": "GuiaCorretorPro",
"short_name": "GuiaCorretorPro",
"icons": [
{
  "src": "https://painel.guiacorretor.com/public/favicon.png",
  "type": "image/png",
  "sizes": "512x512",
  "purpose": "maskable"
},
{
  "src": "https://painel.guiacorretor.com/public/favicon.png",
  "type": "image/png",
  "sizes": "144x144",
  "purpose": "any"
}
],
  "theme_color": "#341864",
  "background_color": "#9b67f7",
  "start_url": "/auth/login",
  "display": "standalone",
  "orientation": "portrait",

A: You need to add a scope to your manifest.json file for it
"scope": "https://painel.guiacorretor.com/"

The scope member is a string that defines the navigation scope of this web application's application context. It restricts what web pages can be viewed while the manifest is applied. If the user navigates outside the scope, it reverts to a normal web page inside a browser tab or window

https://developer.mozilla.org/en-US/docs/Web/Manifest/scope


text:
Q: Selenium - How To Change "CommandTimeout" After WebDriver is Declared I'm declaring my Selenium WebDriver reference like this:
var driver = new FirefoxDriver(service,
    new FirefoxOptions {
        BrowserExecutableLocation = "XXXX",
        Profile = firefoxProfile,
        UseLegacyImplementation = true },
    new TimeSpan(0, 1, 30));

It works great 99% of the time, however there are certain cases where I want to change the default "commandTimeout" to something other than 90 seconds. How do I do this without redefining the driver?
I've explored all the methods/properties of the following class and it doesn't seem changing any of them has any effect:
driver.Manage().Timeouts()

There also this post, but it's not related to the "commandTimeout". There's this, which doesn't really cover AFTER the driver is created. Most posts about Selenium timeouts are concerned with Implicit Wait's or various other timeouts, not the timeout value specified in the driver's declaration.

A: Why would you need to set the commandTimeout afterward? It is actually only a backup for when a driver does not respond anymore. It doesn't have anything to do with driving browsers themselves.
Looking into the selenium source code, you can see the commandTimeout parameter is passed into the RemoteWebdriver.ICommandExecutor field, which is private. This means, after initialization, it is not possible to access or change the command timeout anymore.
A very hacky, and certainly not recommended 'solution' for this could be to use reflection to access the property. This however is certainly not recommended, since it heavily depends on the driver you are using, and can therefore break at any moment.
If you need high timeouts occasionally, it is often better to set the commandTimeout to a high value, and manage the timeout using ImplicitWait & co.


text:
Q: Перенос из одной таблицу в другую при обновлении у меня есть вот такая таблица в MS SQL
ITEM_ID INT IDENTITY (1,1) NOT NULL
CONSTRAINT PK_Item PRIMARY KEY,
Name          NVARCHAR(50)       NOT NULL,
Price         FLOAT              NOT NULL,
PriceToReturn FLOAT              NOT NULL,
Discription   NVARCHAR(120)      NOT NULL,
PS            NVARCHAR(120)      NOT NULL,
Returned      BIT                NOT NULL,

Мне нужно написать триггер который при обновлении поля "Returned" перенесёт обновлённую строку в другую, точно такую же таблицу, задача элементарная как мне кажется, но мне нужна помощь

A: Решение проблемы
CREATE OR ALTER TRIGGER Returned
ON Item
AFTER UPDATE
AS
    BEGIN
        IF UPDATE(Returned)
        BEGIN
        DECLARE @Name NVARCHAR(40)
        DECLARE @Price FLOAT
        DECLARE @PriceToReturn FLOAT
        DECLARE @Discription NVARCHAR(40)
        DECLARE @PS NVARCHAR(120)
        SET @Name = (SELECT Name FROM deleted)
        SET @Price = (SELECT Price FROM deleted)
        SET @PriceToReturn = (SELECT PriceToReturn FROM deleted)
        SET @Discription = (SELECT Discription FROM deleted)
        SET @PS = (SELECT PS FROM deleted)
        INSERT INTO ReturnedItems(Name, Price, PriceToReturn, Discription, PS) VALUES(@Name,@Price,@PriceToReturn,@Discription,@PS)
    END;
END;


text:
Q: Google Maps - all buttons are disabled on load I'm writing a Wordpress page for a client that displays some text and a Google Map based on data loaded from a database.
So far I've gotten most of it to work. The Google Maps however begins to load then mysteriously "blues" out displaying only what looks like ocean with all the other options (zoom in/out, street view, etc.) greyed out.

*

*There are no JavaScript errors available from FireBug etc.

*The divs containing the map (#container, and #map-canvas ) are set to real pixel values.

*The solution given here yields no positive results.

This is what the end result looks like:

Any ideas would be extremely welcome.
Edit:
Code snip per request:
echo '';
        echo '

'.$detail['name'].'

'.$detail['description'].'

'.$detail['address'].'

        ';

Un-minified version of the JS:
function initialize(lat,lng,name) {
lat = parseFloat(lat);
lng = parseFloat(lng);
var ourLocation = new google.maps.LatLng(lat,lng);
var marker;
var map;
    var mapOptions = {
        center: ourLocation,
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

    marker = new google.maps.Marker({
        map: map,
        draggable: false,
        animation: google.maps.Animation.DROP,
        position: ourLocation,
        title:name
    });
    google.maps.event.addDomListener(window,"load",initialize);
};

jQuery(function($){
    initialize(lat,lng,name);
    // the variables lat, lng, and name are replaced with php variables in the code
});

A: I figured it out. Took a little while, but...
Wordpress hates the jQuery call for some reason or another.
I noticed that in the JS console, if I called the initialize function with the variables I'd rip from the generated source then the map would magically work.
Instead of using jQuery, I just used the windows onload event.
window.onload = function() { initialize('.$detail['latitude'].','.$detail['longitude'].',"'.$detail['name'].'"); }

Which magically works.
Lesson learned, jQuery and Wordpress are like Strawberry Chocolate Milk and India Pale Ales: they don't mix well.
Thank you everyone that contributed.


text:
Q: Android - RecyclerView freeze after load I have a RecyclerView and I load item ten by ten from my database by detecting the end of the RecyclerView.
My problem : after loading items, when i scroll, the RecyclerView freeze during 1-2 sec.
I think the problem come from ImageView in each item.
After each load, the last list is added to adapter like this : arrayAdapter.list.addAll(questions); and then arrayAdapter.notifyDataSetChanged();
My adpater :
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    final Question question = list.get(position);
    holder.tvOwner.setText("Question posée par " + question.ownerUsername);
    holder.tvQuestion.setText(question.question);

    if (question.image != null) {
        holder.questionImage.setImageBitmap(question.image);
        holder.questionImage.setVisibility(View.VISIBLE);
        holder.questionImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavigationMenu nav = (NavigationMenu) context;
                nav.showPictureFullScreen(question.image);
            }
        });
    } else {
        holder.questionImage.setImageBitmap(null);
        holder.questionImage.setVisibility(View.GONE);
    }

A: Thanks to Pavan
public class SetImageBitmap extends AsyncTask<Void, Void, Bitmap> {
    Question q;
    ImageView iv;

    public SetImageBitmap(Question q, ImageView iv) {
        this.q = q;
        this.iv = iv;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {
        return q.image;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        iv.setImageBitmap(bitmap);
        iv.setVisibility(View.VISIBLE);
    }
}


text:
Q: Solution of $\frac{dx}{dt}=-\frac{(\sigma+1)x}{\sigma x+1}$ in terms of Lambert $w$ function Solution of $\frac{dx}{dt}=-\frac{(\sigma+1)x}{\sigma x+1}$ in terms of Lambert $w$ function.
Should I first take the solution of ODE and then apply Laplace transform. Please give step by step solution if possible

A: lets take $\sigma x = \phi$
then
$$
\dfrac{dx}{dt} = -\dfrac{(\sigma+1)x}{\sigma x + 1}
$$
transforms to
$$
\dfrac{d\phi}{dt} = -(\sigma+1)\dfrac{\phi}{\phi+1}
$$
re-arrange leads to
$$
\int 1+\dfrac{1}{\phi}d\phi = \phi + \ln \phi = \int -(\sigma+1) dt = -(\sigma+1)t + C
$$
thus
$$
\phi\mathrm{e}^{\phi} = C_1\mathrm{e}^{-(\sigma+1)t}
$$
when t = 0 we find
$$
C_1 = \phi(t=0)\mathrm{e}^{\phi(t=0)} = \sigma x(t=0) \mathrm{e}^{\sigma x(t=0)}
$$
thus
$$
\phi\mathrm{e}^{\phi} = \sigma x(t=0) \mathrm{e}^{\sigma x(t=0)} \mathrm{e}^{-(\sigma+1)t}
$$
thus
$$
\phi\mathrm{e}^{\phi} = \sigma x(t=0) \mathrm{e}^{\left(\sigma x(t=0) -(\sigma+1)t\right)}
$$
now using a standard result
$$
Y = X\mathrm{e}^X \implies X = W(Y)
$$
thus
$$
\phi\mathrm{e}^{\phi} = \sigma x(t=0) \mathrm{e}^{\left(\sigma x(t=0) -(\sigma+1)t\right)}
$$
leads to
$$
\phi = W\left[\sigma x(t=0) \mathrm{e}^{\left(\sigma x(t=0) -(\sigma+1)t\right)}\right]
$$
now transforming back to $x$
we find
$$
x(t) = \dfrac{W\left[\sigma x(t=0) \mathrm{e}^{\left(\sigma x(t=0) -(\sigma+1)t\right)}\right]}{\sigma}
$$
the finally piece of your puzzle is the condition that $x(t=0)=1$ to get the result that you show. If thats the case then
$$
x(t) = \dfrac{W\left[\sigma \mathrm{e}^{\left(\sigma -(\sigma+1)t\right)}\right]}{\sigma}
$$


text:
Q: How do I reuse golang http request in python request So I have a tls proxy that I am running in golang and I am sending the requests through python requests into the proxy. But I don't get the headers and cookies back in python requests. How can I reuse the headers and cookies that I get when using the tls proxy from golang into my python request? I can see that the new headers and cookies are being created in the golang tls proxy, but how can I transfer the new headers and cookies into python requests?
Golang code:
package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "net/url"
    "strings"

    http "github.com/useflyent/fhttp"

    "github.com/Carcraftz/CycleTLS/cycletls"
)

var client = cycletls.Init()

func main() {
    port := flag.String("port", "8082", "A port number (default 8082)")
    flag.Parse()
    addr := "127.0.0.1:" + string(*port)
    fmt.Println("Hosting a TLS API on http://" + addr)
    http.HandleFunc("/", handleReq)
    err := http.ListenAndServe(addr, nil)
    if err != nil {
        log.Fatalln("Error starting the HTTP server:", err)
    }

}

func handleReq(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    // Ensure page URL header is provided
    pageURL := r.Header.Get("Poptls-Url")
    if pageURL == "" {
        http.Error(w, "ERROR: No Page URL Provided", http.StatusBadRequest)
        return
    }
    // Remove header to ignore later
    r.Header.Del("Poptls-Url")

    // Ensure user agent header is provided
    userAgent := r.Header.Get("User-Agent")
    if userAgent == "" {
        http.Error(w, "ERROR: No User Agent Provided", http.StatusBadRequest)
        return
    }

    // Extract proxy from header
    proxy := r.Header.Get("Poptls-Proxy")
    if proxy != "" {
        r.Header.Del("Poptls-Proxy")
    }

    redirectVal := r.Header.Get("Poptls-Allowredirect")
    allowRedirect := true
    if redirectVal != "" {
        if redirectVal == "false" {
            fmt.Println(("redirects disabled"))
            allowRedirect = false
        }
    }
    if redirectVal != "" {
        r.Header.Del("Poptls-Allowredirect")
    }
    // Change JA3
    // Use Chrome JA3 by default
    //TODO: ADD MORE JA3 HASHES
    tlsClient := "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-21,29-23-24,0"
    if strings.Contains(strings.ToLower(userAgent), "firefox") {
        tlsClient = "771,4865-4867-4866-49195-49199-52393-52392-49196-49200-49162-49161-49171-49172-156-157-47-53-10,0-23-65281-10-11-35-16-5-51-43-13-45-28-21,29-23-24-25-256-257,0"
    }

    // Forward body
    body, _ := ioutil.ReadAll(r.Body)

    // Forward query params
    var addedQuery string
    for k, v := range r.URL.Query() {
        addedQuery += "&" + k + "=" + v[0]
    }

    endpoint := pageURL + "?" + addedQuery
    if strings.Contains(pageURL, "?") {
        endpoint = pageURL + addedQuery
    } else if addedQuery != "" {
        endpoint = pageURL + "?" + addedQuery[1:]
    }
    u, err := url.Parse(endpoint)
    if err != nil {
        panic(err)
    }
    // Forward headers
    headers := make(map[string]string)
    //fmt.Println(r.Cookies()) //Delete this
    //fmt.Println(r.Method)    //Delete this
    for k := range r.Header {
        if k != "Content-Length" {
            headers[k] = r.Header.Get(k)
        }
    }
    headers["Host"] = u.Host
    // Set options
    opts := cycletls.Options{
        Body:          string(body), // ideally, body should be passed as bytes
        Ja3:           tlsClient,
        UserAgent:     userAgent,
        Headers:       headers,
        Method:        r.Method,
        Proxy:         proxy,
        AllowRedirect: allowRedirect,
    }
    // Perform request
    res, err := client.Do(endpoint, opts, r.Method)
    if err != nil {
        log.Println("Request failed:", err)
    }
    fmt.Println(res.Response.Status)
    //fmt.Println(res.Response.Headers) //Delete this
    // Forward response headers
    for k, v := range res.Response.Headers {
        // Do not forward the content length and encoding headers, as we will handle the decoding ourselves
        if k != "Content-Length" && k != "Content-Encoding" {
            w.Header().Set(k, v)
        }

    }
    // Forward respone status
    w.WriteHeader(res.Response.Status)

    // Write forwarded proxy request
    if _, err := fmt.Fprint(w, res.Response.Body); err != nil {
        log.Println("Error writing body:", err)
    }

}

Python code:
import cloudscraper
from http.server import HTTPServer, BaseHTTPRequestHandler
from sys import argv

def main():
    req = cloudscraper.create_scraper()

    akamai_api_login = req.post(
        api,
        data={
            'usrnm':    'user',
            'pass':     'pass'
        }
    )

    abc = req.get(website_endpoint)
    print(f'cookie: {abc.cookies}')

    a_api = req.post(
        api_site,
        data={
            'hello': 'world'
        }
    )
    senreq = req.get(web)
    sendata = senreq.json()

    # Checking for valid
    # Using the TLS Proxy
    tls = req.post(
        'http://127.0.0.1:8082',
        headers={
            'poptls-url': website,
            'accept': '*/*',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'en-US,en;q=0.9',
            'sec-ch-ua': '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-fetch-dest': 'script',
            'sec-fetch-mode': 'no-cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.192 Safari/537.36'
        },
        json={
            'data': data
        },
        cookies= dict(abc.cookies)
    )

    print(tls.cookies)
    req.close()

main()


text:
Q: Do I really need Basic dispose pattern for type referencing other IDisposable objects? Microsoft design guidelines mention Dispose pattern and scenarios how to use it:

DO implement the Basic Dispose Pattern on types containing instances
  of disposable types. See the Basic Dispose Pattern section for details
  on the basic pattern.

Later, they show the Basic Dispose Pattern as follows:
public class DisposableResourceHolder : IDisposable {

    private SafeHandle resource; // handle to a resource

    public DisposableResourceHolder(){
        this.resource = ... // allocates the resource
    }

    public void Dispose(){
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing){
        if (disposing){
            if (resource!= null) resource.Dispose();
        }
    }
}

My questions are:

*

*Why do we need to implement Dispose(bool) if it has just a single call with parameter true? It could be easily simplified to just parameterless Dispose() {resource?.Dispose();}. Note we don't need finalizer here because objects we are referencing are managed and have their own finalizers, so they won't be leaked.

*Why do they recommend to call GC.SuppressFinalize(this) while not having finalizer? GC anyway wouldn't call finalizer because it does not exist!

*The only case when I see the need of Dispose(bool) is when we really have some unmanaged references, which does not implement IDisposable nor finalizer (like shown in this article). But then the meaning of bool disposing would be bool includingManagedResources. So why is it named so misleading 'disposing' to what it should do in fact?

A: *

*Other classes could inherit from your class. Considering that the deriving class also holds unmanaged resources (recommended or not), this class should then add the finalizer calling Dispose(false). If your class was sealed I would agree with you.

*Because the method void Dispose() should not be virtual following the guidelines from Microsoft and thus deriving classes would then have no chance to suppress finalization after disposal. Your implementation might not need a finalizer, but probably deriving classes do.

*It's called disposing for no specific reason in my opinion. I personally would rename it as well.
Anyway, from my point of view it is not a good approach to mix owning managed and unmanaged resources. As already mentioned in the comment even Microsoft recommends to encapsulate unmanaged resources into managed ones thus the cases where you need to implement finalizers are probably rare. I cannot remember when I did this myself the last time.
I am also not sticking to the implementation from the guidelines for multiple reasons, like misleading naming or because it's hard to understand. An alternative approach would be this answer.


text:
Q: Update nested map I have this map:
%{project: %{title: "Frank's Project"}}

I want to update the map to look like this:
%{project: %{title: "Frank's Project", subtitle: "another one"}}

How can I do this?
My previous attempt didn't work:
Map.put_new(params[:project], :subtitle, "another one")

returned this:
%{starterTopic: "garden", title: "Frank's Project"}

Which is not quite correct.

A: You can use Kernel.put_in/3:
iex(1)> map = %{project: %{title: "Frank's Project"}}
%{project: %{title: "Frank's Project"}}
iex(2)> map = put_in(map, [:project, :subtitle], "another one")
%{project: %{subtitle: "another one", title: "Frank's Project"}}

A: Elixir has a convenience macro in Kernel (automatically imported) called put_in/2 (or there's put_in/3, which is a function alternative and probably a little easier to understand what's going on).
iex> map = %{project: %{title: "Frank's Project"}}
%{project: %{title: "Frank's Project"}}
iex> put_in(map.project[:subtitle], "another_one")
%{project: %{subtitle: "another_one", title: "Frank's Project"}}


text:
Q: Rails Transform Json Request I am creating an API for serving up crossword puzzles. I am trying to stay pretty close to the JSON format proposed at XwordInfo. What I am having trouble with is transforming how I want it described in my models (client and server side) and how I want it in the database.
For example, take clues:
{
  ...

  "clues": {
              "across": [
                           "1. This is a clue",
                           "5. So is this"
              ],
              "down": [
                         "1. This is a down clue",
                         "2. Here we go again."
              ]
           }
  ...
}

Client-side puzzle model:
...
String title
Dictionary<String, Array> clues
String authore
...

Database:
create_table "clues", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "direction"
    t.integer  "crossword_id"
  end

  add_index "clues", ["crossword_id"], name: "index_clues_on_crossword_id", using: :btree

So I need to convert basically an array of clue name, direction objects (what's in the database) to a dictionary of clues which has 2 arrays, across and down. This seems like something that should be fairly common to have to do (transforming requests/responses) but I can't quite figure out how to search for it.
EDIT: I've already got the serialization part figured out with JBuilder: Here is how I display an array of clues:
crossword/index.json.jbuilder:
json.clues do
  json.across @crossword.clues.reject { |clue| clue.direction != 'across' }.collect { |clue| clue.name}
  json.down @crossword.clues.reject { |clue| clue.direction != 'down' }.collect { |clue| clue.name}
end

But coming from the user, how do I take that same dictionary > of clues and turn it into a list of Clue(name, direction,

A: This is a great use case for a serializer. I like https://github.com/rails-api/active_model_serializers
You can create a serializer for the Crossword model that in turn will return an array of its clues, each of which is serialized by its own Clue serializer.

A: I think you're just talking about iterating over the hash structure. Something like:
crossword = Crossword.find(id) # Or somesuch - not sure how you get the crossword

# Process across then down clues from the clues hash
["across", "down"].each do |direction|
  # Iterate over the clues in the array for the given direction
  clues[direction].each do |clue_text|
    # Create a clue on the crossword with the given text and direction
    crossword.clues.create!(name: clue_text, direction: direction)
  end
end

That will certainly populate your clues model from the json. Providing of course you have a has_many clues on your Crossword model (you seem to).

Aside 1: You might want to extend the model to include the number of the clue though because that implementation will not guarantee your clues are returned in order. This will obviously affect your serialization/deserialization though and you may end up with a hash for each clue. Or may it's enough to parse the clue text for the number.
Aside 2: You may also want to add a couple of direction class methods to your Clue class to make it easier to retrieve down and across clues:
def self.down
  where(direction: 'down')
end

def self.across
  where(direction: 'across')
end

In your jbuilder you can then do:
@crossword.clues.down.collect(&:name)


text:
Q: How to get original object from Vue 3 proxy? I want to get original object that was passed to reactive() from Vue 3 proxy. This is my code:
const token: any = reactive(new Token());
console.log(token.target);//prints undefined

Could anyone say how to do it?

A: reactive returns JavaScript Proxy which doesn't expose original object, unless a proxy is revokable.
Original object can be accessed through __v_raw property on reactive proxy, it's not a part of public API and shouldn't be relied on. Public API is toRaw:
const token = reactive(new Token());
const rawToken = toRaw(token);

If original object is needed then the reference shouldn't be discarded:
const rawToken = new Token();
const token = reactive(rawToken);


text:
Q: Converting a factor into a date in R Hey i'm new in using R so this question could be easy for many of you, but I'm really struggeling.
I have a column in my dataset called datum.
It's handled by R as an Factor
$ Datum        : Factor w/ 550 levels "1-10-2014","1-10-2015",..: 203 203 203 203 203 203 203 203 203 399 ...
When I try to convert this factor into a date, i get as result NA.
I tried several things like:
> prijzen$Datum <- as.Date(prijzen$Datum, format='%d/%m/%y')
> prijzen$Datum<- as.Date(as.character(prijzen$Datum), format="%d/%m/%y")
Even reading in the file with stringsAsFactors = FALSE didn't help.
How could i fix this?

A: Your format is wrong, you can use:
prijzen <- data.frame(Datum = c("1-10-2014","1-10-2015"), prijs = c(125, 150))
prijzen$Datum <- as.Date(prijzen$Datum, format='%d-%m-%Y')

This will format the Datum column as a Date and can be used in date calculations. The default format in R follows the rules of the ISO 8601 international standard which expresses a day as "2001-02-03"
But have a look at the way you are reading in the data. If, for example, you are using read.csv, try to specify the columns with the option colClasses.
Edit based on comments, formatted the output as well so the result in in dd-mm-yyyy format and not in standard iso format:
prijzen$Datum <- format(as.Date(prijzen$Datum, format='%d-%m-%Y'), '%d-%m-%Y')

This will transform the Datum column to a character column. This is more for printing the dates or exporting them.


text:
Q: How to initiate "npm start" via javascript file My project has a json file with following lines:
"scripts": {
    "start": "npm test",

Till now I ran it from vscode terminal -> npm start command.
Now, I added a js file to the project, with a button, and I want that npm start will run on button clicking.
I know how to add an event listener, but how can I link between npm start and the js file?


text:
Q: API for Wikipedia in Objective C? Does anybody know if there is an implementation of the wikipedia api in objective c?
which can be used to access and display the information a bit nicer then with the plain website.
I'm thinking of something like the wikipanion app but not so sophisticated.
Thanks
Joerg

A: I know the question is very old. But just for other ppl who are dealing with the same issue. I wrote a very small library which provides basic access to the Wikipedia API.
You can get it on github:
https://github.com/prine/WikiApiObjectiveC

A: You can use the MediaWiki API to download the markup text.
Also, why not look at http://en.m.wikipedia.org/ ?


text:
Q: Angular perform recursion to traverse hierarchy structure I have the following code in which the "currentNode" is the node which has been selected from the hierarchy level. It is a json having key-value pairs. It has keys like "children", "selected" etc.
I want to perform recursion so that whenever a node is selected (the selected function has the "currentNode" which is selected), check if it has children. If not, just pass the currentNode. If it has children, perform recursion to pass the nodes which have "Selected=true" attribute.
In my current code, I am able to get the selected child nodes only up to one level depth.
checkbox-tree.component.ts:
import { Component, EventEmitter, Output } from '@angular/core';
import { TreeNode } from './../../dto/TreeNode';
import { BaseTreeComponent } from './../base-tree/base-tree.component';
import { Subject } from 'rxjs/Subject';

import html from './checkbox-tree.component.html';
import css from '../fortune-select.component.css';

@Component({
  selector: 'checkbox-tree',
  template: html,
  styles: [css],
})

export class CheckboxTreeComponent<T> extends BaseTreeComponent<T> {

  //gets called when a node is selected
  public selected():void {

      if(this.currentNode.children.length !== 0) {
      this.currentNode.children.forEach(child => {if(child.selected = true) {
       this.sliceSelected.emit(child);

      //should ideally check again if child has children and if the child nodes are selected

      }})}
      else {
        this.sliceSelected.emit(this.currentNode);
      }

    if(!this.linked || (this.currentNode.indeterminate && !this.currentNode.selected)) {
      this.dataChangedEvent();
      return;
    }

    this.currentNode.indeterminate = false;
    if(this.singleLevelOnly) {
      this.currentNode.selectChildrenSingleLevel(this.currentNode.selected);
    } else {
      this.currentNode.selectChildren(this.currentNode.selected);
    }

    this.childChanged.emit();
    this.dataChangedEvent();
  }

}


text:
Q: Android AsyncTask threads limits? I am developing an application where I need to update some info every time user logs in to the system, I also use database in the phone. For all those operations (updates, retrieving data from db and etc.) I use async tasks. As up till now I didn't see why I shouldn't use them, but recently I experienced that if I do some operations some of my async tasks simply stop on pre-execute and don't jump to doInBackground. That was just too strange to leave it like that, so I developed another simple application just to check whats wrong. And strange enough, I get the same behavior when count of total async tasks reach 5, the 6th one stops on pre-execute.
Does android have a limit of asyncTasks on Activity/App? Or is it just some bug and it should be reported? Did anyone experience the same problem and maybe found a workaround to it?
Here is the code:
Simply create 5 of those threads to work in a background:
private class LongAsync extends AsyncTask<String, Void, String>
{
    @Override
    protected void onPreExecute()
    {
        Log.d("TestBug","onPreExecute");
        isRunning = true;
    }

    @Override
    protected String doInBackground(String... params)
    {
        Log.d("TestBug","doInBackground");
        while (isRunning)
        {

        }
        return null;
    }

    @Override
    protected void onPostExecute(String result)
    {
        Log.d("TestBug","onPostExecute");
    }
}

And then create this thread. It will enter preExecute and hang (it will not go to doInBackground).
private class TestBug extends AsyncTask<String, Void, String>
{
    @Override
    protected void onPreExecute()
    {
        Log.d("TestBug","onPreExecute");

        waiting = new ProgressDialog(TestActivity.this);
        waiting.setMessage("Loading data");
        waiting.setIndeterminate(true);
        waiting.setCancelable(true);
        waiting.show();
    }

    @Override
    protected String doInBackground(String... params)
    {
        Log.d("TestBug","doInBackground");
        return null;
    }

    @Override
    protected void onPostExecute(String result)
    {
        waiting.cancel();
        Log.d("TestBug","onPostExecute");
    }
}

A: Update: Since API 19 the core thread pool size was changed to reflect the number of CPUs on the device, with a minimum of 2 and maximum of 4 at start, while growing to a max of CPU*2 +1  - Reference
// We want at least 2 threads and at most 4 threads in the core pool,
// preferring to have 1 less than the CPU count to avoid saturating
// the CPU with background work
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;

Also note that while the default executor of AsyncTask is serial (executes one task at a time and in the order in which they arrive), with the method
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
        Params... params)

you can provide an Executor to run your tasks. You may provide the THREAD_POOL_EXECUTOR the under the hood executor but with no serialization of tasks, or you can even create your own Executor and provide it here.
However, carefully note the warning in the Javadocs.

Warning: Allowing multiple tasks to run in parallel from a thread pool is generally not what one wants, because the order of their operation is not defined. For example, if these tasks are used to modify any state in common (such as writing a file due to a button click), there are no guarantees on the order of the modifications. Without careful work it is possible in rare cases for the newer version of the data to be over-written by an older one, leading to obscure data loss and stability issues. Such changes are best executed in serial; to guarantee such work is serialized regardless of platform version you can use this function with SERIAL_EXECUTOR.

One more thing to note is that both the framework provided Executors THREAD_POOL_EXECUTOR and its serial version SERIAL_EXECUTOR (which is default for AsyncTask) are static (class level constructs) and hence shared across all instances of AsyncTask(s) across your app process.

A: All AsyncTasks are controlled internally by a shared (static) ThreadPoolExecutor and a LinkedBlockingQueue. When you call execute on an AsyncTask, the ThreadPoolExecutor will execute it when it is ready some time in the future.
The 'when am I ready?' behavior of a ThreadPoolExecutor is controlled by two parameters, the core pool size and the maximum pool size. If there are less than core pool size threads currently active and a new job comes in, the executor will create a new thread and execute it immediately. If there are at least core pool size threads running, it will try to queue the job and wait until there is an idle thread available (i.e. until another job is completed). If it is not possible to queue the job (the queue can have a max capacity), it will create a new thread (up-to maximum pool size threads) for the jobs to run in. Non-core idle threads can eventually be decommissioned according to a keep-alive timeout parameter.
Before Android 1.6, the core pool size was 1 and the maximum pool size was 10. Since Android 1.6, the core pool size is 5, and the maximum pool size is 128. The size of the queue is 10 in both cases. The keep-alive timeout was 10 seconds before 2.3, and 1 second since then.
With all of this in mind, it now becomes clear why the AsyncTask will only appear to execute 5/6 of your tasks. The 6th task is being queued up until one of the other tasks complete. This is a very good reason why you should not use AsyncTasks for long-running operations - it will prevent other AsyncTasks from ever running.
For completeness, if you repeated your exercise with more than 6 tasks (e.g. 30), you will see that more than 6 will enter doInBackground as the queue will become full and the executor is pushed to create more worker threads. If you kept with the long-running task, you should see that 20/30 become active, with 10 still in the queue.

A: @antonyt has the right answer but in case you are seeking for a simple solution then you may check out Needle.
With it you can define a custom thread pool size and, unlike AsyncTask, it works on all Android versions the same. With it you can say things like:
Needle.onBackgroundThread().withThreadPoolSize(3).execute(new UiRelatedTask<Integer>() {
   @Override
   protected Integer doWork() {
       int result = 1+2;
       return result;
   }

   @Override
   protected void thenDoUiRelatedWork(Integer result) {
       mSomeTextView.setText("result: " + result);
   }
});

or things like
Needle.onMainThread().execute(new Runnable() {
   @Override
   public void run() {
       // e.g. change one of the views
   }
});

It can do even lot more. Check it out on GitHub.


text:
Q: How to upload a jacoco report dumped by the jvm to SonarQube? During my build pipeline, the integration tests invoke application endpoints, via network transport. After this step the application's JVM dumps a jacoco report into a local file. How can I upload this report file to SonarQube?

A: The code coverage (similar to the measures) is always linked to an analysis.
So I suggest these steps:

*

*generate your jacoco report file as usual

*upload the file to the machine, where you Sonar analysis is done

*run an analysis, by setting the sonar.jacoco.reportPaths property to the location of the uploaded file


text:
Q: Why is the 'change-of-basis matrix' called such?
"Let $P$ be the change-of-basis matrix
  from a basis $S$ to a basis $S'$ in a
  vector space $V$. Then, for any vector
  $v \in V$, we have $$P[v]_{S'}=[v]_{S}
 \text{ and hence, }  P^{-1}[v]_{S} =
 [v]_{S'}$$
Namely, if we multiply the coordinates
  of $v$ in the original basis $S$ by
  $P^{-1}$, we get the coordinates of
  $v$ in the new basis $S'$." - Schaum's
  Outlines: Linear Algebra. 4th Ed.

I am having a lot of difficulty keeping these matrices straight. Could someone please help me understand the reasoning behind (what appears to me as) the counter-intuitive naming of $P$ as the change of basis matrix from $S$ to $S'$? It seems like $P^{-1}$ is the matrix which actually changes a coordinate vector in terms of the 'old' basis $S$ to a coordinate vector in terms of the 'new' basis $S'$...
Added:

"Consider a basis $S =
 \{u_1,u_2,...,u_n\}$ of a vector space
  $V$ over a field $K$. For any vector
  $v\in V$, suppose $v = a_1u_1
 +a_2u_2+...+a_nu_n$
Then the coordinate vector of $v$
  relative to the basis $S$, which we
  assume to be a column vector (unless
  otherwise stated or implied), is
  denoted and defined by $[v]_S =
 [a_1,a_2,...,a_n]^{T}$. "
"Let $S = \{ u_1,u_2,...,u_n\}$ be a
  basis of a vector space $V$, and let
  $S'=\{v_1,v_2,...,v_n\}$ be another
  basis. (For reference, we will call
  $S$ the 'old' basis and $S'$ the 'new'
  basis.) Because $S$ is a basis, each
  vector in the 'new' basis $S'$ can be
  written uniquely as a linear
  combination of the vectors in S; say,
$\begin{array}{c} v_1 = a_{11}u_1 +
 a_{12}u_2 + \cdots +a_{1n}u_n \\ v_2 =
 a_{21}u_1 + a_{22}u_2 + \cdots
 +a_{2n}u_n \\ \cdots \cdots \cdots \\ v_n = a_{n1}u_1 + a_{n2}u_2 + \cdots
 +a_{nn}u_n \end{array}$
Let $P$ be the transpose of the above
  matrix of coefficients; that is, let
  $P = [p_{ij}]$, where $p_{ij} =
 a_{ij}$. Then $P$ is called the
  \textit{change-of-basis matrix} from
  the 'old' basis $S$ to the 'new' basis
  $S'$." - Schaum's Outline: Linear Algebra 4th Ed.

I am trying to understand the above definitions with this example:
Basis vectors of $\mathbb{R}^{2}: S= \{u_1,u_2\}=\{(1,-2),(3,-4)\}$ and $S' = \{v_1,v_2\}= \{(1,3), (3,8)\}$ the change of basis matrix from $S$ to $S'$ is $P = \left( \begin{array}{cc} -\frac{13}{2} & -18 \\ \frac{5}{2} & 7 \end{array} \right)$.
My current understanding is the following: normally vectors such as $u_1, u_2$ are written under the assumption of the usual basis that is $u_1 = (1,-2) = e_1 - 2e_2 = [u_1]_E$. So actually $[u_1]_S = (1,0)$ and I guess this would be true in general... But I am not really understanding what effect if any $P$ is supposed to have on the basis vectors themselves (I think I understand the effect on the coordinates relative to a basis). I guess I could calculate a matrix $P'$ which has the effect  $P'u_1, P'u_2,...,P'u_n = v_1, v_2,..., v_n$ but would this be anything?

A: Everybody studying the change of basis affair should work out some simple examples like the following. Consider this basis in $\mathbb{R}^2$:
$$
v_1 = (1,1) \qquad \text{and} \qquad v_2 = (1,-1) \ .
$$
Or, since we are going to stress the bases and coordinates thing, we could write it this way
$$
v_1 = (1,1)_e \qquad \text{and} \qquad v_2 = (1,-1)_e \ ,
$$
since these are coordinates in the standard basis
$$
e_1 = (1,0) \qquad \text{and} \qquad e_2 = (0,1) \ .
$$
The change of basis matrix from $v$ to $e$ is
$$
P =
\begin{pmatrix}
1 & 1 \\\
1 & -1
\end{pmatrix} \ .
$$
Now, take the vector
$$
u = 2v_1 - 3v_2 \ .
$$
Its coordinates in the $v$ basis are:
$$
u = (2,-3)_v \ .
$$
If you want to obtain its coordinates in the $e$ (standard) basis, you can do it by hand:
$$
u = 2v_1 - 3v_2 = 2(1,1)_e -3(1,-1)_e = (2-3, 2+3)_e = (-1, 5)_e \ .
$$
Now, you realise that these are exactly the same operations that you do when performing this matrix multiplication:
$$
P
\begin{pmatrix}
2 \\\
-3
\end{pmatrix}
=
\begin{pmatrix}
1 & 1   \\\
1 & -1
\end{pmatrix}
\begin{pmatrix}
2 \\\
-3
\end{pmatrix}
=
\begin{pmatrix}
2 - 3 \\\
2 + 3
\end{pmatrix}
=
\begin{pmatrix}
-1 \\\
5
\end{pmatrix}  \ .
$$
Exercise. Maybe now you could redo yourself the proof of the change of basis theorem: take two arbitrary bases $v$ and $e$ in no matter which vector space, related by
$$
v_i = a^1_i e_1 + \cdots + a^n_i e_n \ , \qquad i = 1, \dots , n \ .
$$
Write down the change of basis matrix from $v$ to $e$ (that is, put the coordinates of the $v$ vectors as columns, like in the previous example):
$$
P =
\begin{pmatrix}
a^1_1    & \dots      & a^1_n     \\\
\vdots   & \ddots     & \vdots    \\\
a^n_1    & \dots      & a^n_n
\end{pmatrix}   \ ,
$$
take any vector
$$
u = b^1v_1 + \cdots + b^nv_n \ ,
$$
and write down its coordinates in the $v$ basis. Finally, find out its coordinates in the $e$ basis (by hand and with the help of the matrix $P$).

A: One major reason is practical. The matrix that converts vectors in the new coordinates into the old coordinates is easy to come by: you just put your new basis vectors as columns of the matrix.
Then to find the matrix going the other way around, you have to compute the inverse of this matrix.
Thus, it makes sense to call the first one $P$, and the second one $P^{-1}$.

A: The situation here is closely related to the following situation: say you have some real function $f(x)$ and you want to shift its graph to the right by a positive constant $a$. Then the correct thing to do to the function is to shift $x$ over to the left; that is, the new function is $f(x - a)$. In essence you have shifted the graph to the right by shifting the coordinate axes to the left.
In this situation, if you have a vector $v$ expressed in some basis $e_1, ... e_n$, and you want to express it in a new basis $Pe_1, .... Pe_n$ (this is why $P$ is called the change of basis matrix), then you multiply the numerical vector $v$ by $P^{-1}$ in order to do this. You should carefully work through some numerical examples to convince yourself that this is correct. Consider, for example, the simple case that $P$ is multiplication by a scalar.
The lesson here is that one must carefully distinguish between vectors and the components used to express a vector in a particular basis. Vectors transform covariantly, but their components transform contravariantly.

A: My belief is that this is merely convention. It is indeed natural to call matrix $P$ in ${P[v]}_{s'}=[v]_s$ the change-of-basis matrix from a basis $S'$ to a basis $S$, rather than the other way around. And in fact some books do use the opposite convention, especially when this thing is called a "change-of-coordinates matrix". In the book Linear Algebra and Its Applications (Fourth Edition) by David C. Lay, there is the following:

Theorem 15:
Let $\mathcal{B}=\{ \bf{b}_1,...,\bf{b}_n \}$ and $\mathcal{C}=\{ \bf{c}_1,...,\bf{c}_n \}$ be bases of a vector space $V$. Then there is a unique $n\times n$ matrix $\underset{\mathcal{C}\leftarrow \mathcal{B}}{P}$ such that
  $$[\bf{x}]_\mathcal{C} = \underset{\mathcal{C}\leftarrow \mathcal{B}}{\textit{P}}[\bf{x}]_{\mathcal{B}}$$
  .....
The matrix $\underset{\mathcal{C}\leftarrow \mathcal{B}}{P}$ in Theorem 15 is called the change-of-coordinates matrix from $\mathcal{B}$ to $\mathcal{C}$.

This is exactly the opposite of Schaum's Outlines says but this opposite convention is also used. Of course, here the name of the matrix is "change-of-coordinates" matrix rather than "change-of-basis" matrix, but they are talking about the same thing.


text:
Q: Saving multiple values to session array and reading them I have a problem with saving multiple values (product_id's) to session array without refreshing the page and reading them later on.
This is how I try to save them. My page loads jquery and has session_start(); in the head-section.
...

 while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC))

{

echo "Add to list ";

echo "";

}

This is my list.php:
<?php
session_start();

if (!isset($_SESSION['list'])) {
  $_SESSION['list'] = array();
}

$_SESSION['list'] = $_POST['varname'];

?>

And this is how I try to print the session:
<?php
session_start();

 print_r($_SESSION['list']);

?>

I really don't know what I'm doing wrong so any help would be appreciated. :)


text:
Q: Give the hyperlinks in the revision history a little breathing room, they're suffocating! With the addition of the "link" uhh link to the row of hyperlinks in the revision history, it has pointed my eyes to the lack of space they are given in that row. It's almost the same as the links seen below every post, except those ones have additional padding around them which is also clickable, whereas these links are just links. Can they be formatted similar to the post options to make them easier to click on and not look so pushed together, especially compared to the big Markdown view buttons below?

A: The revision menus are now given the same CSS treatment as the post menus, so the spacing, colors, etc. should match now.


text:
Q: base64_encode() limitation in php I am using the base64_encode for sending the numeric id to url, base64_encode($list_post['id']); up to 99 its working fine, but after 99 its produce wrong encoded string.
the last character in encoded string is = (equal sign), but when the number more than 99, for example 100 it don't show = (equal sign) at the end.

A: Take a look at how padding in base64 works: http://en.wikipedia.org/wiki/Base64#Padding
The padding (the "=" character) is not always needed and in some implementations is not even mandatory.
EDIT: ok from your comments I see that you are using the base64 encoded string in a URL like this:
http://example.com/path/OTC=

The base64 encoding includes chars that have a special meaning in URLs so you need to use a slightly modified function (https://stackoverflow.com/a/5835352/2737514):
function base64_url_encode($input) {
    return strtr(base64_encode($input), '+/=', '-_,');
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_,', '+/='));
}

However, since your code works for some numbers, maybe there is a problem with the .htaccess not parsing the url correctly, or the PHP code that interpretes the URL. I can't help more than this without seeing some other code.

A: it seems working fine for me
Can you please test with following code
echo base64_encode(101);
echo base64_decode(base64_encode(101));

DEMO

Base64-encoded data takes about 33% more space than the original data.

So these numbers shouldnt be a problem


text:
Q: Switch/Case statement cannot populate cell based on numeric value I am using the following case statement with KnockoutJS.

Status can be either 1 or 0, but no matter what I change the comparison to be my cells are either all up arrows or all down arrows. What am I missing here? Is there an easier way to say:

*

*If Status == 1 display an up arrow

*Else display a down arrow

EDIT:

This caused it to work, though I'm not sure why when I would say text: Status it would display the 1 or 0.

A: Try this:


text:
Q: SDRAM issue - LPC1788 I have been using an NXP LPC1788 dev board which I have developed my application on (.NET Microframework Cortex-M3 Port).
  Everything was well and good on this board, I had no issues with RAM or otherwise, and so I was ready to begin development of my production board.
I created a new board with the same RAM and processor, and I took the binary from the dev board and put it on the new board and I am getting problems when running from SDRAM. Not the usual where there is no connection, nor is there an intermittant fault... I can run a memory test (write to the entire SDRAM block in 32bits, 16bits, 8bits and read back the correct data multiple times).
However when I try to run my application I get really odd problems with RAM either getting overwritten, or not written at all. This is only when running the application which is perfect on the dev board. It is not intermittant, it does the same thing every time. Because of this I assume it is not my routing that is causing me issues (because my memory check passes).
Is there some odd feature of the LPC1788 EMC (ARM PrimeCell™ MultiPort Memory Controller) that I am not aware of that could be causing buffering issues or read-ahead problems? If anyone with experience with this could point me in the right direction, or help me write a better memory test to test for these odd conditions would be very helpful...
I have attached a picture of the routing, which although is not optimal (I have only 4 layers, 2 signal, 2 power plane) does allow the RAM to function and I can read from the device.

A: Smells like a data-dependent problem.  You may have some unfortunate coupling between some of the data and/or address lines such that the right pattern causes a failure somewhere.
Try slowing down the clock.  How the symptom changes or not may give some clues.  If there is crosstalk between some of the address and data lines, this should make the problem go away because transfers are done after everything eventually settles.  If the problem is noise getting onto the clock line, then this probably won't change anything.
Look at some of the signals with a scope and see how clean they look.  Did you put resistors in series with the lines to match the trace impedance better and reduce ringing?  Make sure to check the clock line too, not just a few data lines.  Also verify you really have the setup and hold times the chip needs.
Remember that apparent proper operation is not proof of correct operation, only of being lucky.

A: Long, parallel traces.  No signal termination.  No decoupling caps on the RAM.  Signal traces going from top to bottom layer without a cap near by.  Traces with long, unterminated, stubs.  Some signals going through 5 vias.  And possibly not enough vias on the power/gnd pins of the BGA (but it's hard to tell from your picture).
Any of these could cause memory problems, and some at any speed.  Carefully probe your clocks at the destination with a high speed o-scope (350 MHz or greater) and show us what you see.  Odds are that you have a problem with signal integrity.

A: What memory tests are you running?  In addition to the classics fill it with 0's and F's and A's and 5's and walking ones and all that, and the address to do an address bit test.  My favorite is a pseudo random test.  take an lfsr (very easy to code, deterministic and repeatable and is "random enough"), seed it, fill memory with random numbers (dont skip any or stop short, beginning to end one pass one seed at the start, insure/choose the lfsr does not repeat within the space you are using it), seed it and read back.  seed it, fill memory with the inverted values from the randomizer, seed it check.  Change the seed and repeat.  I tend to let a test like this run for a while.  It very quickly finds address bit problems and data line problems and many of the normal problems faster than the traditional tests.
What happens if you slow the clock(s) down and run slower, does it change?
If it is not hardware then focus on software, what is different between the dev board and your board?  break the application down into pieces and see if any of it runs or if it fails no matter how much you trim it down.


text:
Q: Make a tick togglebutton android
Is it possible to have a tick togglebutton ?

The layout is below

 <ImageView
            android:id="@+id/donePic"
            android:src="@mipmap/done"
            android:tint="@color/red"
            android:paddingLeft="320dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

Currently the tick button is ImageView. How to make the ImageView become toggleButton ? Is it possible ?

A: Make a Tic  toggle button with selector
<ToggleButton
                android:id="@+id/toggle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/check"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:textOff=""
                android:textOn="" />

Selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use tic -->
    <item android:drawable="@drawable/tic_img"
          android:state_checked="true" />
    <!-- When not selected, use un tic-->
    <item android:drawable="@drawable/untic_img"
        android:state_checked="false"/>

 </selector>

A: Set up onClickListenr for your imageView and when the user click the image, change the drawable to done or to undone.
You can keep a boolean value to see whether the user has clicked boolean ifClick = false or not!

A: You can use two images,one for toggle off and another for toggle on and set onClickListner on imageView.
boolean isToggle=false;

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

                if(!isToggle)
                {
                    //Do whatever you want to do

                    imageView.setImageResource(R.drawable.toggleOffImage);//set Toggle Off image
                    isToggle =true;
                }
                else
                {
                    //Do whatever you want to do
                    imageView.setImageResource(R.drawable.toggleOnImage); //set Toggle Off image
                    isToggle =false;
                }
            }
        });


text:
Q: How can I speed up this view transition, the first time through, on 3G phones? The following function is a method of a class called TitleOverlay - which is a transparent overlay with a textView.
The function shows the overlay by animating its alpha, and in parallel uses the animationWillStart property of the animation to show the keyboard.
On 3G phones, the first time this function is called, there is some lag before the keyboard shows. In fact, I think the animation to show the overlay and show the keyboard are being serialized. I tried setting the length of the overlay alpha animation to various lengths, and the keyboad always shows after the animation completes.
Basically, the first time, there is lag. On all subsequent times, the keyboard and the overlay animations occur in parallel, and it looks nice.
WHat can I do to fix this?
- (void) showOverlay {

  [[self superview] bringSubviewToFront:self];

  NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  [nc addObserver:self
         selector:@selector(keyboardWillShow:)
            name:UIKeyboardWillShowNotification
          object:nil];
  [nc addObserver:self
         selector:@selector(keyboardWillHide:)
             name:UIKeyboardWillHideNotification
           object:nil];

  [UIView beginAnimations:nil context: nil];
  [UIView setAnimationDuration: .5];
  [UIView setAnimationDelegate:titleField];
  [UIView setAnimationWillStartSelector:@selector(becomeFirstResponder)];
  self.whiteBlock.alpha = 1;
  [UIView commitAnimations];

}

A: The lag when displaying a keyboard for the first time in an iPhone application is a known issue.  There is a hack to work around this, as pointed out in that question.