text:
Q: Which is more efficient: Return a value vs. Pass by reference? I am currently studying how to write efficient C++ code, and on the matter of function calls, a question comes to mind. Comparing this pseudocode function:
not-void function-name () {
    do-something
    return value;
}
int main () {
    ...
    arg = function-name();
    ...
}

with this otherwise-identical pseudocode function:
void function-name (not-void& arg) {
    do-something
    arg = value;
}
int main () {
    ...
    function-name(arg);
    ...
}

Which version is more efficient, and in what respect (time, memory etc.)? If it depends, then when would the first be more efficient and when would the more efficient be the second?
Edit: For context, this question is limited to hardware platform-independent differences, and for the most part software too. Are there any machine-independent performance difference?
Edit: I don't see how this is a duplicate. The other question is comparing passing by reference (prev. code) to passing by value (below):
not-void function-name (not-void arg)

Which is not the same thing as my question. My focus is not on which is the better way to pass in an argument to a function. My focus is on which is the better way to pass out a result to a variable from the outside scope.

A: Some of the answers have touched on this, but I would like to emphasize in light of the edit

For context, this question is limited to hardware platform-independent differences, and for the most part software too. Are there any machine-independent performance difference?

If this is the limits of the question, the answer is that there is no answer. The c++ spec does not stipulate how either the return of an object or a passing by reference is implemented performance wise, only the semantics of what they both do in terms of code.
A compiler is therefore free to optimize one to identical code as the other assuming this does not create a perceptible difference to the programmer.
In light of this, I think it is best to use whichever is the most intuitive for the situation. If the function is indeed "returning" an object as the result of some task or query, return it, while if the function is performing an operation on some object owned by the outside code, pass by reference.
You cannot generalize performance on this. As a start, do whatever is intuitive and see how well your target system and compiler optimizes it. If after profiling you will discover a problem, change it if you need to.

A: We can't be 100% general because different platforms have different ABIs but I think we can make some fairly general statements that will apply on most implementations with the caveat that these things mostly apply to functions that are not inlined.
Firstly lets consider primitive types. At a low level a parameter pass by reference is implemented using a pointer whereas primitive return values are typically passed literally in registers. So return values are likely to perform better. On some architectures the same applies to small structures. Copying a value small enough to fit in a register or two is very cheap.
Now lets consider larger but still simple (no default constructors, copy constructors etc) return values. Typically larger return values are handled by passing the function a pointer to the location where the return value should be put. Copy elision allows the variable returned from the function, the temporary used for return and the variable in the caller that the result is placed into to be merged into one. So the basics of passing would be much the same for pass by reference and return value.
Overall for primitive types I would expect return values to be marginally better and for larger but still simple types I would expect them to be the same or better unless your compiler is very bad at copy elision.
For types that use default constructors, copy constructors etc things get more complex. If the function is called multiple times then return values will force the object to be re-constructed each time whereas reference parameters may allow the data structure to be reused without being reconstructed. On the other hand reference parameters will force a (possibly unnecessary) construction before the function is called.

A: First of all, take in account that returning an object will always be more readable (and very similar in performance) than having it passed by reference, so could be more interesting for your project to return the object and increase readability without having important performance differences.
If you want to know how to have the lowest cost, the thing is what do you need to return:

*

*If you need to return a simple or basic object, the performance would be similar in both cases.

*If the object is so large and complex, returning it would need a copy, and it could be slower than having it as a referenced parameter, but it would spend less memory I think.
You have to think anyway that compilers do a lot of optimizations which make both performances very similar. See Copy Elision.

A: This pseudocode function:
not-void function-name () {
    do-something
    return value;
}

would be better used when the returned value does not require any further modifications onto it. The parameter passed is only modified in the function-name. There are no more references required to it.

otherwise-identical pseudocode function:
void function-name (not-void& arg) {
    do-something
    arg = value;
}

would be useful if we have another method moderating the value of the same variable like and we need to keep the changes made to the variable by either of the call.
void another-function-name (not-void& arg) {
    do-something
    arg = value;
}

A: Returning the object should be used in most cases because of an optimsation called copy elision.
However, depending on how your function is intended to be used, it may be better to pass the object by reference.
Look at std::getline for instance, which takes a std::string by reference. This function is intended to be used as a loop condition and keeps filling a std::string until EOF is reached. Using the same std::string allows the storage space of the std::string to be reused in every loop iteration, drastically reducing the number of memory allocations that need to be performed.

A: Well, one must understand that compilation is not an easy buisness. there are many consideration taken when the compiler compiles your code.
One can't simply answer this question because the C++ standard doesn't provide standard ABI (abstract binary interface), so each compiler is allowed to compile the code whatever it likes and you can get different results in each compilation.
For example, on some projects C++ is compiled to managed extension of Microsoft CLR (C++/CX). since everything there is already a reference to an object on the heap, I guess there is not difference.
The answer is not simpler for un-managed compilations. several quaestion come to mind when I think about "Will XXX run faster then YYY?", for example:

*

*Is you object deafult-constructible?

*Does your compiler support return-value-optimization?

*Does your object support Copy-only semantics or both copy and move?

*Is the object packed in contigious manner (e.g. std::array) or it has pointer to something on the heap? (e.g. std::vector)?

If I give concrete example, my guess is that on MSVC++ and GCC, returning std::vector by value will be the as passing it by reference, because of r-value-optimization, and will be a bit (by few nanoseconds) faster then returning the vector by move. this may be completly different on Clang, for example.
eventually, profiling is the only true answer here.

A: Performance-wise, copies are generally more expensive, although the difference might be negligible for small objects. Also, your compiler might optimize a return copy into a move, making equivalent to passing a reference.
I'd recommend not passing non-const references unless you have a good reason to. Use the return value (e.g. functions of the tryGet() sort).
If you want you can measure yourself the difference, as others have said already. Run the test code a few million times for both versions and see the difference.


text:
Q: Переобразование из byte в double double val = System::Convert::ToDouble(sim[5]);

sim[5]= 0xA7;  после конвертации дает значение -89
где ошибка, что я не учел?

A: 0xA7 это 167 для беззнакового байта или -89 для знакового

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add a subplot to a plot with control widgets I would like to extend solution of the question "How to keep some text relative to the line into the plot when the plot changes" with two subplots controlled with a pair of widget sliders.
The code I have tried it makes no errors, but it does not show the Figure nor the controls.
from ipywidgets import widgets
from IPython.display import display
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

fig1, ax1 = plt.subplots(211)
line1, = ax1.semilogx([],[], label='Multipath')
hline1 = ax1.axhline(y = 0, linewidth=1.2, color='black',ls='--')
text1 = ax1.text(0, 0, "T Threshold",
                verticalalignment='top', horizontalalignment='left',
                transform=ax1.get_yaxis_transform(),
                color='brown', fontsize=10)
ax1.set_xlabel('Separation Distance, r (m)')
ax1.set_ylabel('Received Power, $P_t$ (dBm)')
ax1.grid(True,which="both",ls=":")
ax1.legend()

fig2, ax2 = plt.subplots(212)
line2, = ax2.semilogx([],[], label='Monostatic Link')
hline2 = ax2.axhline(y = 0, linewidth=1.2, color='black',ls='--')
text2 = ax2.text(0, 0, "R Threshold",
                verticalalignment='top', horizontalalignment='left',
                transform=ax2.get_yaxis_transform(),
                color='brown', fontsize=10)
ax2.set_xlabel('Separation Distance, r (m)')
ax2.set_ylabel('Received Power, $P_t$ (dBm)')
ax2.grid(True,which="both",ls=":")
ax2.legend()

def update_plot(h1, h2):
    D = np.arange(0.5, 12.0, 0.0100)
    r = np.sqrt((h1-h2)**2 + D**2)
    freq = 865.7 #freq = 915 MHz
    lmb = 300/freq
    H = D**2/(D**2+2*h1*h2)
    theta = 4*np.pi*h1*h2/(lmb*D)
    q_e = H**2*(np.sin(theta))**2 + (1 - H*np.cos(theta))**2
    q_e_rcn1 = 1
    P_x_G = 4 # 4 Watt EIRP
    sigma = 1.94
    N_1 = np.random.normal(0,sigma,D.shape)
    rnd = 10**(-N_1/10)
    F = 10
    y = 10*np.log10( 1000*(P_x_G*1.622*((lmb)**2) *0.5*1) / (((4*np.pi*r)**2) *1.2*1*F)*q_e*rnd*q_e_rcn1 )
    line1.set_data(r,y)

    hline1.set_ydata(-18)
    text1.set_position((0.02, -18.5))
    ax1.relim()
    ax1.autoscale_view()
    fig1.canvas.draw_idle()
    ######################################
    rd =np.sqrt((h1-h2)**2 + D**2)
    rd = np.sort(rd)
    P_r=0.8
    G_r=5 # 7dBi
    q_e_rcn2 = 1
    N_2 = np.random.normal(0, sigma*2, D.shape)
    rnd_2 = 10**(-N_2/10)
    F_2 = 126 # 21 dB for K=3dB and P_outage = 0.05
    y = 10*np.log10(  1000*(P_r*(G_r*1.622)**2*(lmb)**4*0.5**2*0.25)/((4*np.pi*rd)**4*1.2**2*1**2*F_2)*
            q_e**2*rnd*rnd_2*q_e_rcn1*q_e_rcn2  )
    line2.set_data(rd,y)
    hline2.set_ydata(-80)
    text2.set_position((0.02, -80.5))
    ax2.relim()
    ax2.autoscale_view()
    fig2.canvas.draw_idle()

r_height = widgets.FloatSlider(min=0.5, max=4, value=0.9, description= 'R_Height:')
t_height = widgets.FloatSlider(min=0.15, max=1.5, value=0.5, description= 'T_Height:')
widgets.interactive(update_plot, h1=r_height, h2=t_height)

In the second subplot, there would be a horizontal line at y=-80 with a text that should move in a similar way as the first subplot of the figure.
How could I add the second subplot using the same controls?
Regards.

A: This code does produce an error. The problem is that you are creating a figure with 211 (i.e. twohundredeleven) subplots. Those are stored in an array called ax1 and this array does not have a .semilogx method. Hence the error AttributeError: 'numpy.ndarray' object has no attribute 'semilogx'.
So, what you need instead is only two subplots, which you may directly unpack.
fig, (ax1, ax2) = plt.subplots(nrows=2)

The rest is basically adjusting the code for the new situation. It should then look like this:
from ipywidgets import widgets
from IPython.display import display
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

fig, (ax1, ax2) = plt.subplots(nrows=2)
line1, = ax1.semilogx([],[], label='Multipath')
hline1 = ax1.axhline(y = 0, linewidth=1.2, color='black',ls='--')
text1 = ax1.text(0, 0, "T Threshold",
                verticalalignment='top', horizontalalignment='left',
                transform=ax1.get_yaxis_transform(),
                color='brown', fontsize=10)
ax1.set_xlabel('Separation Distance, r (m)')
ax1.set_ylabel('Received Power, $P_t$ (dBm)')
ax1.grid(True,which="both",ls=":")
ax1.legend()

line2, = ax2.semilogx([],[], label='Monostatic Link')
hline2 = ax2.axhline(y = 0, linewidth=1.2, color='black',ls='--')
text2 = ax2.text(0, 0, "R Threshold",
                verticalalignment='top', horizontalalignment='left',
                transform=ax2.get_yaxis_transform(),
                color='brown', fontsize=10)
ax2.set_xlabel('Separation Distance, r (m)')
ax2.set_ylabel('Received Power, $P_t$ (dBm)')
ax2.grid(True,which="both",ls=":")
ax2.legend()

def update_plot(h1, h2):
    D = np.arange(0.5, 12.0, 0.0100)
    r = np.sqrt((h1-h2)**2 + D**2)
    freq = 865.7 #freq = 915 MHz
    lmb = 300/freq
    H = D**2/(D**2+2*h1*h2)
    theta = 4*np.pi*h1*h2/(lmb*D)
    q_e = H**2*(np.sin(theta))**2 + (1 - H*np.cos(theta))**2
    q_e_rcn1 = 1
    P_x_G = 4 # 4 Watt EIRP
    sigma = 1.94
    N_1 = np.random.normal(0,sigma,D.shape)
    rnd = 10**(-N_1/10)
    F = 10
    y = 10*np.log10( 1000*(P_x_G*1.622*((lmb)**2) *0.5*1) / (((4*np.pi*r)**2) *1.2*1*F)*q_e*rnd*q_e_rcn1 )
    line1.set_data(r,y)

    hline1.set_ydata(-18)
    text1.set_position((0.02, -18.5))
    ax1.relim()
    ax1.autoscale_view()

    ######################################
    rd =np.sqrt((h1-h2)**2 + D**2)
    rd = np.sort(rd)
    P_r=0.8
    G_r=5 # 7dBi
    q_e_rcn2 = 1
    N_2 = np.random.normal(0, sigma*2, D.shape)
    rnd_2 = 10**(-N_2/10)
    F_2 = 126 # 21 dB for K=3dB and P_outage = 0.05
    y = 10*np.log10(  1000*(P_r*(G_r*1.622)**2*(lmb)**4*0.5**2*0.25)/((4*np.pi*rd)**4*1.2**2*1**2*F_2)*
            q_e**2*rnd*rnd_2*q_e_rcn1*q_e_rcn2  )
    line2.set_data(rd,y)
    hline2.set_ydata(-80)
    text2.set_position((0.02, -80.5))
    ax2.relim()
    ax2.autoscale_view()

    fig.canvas.draw_idle()

r_height = widgets.FloatSlider(min=0.5, max=4, value=0.9, description= 'R_Height:')
t_height = widgets.FloatSlider(min=0.15, max=1.5, value=0.5, description= 'T_Height:')
widgets.interactive(update_plot, h1=r_height, h2=t_height)


text:
Q: If $(B_t)_{t\ge 0}$ is a Brownian motion and $\tau$ is a stopping time, then the stopped process $(B_{\min(\tau,t)})_{t\ge 0}$ is integrable Let $B=(B_t)_{t\ge 0}$ be a Brownian motion on a probability space $(\Omega,\mathcal A,\operatorname{P})$. By definition $B_t$ is normally distributed with mean $0$ and variance $t$.
Now, let $\mathbb F=(\mathcal F_t)_{t\ge 0}$ be a filtration on $(\Omega,\mathcal A)$ and $\tau$ be a $\mathbb F$-stopping time. Is the stopped process $B^\tau:=(B_{\min(\tau,t)})_{t\ge 0}$ integrable, i.e. does it hold $$B_{\min(\tau,t)}\in\mathcal{L}^1(\operatorname{P})\;\;\;\text{for all }t\ge 0\;?\tag{1}$$
I assume, that $(1)$ can be easily shown and most likely $B_{\min(\tau,t)}$ is normally distributed, too. However, how can we prove that?
Maybe we need boundedness of $\tau$. Then, there exists a $T>0$ such that $$B_{\min(\tau,t)}=B_T\;\;\;\text{for all }t>T$$ and $B_{\min(\tau,t)}$ would be normally distributed with mean $0$ and variance $T$ for all $t>T$.
But that is not exactly the desired statement $(1)$.

Remark: $\;\;\;$ $B$ is called Brownian motion $:\Leftrightarrow$ $B$ is a real-valued stochastic process on $(\Omega,\mathcal A,\operatorname{P})$ with

*

*$B_0=0$ almost surely

*$B$ has independent and stationary increments

*$B_t\;\tilde\;\mathcal{N}_{0,\;t}$

*$B$ is almost surely continuous

Please note, that out there exists a definition of a so-called $\mathbb{G}$-Brownian motion, where $\mathbb{G}$ is a given filtration on $(\Omega,\mathcal{A})$. One can show, that the Brownian motion defined above is a $\mathbb{G}$-Brownian motion, if $G$ satisfies the usual conditions.

A: Doob says: $B_{\tau \wedge t} = E[B_{t \wedge t}\mid \mathcal{F}_\tau]$.
Jensen says:
$$E[\lvert B_{\tau \wedge t}  \rvert] = E[\lvert E[B_{t \wedge t}\mid \mathcal{F}_\tau]\rvert] \leq E[ E[\lvert B_{t \wedge t}\rvert\mid \mathcal{F}_\tau]] = E[\lvert B_t \rvert] < \infty$$

A: There is an answer to this once one knows the density of the signed running minimum/maximum of a reflected Brownian motion,
$$M_t^{\pm} = \sup_{0 < s < t}\pm B_s \lor 0.$$
Clearly
$$|B_{\tau \land t}| \leq M_t^+ + M_t^-$$ almost surely. In fact, for each
$t,$ $M_t^\pm \overset{d}{=} |B_t|.$ (See Karatzas and Shreve, for instance).
Then
$$E|B_{\tau \land t}| \leq EM_t^+ + EM_t^- < \infty.$$


text:
Q: What is the Regular Expression that Enables Press the Enter Key to Exit a Loop (Python)? What is the regex that allows the 'Enter' key event (pressing the Enter key) as the only acceptable input? I want to be able to skip an 'optional' input() statement (e.g. middleName = input("Enter middle name (Optional): ") (for those who have no middle name or don't want to enter their middle name)) by pressing the 'Enter' key to proceed to a required input() statement (e.g. lastName = input("Enter last name: ")). The Empty String regex does not work for me because it does not 'restrict' acceptable input to the 'Enter' key event only; it allows all characters (e.g. numbers, special characters) entered by the user to be stored in the variable (e.g. middleName). I want to handle all non-alphabet characters as invalid inputs, except those I allow in a regex (e.g. apostrophe, hyphen, white space), if the user inputs a non-alphabet character.
Here's my code:
import re

print('Political Elections Voter Eligibility\n\n')

pattern1 = "^[A-Z]|^[A-Z]+'[A-Z]|^[A-Z]+-[A-Z]"
pattern2 = "^[A-Z]|^[A-Z].|^[A-Z]+'[A-Z]|^[A-Z]+-[A-Z]"
pattern3 = "^[A-Z]|^[A-Z]+'[A-Z]|^[A-Z]+-[A-Z]|^[A-Z]+ [A-Z]|^[A-Z]+ [A-Z]."

while True:

    firstName = input("Enter your first name and tap or click 'Enter': ")

    print('\n')

    if re.search(pattern1, firstName):

        break

    else:

        print('\n')

        print('Invalid entry.')

while True:

    middleName = input("Enter your middle name or middle initial and tap or click 'Enter' (Optional): ")

    print('\n')

    if re.search(pattern2, middleName):

        break

    else:

        print('\n')

        print('Invalid entry.')

while True:

    lastName = input("Enter your last name and tap or click 'Enter': ")

    print('\n')

    if re.search(pattern3, lastName):

        break

    else:

        print('\n')

        print('Invalid entry.')

while True:
try:
    age = int(input("Enter your age and tap or click 'Enter': "))

except ValueError:

    print('\n')

    print('Invalid entry.')

    continue

print('\n')

if 1 <= age <= 125:

    if 1 <= age <= 17:
        print('%s %s %s, age %s, you are not eligible to vote in political elections.' % (firstName, middleName, lastName, age))

        break

    if 18 <= age <= 125:
        print('%s %s %s, age %s, you are eligible to vote in political elections.' % (firstName, middleName, lastName, age))

        break

else:
    print('Invalid entry.')

A: I think, there is a more simple scenario to achieve your target. If you modify the if statement in the case of middleName.
from
    if re.search(pattern2, middleName):

to
    if len(middleName)==0 or re.search(pattern2, middleName):

so the code become(in the code related to middleName):
while True:

    middleName = input("Enter your middle name or middle initial and tap or click 'Enter' (Optional): ")

    print('\n')

    if len(middleName)==0 or re.search(pattern2, middleName):

        break

    else:

        print('\n')

        print('Invalid entry.')


text:
Q: Find the first missing date in a column (Oracle) I need to find the first missing date in a date column from plan_table table. which should not be in holiday_table or it should be belongs to any week end.
holiday_table stores all the holiday dates.
Plan_table contains dates. here we have to find the first missing date
Plan_id      Date
1           10/2/2016
2           10/3/2016
3           10/6/2016
4           10/9/2016
5           10/10/2016
6           10/12/2016
7           10/13/2016
8           10/16/2016

Here the first missing date is  10/4/2016, but if this date is in holiday_table then we have to show 10/5/2016 or next first occurrence..
Please help me to write a query for the same.

A: you can use the LEAD analytic function like this
 select d
 from
  (
    select
      date + 1  as d
    from
    (
      select
        date,
        lead(date) over(order by date)  as next_date
        from
        (
          select date   from plan_table
        union
          select date from holliday_table
         )
      order by date
    )
    where
      trunc(date) + 1 < trunc(next_date)
    order by d
  )
  where rownum = 1
 ;


text:
Q: Lambda expression for outer joins I want to write a lambda equivalent for
from col in db.Collectors
  join f in db.Files
on new { col.CollectorCode, col.StatusID }
  equals new { f.CollectorCode, StatusID = 1 } into f_join
from f in f_join.DefaultIfEmpty()
where
  col.FileID == null
orderby
  col.CollectorCode
select new {
  col.CollectorCode,
  col.Name
}

I have a table collector and table file. Table files contains multiple records(files) for each collector and I want to retrieve only the collectors that do not have records in table files.
I am not clear how to do it.
This is what I have, but is not working as expected:
db.Collectors.Join(
                db.Files,
                col => col.CollectorCode,
                f => f.CollectorCode,
                (col, f) => new { Collector = col });

A: The join ... into query syntax code corresponds to GroupJoin, not Join.
db.Collectors.GroupJoin(
    db.Files,
    col => col.CollectorCode,
    f => f.CollectorCode,
    (col, f_join) => new { col, f_join })

And any from clauses after the first will correspond to SelectMany:
db.Collectors.GroupJoin(...)
    .SelectMany(join => join.f_join.DefaultIfEmpty().Select(f => new{join.col, f}))
    //...

Personally, with a query like this that needs to propagate information projected from previous operations "past" another operation tends to be much clearer in query syntax than method syntax, due to the need in method syntax here to constantly be projecting everything out into anonymous types with all of the pieces of data to hold onto.

A: Sounds like a simple Where clause:
db.Collectors.Where(c => !db.Files.Any(f => f.CollectorCode == c.CollectorCode));

I use Any in the inner query so it will "short-circuit" when a match is found. There may be a more efficient approach, but this will work.


text:
Q: Correlation between two sequences of irrational numbers Let us consider the sequence $x(n+1) = \{b+x(n)\}$ with $x(0) = 0$. Here the brackets represent the fractional part function. Thus $x(n)= \{nb\}$ is related to Beatty sequences. If $b$ is irrational, it is known that the numbers $x(n)$ are uniformly distributed, with a lag-$k$ auto-correlation equal to
$6(b+k)^2 + 6(1-2\lfloor b+k+1\rfloor)(b+k)+6\lfloor b+k+1\rfloor^2
-6\lfloor b+k+1\rfloor+1$.
This result follows from section 5.4 in this article as well as results published here. Also, if $b_1$ and $b_2$ are two irrational numbers that are linearly independent over the set of rational numbers, then the correlation between the two sequences (one generated with $b_1$ and the other one with $b_2$) is zero.
But what if $b_1 = -1 + \sqrt{5}/2$ and $b_2 = 2/\sqrt{5}$? In that case, I know with absolute certainty (yet with no proof so far) that the correlation between the two sequences is 1/20 = 0.05. How do you prove this result?

A: Look at the closed subgroup $G\subset \mathbb T^2$ (using the notation that $\mathbb T=\mathbb R / \mathbb Z$) generated by $(b_1,b_2)$; it
 will be of the form $G=\{ (ax,bx):x\in\mathbb T\} $ for certain  integers $a$ and $b$. (In your case,  $(a,b)=(5,4)$.)  Your orbit $\{(nb_
1,nb_2):n=1,2,\ldots\}$ is uniformly distributed in $G$.  Your correlation is obtained by integrating with respect to the uniform (Haar) measure on $G$,
 namely  by $\int_0^1 (ax\bmod1)(bx\bmod1)dx$.
It might help in general to develop the Fourier series for the functions $ x\mapsto ax\bmod1$ and $bx\mapsto x\bmod1$ on $\mathbb T$.
In your specific case, however, the integral $I= \int_0^1 (5x\bmod1)(4x\bmod1)dx$ is given by the following edge-of-tedious expression
$$I=\int_0^{1/5}(5x)(4x)dx+
\int_{1/5}^{1/4}(5x-1)(4x)dx+
\int_{1/4}^{2/5}(5x-1)(4x-1)dx+
\int_{2/5}^{1/2}(5x-2)(4x-1)dx+
\int_{1/2}^{3/5}(5x-2)(4x-2)dx+
\int_{3/5}^{3/4}(5x-3)(4x-2)dx+
\int_{3/4}^{4/5}(5x-3)(4x-3)dx+
\int_{4/5}^{1}(5x-4)(4x-3)dx.
$$
The correlation coefficient is $\frac{I-1/4}{1/12}$.


text:
Q: Why is my mousePressEvent called twice? I want to make a QLabel clickable and followed this "how-to". I was not sure how to get this piece of code into my GUI (I am quite newbie to qt). What I did was:

*

*I created a new class (just copy/paste of ClickableLabel from the link, but I changed the signal to clicked(QMouseEvent* event))

*I added a QLabel to my GUI and "promoted" it to a ClickableLable

*I connected the signal to a slot of my main window where I std::cout some stuff:
connect(this->ui->label,SIGNAL(clicked(QMouseEvent*)),
        this,SLOT(on_label_clicked(QMouseEvent*)));

It seems to work. The problem is that each time I click on the label the mousePressedEvent gets called twice. I also tried mouseReleasedEvent but its the same.
Any ideas what could go wrong?
EDIT: Here is my modified ClickableLable:
class MyClickableLabel : public QLabel {
    Q_OBJECT
    public:
        MyClickableLabel(QWidget* parent=0);
        ~GBoardLabel();
    signals:
        void clicked(QMouseEvent* event);
    protected:
        void mouseReleaseEvent(QMouseEvent* event);
};
MyClickableLabel::MyClickableLabel(QWidget* parent) : QLabel(parent) {this->setText("");}
MyClickableLabel::~MyClickableLabel() {}
void MyClickableLabel::mouseReleaseEvent(QMouseEvent *event){
    std::cout << "CLICKED R" << std::endl;
    std::cout << event->type() << std::endl;
    std::cout << event->pos().x() << std::endl;
    std::cout << event->pos().y() << std::endl;
    emit clicked(event);
}

The couts in the in the above method I added only later and realized that the mouseReleaseEvent is actually only called once. But when I connect the clicked to a slot of my mainwindow, this slot recieves the event twice.
Then I removed the connect statement and to my surprise the signal is still emited and recieved (only once). I am a bit puzzled how this works, because I am pretty sure that I do not mistakenly have a connect anywhere in the code.
My label is working, but I would like to understand what is going on. Actually I am not 100% sure anymore that I didn't use some Qt creator feature make the connection. However, I have no idea where to find such connections. For example, I have a QButton on the same main window. In the gui editor I right clicked it and then "show slots"->"clicked()"->"OK" and automatically a method called on_pushButton_clicked() is created, but I have no idea, where this is called / how the button's signal is connected to this method. On the other hand, I do not get the MyClickableLabel::clicked(QMouseEvent*) listed in the list of slots for my label, thus I don't think I created the connection this way...

A: I could fix it, but I do not really understand what is going on...
It was not the mousePressEvent that was fired twice, but my on_label_clicked slot recieved the event twice.
I removed the connect statement and now the on_label_clicked is called only once per click. It seems like, there is something going on under the hood. Maybe when the slot is called on_label_clicked it gets automatically ("qtmatically") connected to the mouse events emmited from the child called label ?
EDIT: Still didnt find the official docs, but this blog explains it quite nicely. In summary, one just needs to use the naming convention for the slot
void on_<widget name="">_<signal name="">(<signal parameters="">);

to make use of the auto connect feature.


text:
Q: AngularJS ng-show and ng-hide doesn't work having a problem with angularjs logic here
I want to show the login link only when there is no user loggedin, and only show the logout link to logged in user, but it doesnt work properly
my HTML

     Sign in

     Sign out

The sign in is working well
this is my Controller
login Controller
 function ($scope, Service){
 $scope.auth = true;
 $scope.signin = function($event, userID, passwd){

                 Service.signin(userID,passwd).then(
                        function (response){
                            $scope.auth = true;
                  });
 }]).

logout Controller
  function ($scope, Service){
  $scope.auth = false;
  $scope.signout = function($event){
                 Service.signout().then(
                        function (response){
                            $scope.auth = false;
                  });
  }]).

those 2 log out and log in links are basically in my main page. I dont want to create a lot of pages, therefore I want to hide each other. When the user click the log in link, it will run the angularjs router, in this case /login, there is another templateURL for the form and it will be appended directly to the main page. Once the user has typed in the userID and password, the user need to click submit button, this is the code
<form role="form" name="form1">
    UserID<input type="text" id="userID" ng-model="userID">
    Password<input type="text" id="passwd" ng-model="passwd">
    <button data-ng-click="signin($event,userID,passwd); reload()">Login</button>

the reload() function will directly refresh the page. I am using the $window.location.reload()

A: Your equals comparison is incorrect.
This is assigning a value of false to auth:
ng-show="auth = false"

What you want is this (double and triple equals do comparisons)
ng-show="auth === false"

You can also do this:

     Sign in

     Sign out

A: Actually You need Two works for this task
First Work:-
You need to assign auth varibale in $rootScope not $scope. because this object used in two controller.
Like
function ($scope, dataService, $rootScope){
 $scope.auth = true;
 $scope.signin = function($event, userID, passwd){

                 Service.signin(userID,passwd).then(
                        function (response){
                            $rootScope.auth = true;
                  });
 }]).

Second Work:
You need to change ng-show="auth = false" to ng-show="auth === false". You have used single equal. it should be double or triple equal
OR
if you assigned the object in $rootScope, then you don't need to check the condition for is true or false in the element. because you already define   auth is false or true in your controller. So you can just call ng-show="auth only.

A: Just try the followingng-show="auth"
Please let me know if it is still not working..


text:
Q: overloading template function Currently, I encounter some difficulty in overloading a certain function. here's my code:
template<typename Value>
bool process(Value thisValue)
{
  return processAccordingToTheType(thisValue);
}

So, there are two overloaded function of processAccordingToTheType:
bool processAccordingToTheType(int thisValue){}
bool processAccordingToTheType(string thisValue){}

when I try to compile it, it said:
error C2665: 'processAccordingToTheType' : none of the 2 overloads could convert all the argument types

what do I need to do?
Update:
int main()
{
  int i = 1;
  process <int> (i);
}

A: From your sample code I understand you need two things to be done:

*

*Call a type specific process function

*Restrict these calls to string and int types

Wrapping the processAccordingToType function inside process<T> is completely redundant: process<T> actually means 'process according to type'. The keyword here is 'template specialization'. You need to specialize your 'process according to type' method for int and string.
You can do this as below:
#include <iostream>

using namespace std;

template<typename T>
bool process(T t)
{
    // call a Compile-Time Assertion
    cout << "I don't want this to be called." << endl;
}

template <>
bool process<int>(int i)
{
    cout << "process(int) called." << endl;
}

template <>
bool process<string>(string s)
{
    cout << "process(string) called." << endl;
}

int main()
{
    process(1);
    process(string("s"));
    process(1.0d);
}

Output:
process(int) called.
process(string) called.
I don't want this to be called.

Ideally, you want to prevent the users of your API calling process with other types. Allowing them to call and handling this at runtime (like it's done in my example) is not acceptable. You achieve this with Compile-Time Assertions. Read "Modern C++ Designs" by Andrei Alexandrescu for ways of doing that.

A: Look into template specialization. Does what you're looking for without deferring to another function based on type.
http://www.cprogramming.com/tutorial/template_specialization.html

A: You can overload function templates with either a non-template function or another template function.  Make sure that whatever you do, you test incrementally as template errors are notoriously hard to understand.
http://www.cplusplus.com/doc/tutorial/templates/
#include <iostream>

using namespace std;

template <typename Value>
bool processAccordingToTheType( Value thisValue ){
    cout << "Generic Type" << endl;
    return false;
}

bool processAccordingToTheType(int thisValue){
    cout << "int type" << endl;
    return true;
}

template <typename Value>
bool process( Value thisValue ){
    return processAccordingToTheType(thisValue);
}

int main( int argc, char* argv[] ){

    cout << process( 1 ) << endl;
    cout << process( "Hello" ) << endl;

    return 0;
}


text:
Q: Projected coordinate in TikZ is not properly placed I'm trying to draw an airplane.  When I was drawing the window for the cockpit, I was using projected points to get right angles.  But things aren't working out as expected.  Could anyone give me a pointer about what I'm doing incorrectly?
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\pagestyle{empty}
\begin{document}

\def\aeBodyRadius{0.25cm}
\def\aeBodyNoseDistance{0.21cm}
\begin{tikzpicture}[x=5cm,y=5cm,scale=3,every node={transform shape}]

  \coordinate (TAIL) at (0,0);
  \coordinate (NOSE) at ($(TAIL)+(30:1)$);

  \coordinate (MID)     at ($(TAIL)!0.75!(NOSE)$);

  \coordinate (MID/TOP) at ($(MID)!\aeBodyRadius!90:(NOSE)$);
  \coordinate (MID/BOT) at ($(MID)!\aeBodyRadius!-90:(NOSE)$);

  \coordinate (NOSE/TIP) at ($(NOSE)!\aeBodyNoseDistance!90:(MID)$);

  \coordinate (HIND/TOP) at ($(TAIL)!\aeBodyRadius!90:(NOSE)$);
  \coordinate (HIND/BOT) at ($(TAIL)!\aeBodyRadius!-90:(NOSE)$);

  \node[fill,circle,inner sep=1pt] at (MID/TOP) {};
  \node[fill,circle,inner sep=1pt] at (MID/BOT) {};
  \node[fill,circle,inner sep=1pt] at (HIND/TOP) {};
  \node[fill,circle,inner sep=1pt] at (HIND/BOT) {};

  \draw[rounded corners=10pt]
                             (HIND/TOP) --
                             (MID/TOP)  --
                             node [pos=0.25] (WINDOW/TOP/N) {}
                             node [pos=0.50] (WINDOW/BOT/N) {}
                             (NOSE/TIP) --
                             (MID/BOT)  --
                             (HIND/BOT);
    \coordinate (WINDOW/TOP) at (WINDOW/TOP/N.center);
    \coordinate (WINDOW/BOT) at (WINDOW/BOT/N.center);

    \coordinate (WINDOW/RIG/T) at ($(TAIL)!(WINDOW/TOP)!(NOSE)$);
    \coordinate (WINDOW/RIG)   at ($(WINDOW/TOP)!(WINDOW/BOT)!(WINDOW/RIG/T)$);

    \draw (WINDOW/TOP) -- (WINDOW/RIG) -- (WINDOW/BOT);

    \draw[red] (TAIL) -- (NOSE);

\end{tikzpicture}

\end{document}

The "red" line runs down the center of the plane clearly shows how my perpendicular is not what it should be.
UPDATE
What seems not to be working is the following snippet of code:
    \coordinate (WINDOW/RIG/T) at ($(TAIL)!(WINDOW/TOP)!(NOSE)$);
    \coordinate (WINDOW/RIG)   at ($(WINDOW/TOP)!(WINDOW/BOT)!(WINDOW/RIG/T)$);

The projected points do not seem to lie on the appropriate perpendicular.  In particular,
(WINDOW/RIG) should lie above the red line since the line through (WINDOW/TOP) and (WINDOW/RIG/T) should be perpendicular to the red line through (TAIL) and (NOSE).

A: You probably intended to put WINDOW/RIG/T along the main axis, but this worked.  (If it aint broke...)

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\pagestyle{empty}
\begin{document}
\def\aeBodyRadius{0.25cm}
\def\aeBodyNoseDistance{0.21cm}
\begin{tikzpicture}[x=5cm,y=5cm,scale=3,every node={transform shape}]
  \coordinate (TAIL) at (0,0);
  \coordinate (NOSE) at ($(TAIL)+(30:1)$);
  \coordinate (MID)     at ($(TAIL)!0.75!(NOSE)$);
  \coordinate (MID/TOP) at ($(MID)!\aeBodyRadius!90:(NOSE)$);
  \coordinate (MID/BOT) at ($(MID)!\aeBodyRadius!-90:(NOSE)$);
  \coordinate (NOSE/TIP) at ($(NOSE)!\aeBodyNoseDistance!90:(MID)$);
  \coordinate (HIND/TOP) at ($(TAIL)!\aeBodyRadius!90:(NOSE)$);
  \coordinate (HIND/BOT) at ($(TAIL)!\aeBodyRadius!-90:(NOSE)$);
  \node[fill,circle,inner sep=1pt] at (MID/TOP) {};
  \node[fill,circle,inner sep=1pt] at (MID/BOT) {};
  \node[fill,circle,inner sep=1pt] at (HIND/TOP) {};
  \node[fill,circle,inner sep=1pt] at (HIND/BOT) {};
  \draw[rounded corners=10pt]
                             (HIND/TOP) --
                             (MID/TOP)  --
                             node [pos=0.25] (WINDOW/TOP/N) {}
                             node [pos=0.50] (WINDOW/BOT/N) {}
                             (NOSE/TIP) --
                             (MID/BOT)  --
                             (HIND/BOT);
  \coordinate (WINDOW/TOP) at (WINDOW/TOP/N.center);
  \coordinate (WINDOW/BOT) at (WINDOW/BOT/N.center);

%start of modifications
   \coordinate (WINDOW/RIG/T) at ($(TAIL)!(WINDOW/TOP)!90:(NOSE)$);
   \coordinate (WINDOW/RIG)   at ($(WINDOW/TOP)!(WINDOW/BOT)!90:(WINDOW/RIG/T)$);
   \node[fill,circle,inner sep=1pt] at (WINDOW/RIG/T) {};% way down near the tail
   \draw[blue] (WINDOW/TOP) -- (WINDOW/RIG) -- (WINDOW/BOT);
%end of modifications

   \draw[red] (TAIL) -- (NOSE);

\end{tikzpicture}

\end{document}

A: As mentioned by A.Ellett, the error is caused by \pgfpointnormalised. A solution to obtain a better precision is given in this answer.
Applied on the MWE:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\pagestyle{empty}

% use the Mark Wibrow's correction
\makeatletter
\def\pgfpointnormalised#1{%
\pgf@process{#1}%
\pgfmathatantwo{\the\pgf@y}{\the\pgf@x}%
\let\pgf@tmp=\pgfmathresult%
\pgfmathcos@{\pgf@tmp}\pgf@x=\pgfmathresult pt\relax%
\pgfmathsin@{\pgf@tmp}\pgf@y=\pgfmathresult pt\relax%
}
\makeatother

\begin{document}

\def\aeBodyRadius{0.25cm}
\def\aeBodyNoseDistance{0.21cm}
\begin{tikzpicture}[x=5cm,y=5cm,scale=3,every node={transform shape}]

  \coordinate (TAIL) at (0,0);
  \coordinate (NOSE) at ($(TAIL)+(30:1)$);

  \coordinate (MID)     at ($(TAIL)!0.75!(NOSE)$);

  \coordinate (MID/TOP) at ($(MID)!\aeBodyRadius!90:(NOSE)$);
  \coordinate (MID/BOT) at ($(MID)!\aeBodyRadius!-90:(NOSE)$);

  \coordinate (NOSE/TIP) at ($(NOSE)!\aeBodyNoseDistance!90:(MID)$);

  \coordinate (HIND/TOP) at ($(TAIL)!\aeBodyRadius!90:(NOSE)$);
  \coordinate (HIND/BOT) at ($(TAIL)!\aeBodyRadius!-90:(NOSE)$);

  \node[fill,circle,inner sep=1pt] at (MID/TOP) {};
  \node[fill,circle,inner sep=1pt] at (MID/BOT) {};
  \node[fill,circle,inner sep=1pt] at (HIND/TOP) {};
  \node[fill,circle,inner sep=1pt] at (HIND/BOT) {};

  \draw[rounded corners=10pt]
                             (HIND/TOP) --
                             (MID/TOP)  --
                             node [pos=0.25] (WINDOW/TOP/N) {}
                             node [pos=0.50] (WINDOW/BOT/N) {}
                             (NOSE/TIP) --
                             (MID/BOT)  --
                             (HIND/BOT);
    \coordinate (WINDOW/TOP) at (WINDOW/TOP/N.center);
    \coordinate (WINDOW/BOT) at (WINDOW/BOT/N.center);

    \coordinate (WINDOW/RIG/T) at ($(TAIL)!(WINDOW/TOP)!(NOSE)$);
    \coordinate (WINDOW/RIG)   at ($(WINDOW/TOP)!(WINDOW/BOT)!(WINDOW/RIG/T)$);

    \draw (WINDOW/TOP) -- (WINDOW/RIG) -- (WINDOW/BOT);

    \draw[red] (TAIL) -- (NOSE);

\end{tikzpicture}

\end{document}

A: To show what I meant by drawing it flat and rotating it:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\pagestyle{empty}

\newlength{\myx}
\newlength{\myy}

\begin{document}
\def\aeBodyRadius{0.25cm}
\def\aeBodyNoseDistance{0.21cm}
\begin{tikzpicture}[x=5cm,y=5cm,scale=3,every node={transform shape},rotate=30]% changed here
  \coordinate (TAIL) at (0,0);
  \coordinate (NOSE) at ($(TAIL)+(1,0)$);% changed here
  \coordinate (MID)     at ($(TAIL)!0.75!(NOSE)$);
  \coordinate (MID/TOP) at ($(MID)!\aeBodyRadius!90:(NOSE)$);
  \coordinate (MID/BOT) at ($(MID)!\aeBodyRadius!-90:(NOSE)$);
  \coordinate (NOSE/TIP) at ($(NOSE)!\aeBodyNoseDistance!90:(MID)$);
  \coordinate (HIND/TOP) at ($(TAIL)!\aeBodyRadius!90:(NOSE)$);
  \coordinate (HIND/BOT) at ($(TAIL)!\aeBodyRadius!-90:(NOSE)$);
  \node[fill,circle,inner sep=1pt] at (MID/TOP) {};
  \node[fill,circle,inner sep=1pt] at (MID/BOT) {};
  \node[fill,circle,inner sep=1pt] at (HIND/TOP) {};
  \node[fill,circle,inner sep=1pt] at (HIND/BOT) {};
  \draw[rounded corners=10pt]
                             (HIND/TOP) --
                             (MID/TOP)  --
                             node [pos=0.25] (WINDOW/TOP/N) {}
                             node [pos=0.50] (WINDOW/BOT/N) {}
                             (NOSE/TIP) --
                             (MID/BOT)  --
                             (HIND/BOT);
  \coordinate (WINDOW/TOP) at (WINDOW/TOP/N.center);
  \coordinate (WINDOW/BOT) at (WINDOW/BOT/N.center);

  \node[fill,circle,inner sep=1pt] at (NOSE) {};
  \node[fill,circle,inner sep=1pt] at (TAIL) {};
  \coordinate (WINDOW/RIG/T) at ($(TAIL)!(WINDOW/TOP)!(NOSE)$);
  \coordinate (WINDOW/RIG)   at ($(WINDOW/TOP)!(WINDOW/BOT)!(WINDOW/RIG/T)$);
  \node[fill,circle,inner sep=1pt] at (WINDOW/RIG/T) {};
  \draw[blue] (WINDOW/TOP) -- (WINDOW/RIG) -- (WINDOW/BOT);
  \draw[red] (TAIL) -- (NOSE);

\end{tikzpicture}

\end{document}


text:
Q: SignalR client HubConnection Stop I have malicious problem with stopping connection in SignalR client.
Here we go with my code.
I start connection with simple method
private void Initialize()
    {
        var hermesHubAddress = ConfigurationManager.AppSettings["HermesUrl"];
        _hubConnection = new HubConnection(hermesHubAddress)
        {
            Credentials = CredentialCache.DefaultCredentials
        };

        _hubProxy = _hubConnection.CreateHubProxy("HermesHub");
        _hubProxy.On<Notification>("Notify", Recieve_Message);
        _hubConnection.Start().Wait();
        _hubConnection.Error += HubConnectionOnError;
        _hubConnection.StateChanged += HubConnectionOnStateChanged;
    }

then when client performs an action to close connection
public void Stop()
    {
        _hubConnection.Stop();
        _hubConnection.Dispose();
    }

Event listner noticed connection state changed and invoked action
private void HubConnectionOnStateChanged(StateChange stateChange)
    {
        if (stateChange.NewState == ConnectionState.Connected)
        {
            if (ConnectionEvent != null)
                ConnectionEvent.Invoke(true);
        }
        else
        {

            if (ConnectionEvent != null)
                ConnectionEvent.Invoke(false);
        }
    }

everything works fine and client is disconnected but when SignalR server broadcasts message somehow _hubProxy autoreconnect to the server and gets response.

A: If there is more than one message to be sent SignalR will try to group them send in one payload. This is the reason why M is an array (you can find more about SignalR protocol in my post).
SignalR cannot send just one message per poll. Polling can be really slow since the client needs to create a new HTTP request for one poll. If you get messages faster than the interval between polls you wouldn't be able to keep up if you sent just one message per poll and you will start missing messages.


text:
Q: Best Practices: Scheduled Reports We are having issues with tons of different users trying to schedule reports, and it is causing others to not be able to schedule their reports because only 2 reports can be scheduled in 1 hour.
I am trying to put some best practices together for this, so we don't run into this issue anymore.
I was wondering if anybody out there already has some best practices for this, so I can get an idea of what all to put in ours?
Thanks,
Adam

A: I see two options
1) Upgrade your Salesforce edition, see Analytics Limits Per Edition
2) Try Conga Courier apps from AppExchange marketplace


text:
Q: Python number format changing after styling I have a dataframe that resembles the following:

Name
Amount

A
3,580,093,709.00

B
5,656,745,317.00

Which I am then applying some styling using CSS, however when I do this the Amount values become scientific formatted so 3.58009e+09 and 5.39538e+07.

Name
Amount

A
3.58009e+09

B
5.65674e+07

How can I stop this from happening?
d = {'Name': ['A', 'B'], 'Amount': [3580093709.00, 5656745317.00]}
df = pd.DataFrame(data=d)
df= df.style
df

A: You are not showing how you are styling the columns but, to set it as a float with two decimals, you should add the following to your styler, based on the first line of Pandas documentation (they write it for something):
df = df.style.format(formatter={('Amount'): "{:.2f}"})

Here is the link for more information:
https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html


text:
Q: Зачем в Python нужен self если можно создать простую функцию и передать ей переменную Вот здесь на сайте объясняется суть self: Для чего в python нужен self?
Вопрос: зачем зачем создавать эти страшные конструкции типа __init__ и self если указанная ниже функция выдаст тоже самое?
def Dog(name):
   return f'Имя моей собаки {name}'

nick_name = Dog('Rex')
print(nick_name)

A: *

*А что вы будете делать, когда от Dog вам нужно будет не одно свойство получить, а два, десять, сто свойств? Будете писать сто отдельных функций? Будете писать одну мега-функцию с параметром, в котором будете передавать, какое свойство вы хотите получить или изменить?

*А если вы захотите от Dog каких-то действий, зависящих от его внутреннего состояния? Например, у него есть уровень сытости и вы хотите, чтобы он по-разному гавкал в зависимости от этого уровня?

*А если вы захотите иметь несколько разных Dog с разным состоянием - вы будете это состояние хранить где-то снаружи и передавать в ваши функции каждый раз вручную?

Просто нужно чуть продолжить мысль о том, что вам может понадобиться от класса и как этим всем было бы удобно пользоваться - и тогда необходимость инкапсуляции, т.е. включения/скрытия полей (переменных) и методов (функций) внутри класса и его объектов, придёт к вам сама собой.
Собственно, self как-раз и представляет собой собой ссылку на объект класса, на его состояние.
А конструктор __init__ нужен, чтобы в удобной форме задать первоначальное состояние экземпляра объекта. Например, имя для собаки. Вряд ли это имя поменяется в течении жизни объекта "собака", так что очень удобно задать это имя сразу при создании объекта. Так исторически и возникла необходимость в конструкторе класса.
И так со всеми штуками, относящимися к классам. Если начать разбираться, то все они нужны как-раз для удобства программиста.


text:
Q: Tkinter tkFileDialog module- limited to one folder The python Tkinter module filedialog.askopenfilename(initialdir , title, filetypes) works fine and opens the initial directory in a new Tkinter window.
But, I can move freely between folders and directories in the new Tkinter window and open files from every directory I want although I defined an initial directory.
I would like to know if I can define an initial directory and the user can open files from this specific directory without moving freely between non-defined directories.
Thanks :)

A: you can use,  initialdir:
dlg = tkFileDialog.Open(self, filetypes = ftypes, initialdir=r"C:\Users\danil\Documents")


text:
Q: how to find the angle of the certain point I drawn the svg circle using start and endangle as follow,
document.getElementById("circle").setAttribute("d", describeArc(150, 150, 100, 180, 360));
            function getPathArc(center, start, end, radius) {
                        end = end - 0.0001;
                        var degree = end - start;
                        degree = degree < 0 ? (degree + 360) : degree;
                        var clockWise = (degree < 180) ? 0 : 1;
                        return getPiePath(center, degreeToLocation(start, radius, center), degreeToLocation(end, radius, center), radius, clockWise);
            }
            function getPiePath(center, start, end, radius, clockWise) {
                        return 'M ' + start.x + ' ' + start.y + ' A ' + radius + ' ' + radius + ' 0 ' + clockWise + ' 1 ' + end.x + ' ' + end.y;
            };
            function degreeToLocation(degree, radius, center) {
                    var radian = (degree * Math.PI) / 180;
                    return {
                        'x' : Math.cos(radian) * radius + center.x,
                        'y': Math.sin(radian) * radius + center.y
                    };
            }
            function describeArc(x, y, radius, startAngle, endAngle){
                var endAngle = endAngle - startAngle;
                startAngle = startAngle <= 0 ? (360 + startAngle) % 360 : startAngle % 360;
                endAngle = endAngle < 0 ? (360 + endAngle + startAngle) % 360 : Math.abs(endAngle + startAngle) % 360;
                    var direction = getPathArc({'x': x, 'y': y}, startAngle, endAngle, radius);
                    var d = direction;
                    return d;
            }

here is the sample https://jsfiddle.net/ndmsqmao/3/
i need to draw the one tick line for that circle for specified point.
for example let us consider,
if it's value is start from 50 to 100 mean i need to draw the one tick line for 66th value.. how to acheive this?

A: Hope this helps...
var minValue = 50, maxValue = 100, value = 66,
    minAngle = 180, maxAngle = 360, angle;

angle = minAngle + (value - minValue) / (maxValue - minValue) * (maxAngle - minAngle);

alert(angle);

A: I hope i understand your Question...
var min = 50;
var max = 100;
var value = 66;

var angle = 180/(max-min)*(value-min)+180;

console.log (angle);


text:
Q: Searching through very large files with php to extract a block very efficiently I've been having a major headache lately with parsing metadata from video files, and found part of the problem is a disregard of various standards (or at least differences in interepretation) by video-production software vendors (and other reasons).
As a result I need to be able scan through very large video (and image) files, of various formats, containers and codecs, and dig out the metadata. I've already got FFMpeg, ExifTool Imagick and Exiv2 each to handle different types of metadata in various filetypes and been through various other options to fill some other gaps (please don't suggest libraries or other tools, I've tried them all :)).
Now I'm down to scanning the large files (upto 2GB each) for an XMP block (which is commonly written to movie files by Adobe suite and some other software). I've written a function to do it, but I'm concerned it could be improved.
function extractBlockReverse($file, $searchStart, $searchEnd)
{
    $handle = fopen($file, "r");
    if($handle)
    {
        $startLen = strlen($searchStart);
        $endLen = strlen($searchEnd);

        for($pos = 0,
                $output = '',
                $length = 0,
                $finished = false,
                $target = '';
            $length < 10000 &&
                !$finished &&
                fseek($handle, $pos, SEEK_END) !== -1;
            $pos--)
        {
            $currChar = fgetc($handle);
            if(!empty($output))
            {
                $output = $currChar . $output;
                $length++;

                $target = $currChar . substr($target, 0, $startLen - 1);
                $finished = ($target == $searchStart);
            }
            else
            {
                $target = $currChar . substr($target, 0, $endLen - 1);
                if($target == $searchEnd)
                {
                    $output = $target;
                    $length = $length + $endLen;
                    $target = '';
                }
            }
        }

        fclose($handle);
        return $output;
    }
    else
    {
        throw new Exception('not found file');
    }
    return false;
}

echo extractBlockReverse("very_large_video_file.mov",
    '<x:xmpmeta',
    '</x:xmpmeta>');

At the moment it's 'ok' but I'd really like to get the most out of php here without crippling my server so I'm wondering if there is a better way to do this (or tweaks to the code which would improve it) as this approach seems a bit over the top for something as simple as finding a couple of strings and pulling out anything between them.

A: You can use one of the fast string searching algorithms - like Knuth-Morris-Pratt
 or Boyer-Moore in order to find the positions of the start and end tags, and then read all the data between them.
You should measure their performance though, as with such small search patterns it might turn out that the constant of the chosen algorithm is not good enough for it to be worth it.

A: With files this big, I think that the most important optimization would be to NOT search the string everywhere. I don't believe that a video or image will ever have a XML block smack in the middle - or if it has, it will likely be garbage.
Okay, it IS possible - TIFF can do this, and JPEG too, and PNG; so why not video formats? But in real world applications, loose-format metadata such as XMP are usually stored last. More rarely, they are stored near the beginning of the file, but that's less common.
Also, I think that most XMP blocks will not have sizes too great (even if Adobe routinely pads them in order to be able to "almost always" quickly update them in-place).
So my first attempt would be to extract the first, say, 100 Kb and last 100 Kb of information from the file. Then scan these two blocks for "

If the search does not succeed, you will still be able to run the exhaustive search, but if it succeeds it will return in one ten-thousandth of the time. Conversely, even if this "trick" only succeeded one time in one thousand, it would still be worthwhile.


text:
Q: I want to set my photos into gridview in an Android? Here is my mainActivity.java
package com.domore.gridviewtutorial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;

public class AndroidGridLayoutActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_grid_layout);
        GridView gridView=(GridView)findViewById(R.id.grid_view);
        gridView.setAdapter(new ImageAdapter(this));
    }
}

i have a grid_layout.xml which see my all the image from drawable directory
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/grid_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:columnWidth="90dp"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp"
    android:gravity="center"
    android:stretchMode="columnWidth" >

</GridView>

i have one more class of adapter class that inflate this grid_layout.xml namely ImageAdapter.java
package com.domore.gridviewtutorial;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

/**
 * Created by MY WORLD on 11/28/2015.
 */
public class ImageAdapter extends BaseAdapter {
    private Context context;

    //Keep all images into an array
    public Integer[] mThumbIds={R.drawable.first,R.drawable.second,R.drawable.third,R.drawable.fourth,
    R.drawable.fifth,R.drawable.sixth,R.drawable.seventh,R.drawable.eighth,R.drawable.ninth,R.drawable.tenth,
    R.drawable.eleventh,R.drawable.twelth,R.drawable.thirteenth,R.drawable.fourtheenth,R.drawable.fiftheenyth};

    public ImageAdapter(Context context){
        this.context=context;
    }
    @Override
    public int getCount() {
        return mThumbIds.length;
    }

    @Override
    public Object getItem(int position) {
        return mThumbIds[position];
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView=new ImageView(context);
        imageView.setImageResource(mThumbIds[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(70,70));
        return imageView;
    }
}

Complete LOGCAT here
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                               at com.domore.gridviewtutorial.AndroidGridLayoutActivity.onCreate(AndroidGridLayoutActivity.java:14)

can anyone please, solve out this problem?

A: Replace this -
setContentView(R.layout.activity_android_grid_layout);

with - setContentView(R.layout.grid_layout);
You are using wrong setContentView .

A: Here is complete solution of you problem
ImageAdapter class
public class ImageAdapter extends BaseAdapter {
private Context context;

// Keep all images into an array
public Integer[] mThumbIds = { R.drawable.ic_communities,
        R.drawable.ic_home, R.drawable.ic_launcher, R.drawable.ic_pages,
        R.drawable.ic_people, R.drawable.ic_people, R.drawable.ic_whats_hot };

public ImageAdapter(Context context) {
    this.context = context;
}

@Override
public int getCount() {
    return mThumbIds.length;
}

@Override
public Object getItem(int position) {
    return mThumbIds[position];
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView = new ImageView(context);
    imageView.setImageResource(mThumbIds[position]);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
    return imageView;
}}

put code inside oncreate MainActivity
setContentView(R.layout.grid_layout.xml);// Missing this to explain
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(this));

second.xml file
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>

This will work for me, check this.
Happy coding And Happy to Help.

A: You have set the content view activity to different layout
setContentView(R.layout.activity_android_grid_layout);

change it to
setContentView(R.layout.grid_layout.xml);

Include layout where your grid layout is present.


text:
Q: Testing REST API, Bulk API limits I am working on a scenario where I export a set of records to Salesforce via bulk API 2.0, I need to handle the daily Salesforce limit exceeded scenarios gracefully.Mainly the REST and Bulk V2 API limits.

*

*Is there a document on what kind of errors and error codes Salesforce returns when limits are reached? (sounds like a googlable point, but could not find any official resource)

*After implementing the logic to handle the above limits, is there any way I can test this functionality apart from intentionally exceeding the limits on the org? - The org is shared and I cannot afford to consume all the APIs myself.

A: Once you exceed a specific rolling limit, you'll receive a HTTP 403 response code with the errorCode "REQUEST_LIMIT_EXCEEDED" in the return payload. There is no built-in mechanism to test this functionality other than configuring your API consumer so it handles 403 return codes with that message appropriately.
One resource you can take advantage of is the Limits API, which will provide a payload describing your current organization's limit consumption status.


text:
Q: how to find average of object with same type of values let numbers = {
    name:"Faisal", value:20,
    name:"qasim", value:32,
    name:"asim", value:20,
    name:"abid", value:30,
    name:"yaqoob", value:50
};

A: assuming you meant to post the following example:
let numbers = [
                { name:"Faisal" , value:20},
                { name:"qasim" , value:32},
                { name:"asim" , value:20},
                { name:"abid" , value:30},
                { name:"yaqoob" , value:50 }
              ]

Then this should get you the average:
var total = 0;
for(var i = 0; i < numbers.length; i++) {
    total += numbers[i].value;
}
var avg = total / numbers.length;

alternatively, you do it more concisely with reduce, like this:
var avg = numbers.reduce(function (accumulator, currentValue) { return accumulator + currentValue.value }, 0) / numbers.length;


text:
Q: Avoiding long case statement on argument class There is a class hierarchy of tasks that can be performed by the class A.
Inside the class A there is a long case statement checking for the task class  and calling the correspondent handler method.
Class Task
End Class

Class TaskX
Inherits Task
End Class

Class TaskY
Inherits Task
End Class

...

Class A
    Public Sub PerformTask(Task As Task)
        Select Case Task.GetType
            Case GetType(TaskX)
                PerformTaskX(CType(Task, TaskX))
            Case GetType(TaskY)
                PerformTaskY(CType(Task, TaskY))
        End Select
    End Sub

    Private Sub PerformTaskX(Task As TaskX)
    End Sub

    Private Sub PerformTaskY(Task As TaskY)
    End Sub

    ...
End Class

The tasks have their individual parameters, validation logic, etc. The example is simplified.
I want to avoid the case statement and I am looking for alternative solutions.
The general idea is mapping a class type to a Handler(Of class) that could work somehow like this:
Delegate Sub Handler(Task As Task)

Private TypeToHandlerDict As New Dictionary(Of System.Type, Handler) From { _
            {GetType(TaskX), AddressOf PerformTaskX}, _
            {GetType(TaskY), AddressOf PerformTaskY} _
        }

so that I can replace the PerformTask method contents with the much more elegant:
Public Sub PerformTask(Task As Task)
    Dim handler As Handler = Nothing
    If Not TypeToHandlerDict.TryGetValue(Task.GetType, handler) Then Exit Sub
    handler(Task)
End Sub

But it doesn't work.
The delegate binds to type Task, but the handler methods accept a task subclass parameter. I am using Option Strict.
I could rewrite all handler methods to accept a Task object and perform an explicit cast, but this is equally inelegant.
Any suggestions?
Thank you!
Update: Here is the solution thanks to the answer from @Sehnsucht.
Class Task
    Public MustOverride Sub Perform(a As A)
End Class

Class TaskX
Inherits Task
    Public Overrides Sub Perform(a As A)
        a.DoThis()
    End Sub
End Class

Class TaskY
Inherits Task
    Public Overrides Sub Perform(a As A)
        a.DoThat()
    End Sub
End Class

...

Class A
    Public Sub PerformTask(Task As Task)
        Task.Perform(Me)
    End Sub

    Public Sub DoThis()
    End Sub

    Public Sub DoThat()
    End Sub

    ...
End Class

A: All the PerformTask... have the same signature and that's enforced by the delegate Handler you showed in your post.
So you should make an Overridable method in your Task class with a default implementation (or mark the method as MustOverride if the Task class is MustInherit), method which will be overrided by it's inheritors to do the job according to their specific case.
Class Task
    Public Overridable Sub Perform()
        ' implementation specific to Task ("default" case)
    End Sub
End Class

Class TaskX
    Inherits Task

    Public Overrides Sub Perform()
        ' implementation specific to TaskX
        ' you can call the parent implementation if needed with
        MyBase.Perform()
    End Sub
End Class

'Usage
Class A
    Public Sub PerformTask(task As Task)
        task.Perform() ' will call the "right one" according to it's runtime type
    End Sub
End Class


text:
Q: Access by multiple users to access database I am not very familiar with Access database till now i was only programming to SQL Server but now it's time to do so. I am building WinForms application which will be using Access database and i have some question related to that point if you don't mind. My application will be used by multiple users and there will be one access databsae. My questions as below:

*

*Is there any problem with accessing access database in same time by many users or only one user can be connected?

*If i develop my program to use access 2016 and some of my users will have diffrent windows version and also diffrent access version
  will it works?

*Should i know something else? :)

A: If your client want to have a file based database and this is a project constraint , MS Access is the best choice. If you want a more detailed advice, please let me know how many users will perform Read/Write or Read transactions, the size of the database and if the application will run in client-server mode in a LAN/WAN, Cloud or Remote Desktop environment.
Back to your questions:

*

*Depending on these conditions you may range from 10 to 20/25 users. Remember that you can always try with MS Access and later upgrade to a MS SQL database in a couple of hours.

*If your front-end application can link to a 2016 Access database, it will do that without installing MS Access to the clients that will run your App, i.e. the vb.net compiled App will install all needed drivers. If you develop your App within MS Access 2016 (Access Form and reports, some VBA) you can run it with the free runtime version of MS Access, but this only when no older version of Access is installed on the running workstation.

*Please check with your client the real reasons for a file-based database...

A: To answer the questions as asked:

*

*You might run into an issue with this, as access was really designed as a personal use database.  Having anything more than a small handful of users hitting against it at once will in fact cause problems, as it's not really well designed for that purpose...

*This should in theory be fine, as the application itself is interfacing with the database, not the end user...

*It seems like you're taking a step backwards using access for this, and SQL might very well be better suited for this purpose.  This isn't me trying to just bash access either, this comes from personal experience.  Going with this sort of design is likely to cause you more headaches than good.


text:
Q: cakePHP complex find query how do I build a find() query in cakePHP using these conditions:
Find where
MyModel.x = 1 and MyModel.y = 2 OR
MyModel.x = 1 and MyModel.y value does not exist (or is equal to empty string)

Can somebody tell me how I can go about building such find query?

A: I'm gonna give you some pointers, but you need to try to do this as it's very basic and it's always good to practice.
A basic find in cake is in the form of
$this->ModelName->find('all');

This in its default form does a SELECT * from model_names (convention is to have singular ModelName for plural table name - model_names)
To add conditions:
$this->ModelName->find('all', array('conditions' => array('ModelName.x' => 1));

To add AND conditions
$this->ModelName->find('all', array('conditions' => array(
   'ModelName.x' => 1, 'ModelName.y' => 2
));

To add OR conditions
$this->ModelName->find('all', array('conditions' => array(
   'OR' => array(
      'ModelName.x' => 1, 'ModelName.y' => 2
    )
));

To combine both
$this->ModelName->find('all', array('conditions' => array(
   'ModelName.y is not' => null,
   'OR' => array(
      'ModelName.x' => 1, 'ModelName.y' => 2
    )
));

// where y is not null and (x = 1 or y = 2)

http://book.cakephp.org/1.3/view/1030/Complex-Find-Conditions
(btw I'm sure there will be users giving you the exact answers, so just take my answer for your reference :) )

A: $this->MyModel->find('all', array('conditions' => array(
    'OR' => array(
         array(
             'MyModel.x' => 1,
             'MyModel.y' => 1
         ),
         array(
             'MyModle.x' => 1,
             'OR' => array(
                  array('MyModel.y' => NULL),
                  array('MyModel.y' => '')
             )
         )
    )
)));


text:
Q: Public array to shuffle values between subroutines? How do I get a public array whose values are set within a subroutine and do not get cleared at the end of the sub in which they were set?
I tried to get:
Public GlobalArray() as Variant

Sub One()
    ReDim GlobalArray(0 to 2)
    GlobalArray=Array("0","1","2")
End Sub

Sub Two()
    Check = GlobalArray(2)
End Sub

such that Check = 2, but I get thrown an error in sub Two complaining about a lack of values in GlobalArray (in fact, even sub One complains that there is no GlobalArray to put things in).
Basically, I have a procedure (One) pulling data from disparate sources, doing some stuff with it, letting the user do some things in Excel, and then running a new subroutine (Two) that uses both the user's input and some of the arrays from sub One.

A: The Public GlobalArray() variable must be declared in a module.  It will not work if it is declared at the top of either a Worksheet or the ThisWorkbook module. Try:
'// Must be declared in a module
Public GlobalArray() As Integer

'// These routines can be in worksheet/thisworkbook modules along side events etc Or in a module
Sub One()
    ReDim GlobalArray(0 To 2)
    GlobalArray(0) = 0
    GlobalArray(1) = 1
    GlobalArray(2) = 2
End Sub

Sub Two()
    check = GlobalArray(2)
    MsgBox (check)
End Sub

Instead of a public variable you could pass it to the second function:
Sub One()

    Dim GlobalArray(0 To 2) As Integer
    GlobalArray(0) = 0
    GlobalArray(1) = 1
    GlobalArray(2) = 2

    Two GlobalArrayToMe:=GlobalArray
End Sub

Sub Two(ByRef GlobalArrayToMe() As Integer)

    check = GlobalArrayToMe(2)
    MsgBox (check)

End Sub

A: This is not VBA and won't compile: GlobalArray=("0","1","2")
You could instead use: GlobalArray = Array("0", "1", "2")
but that requires declaring Public GlobalArray() As Variant
Otherwise assign the array elements one by one as in @Readfidy's answer.


text:
Q: Best practices for using Subversion on a development server? I installed VisualSVN on a server that I am using to "stage" web applications that I write - at the present time these applications are Classic ASP/VBScript.  My development workstation that I write code on has TortoiseSVN installed, and I can connect to the repository folder I created - I'm using the following structure:
development (repository)
  -- my_application
     -- branches
     -- tags
     -- trunk
  -- another_application
     -- branches
     -- tags
     -- trunk

I also have IIS configured and pointing to another folder on the server's hard drive to store the served files.  Is there a "best practice" for pushing commits out to the folder linked to IIS, so after a commit/iteration I can give my users a URL to see the demo site (as well as test it myself)?  I am ashamed to say that I have never really used version control before, so I am a little bit clueless as to the best way to use it.

A: First, I would concur with the other comments, your repository format is by the book with branches, tags, and the trunk.  I would also recommend splitting the repository per project as mentioned.  I've been involved in projects that have one shared repository and with split repositories, and the split repositories work better.  Plus, if there was ever a reason to limit access to one of the repositories (ie, you were letting someone else access the repository, and you only wanted them to see one of the two projects) its easier with them separated.
In any case, I would suggest using MSBuild for your deployment. You can create an MSBuild project file that checks out from SVN, builds your solution file, then deploys it to the web site.  You would add a line such as this to your MSBuild project file to do the checkout:

<Exec command="svn checkout %22https://server:8443/svn/Project/Trunk/%22 %22c:\Project%22"/>

You can also do things such as making a project to checkout a specific version/tag once you release a version.  There's quite a bit of flexibility in what can be done when going this route for deployment.
For more details on MSBuild, you can find the Microsoft MSBuild Reference Guide here.

A: I can see you've done your homework, your repository layout is set up by the book.  I'm not sure what VisualSVN does in terms of check-outs, but if you want to push changes to a web site, it's easy to do, either interactively or scheduled.
cd to webhome
svn co [svn-project-uri]

A: First of all, I recommend you to keep different applications in different repositories.
Each commit increases revision number, so you could get next situation: first application has no updates for a long time, but it's revision number continually increases because of a second application updates.


text:
Q: How to upload Cloud files into Python I use to upload excel files into pandas dataframe
pd.ExcelFile if the files are in my local drive
How can I do the same if I have an Excel file in Google Drive or Microsoft One Drive and I want to connect remotely?

A: You can use read_csv() on a StringIO object:
from StringIO import StringIO  # moved to io in python3.

import requests
r = requests.get('Your google drive link')
data = r.content

df = pd.read_csv(StringIO(data))


text:
Q: Regarding joining of threads in an order I am a new bie to the world of threads , still learning, as I was going through the concept of threads and join where other thread wait for earlier thread to be completed and join it from that end, could you please advise me that that I want to start three threads T1,T2,T3 in which t2 will start once T1 is completed .

A: Of what I understand you want to wait until Thread 1 is completely done and then start Thread 2, while thread 3 can run anywhere. Simple code that I think fulfills your question:
Thread thread1 = new Thread1();
Thread thread2 = new Thread2();
Thread thread3 = new Thread3();
thread3.start();
thread1.start();
try {
  thread1.join();
  thread2.start();
} catch (InterruptedException e) {
  //if you do not use thread1.interrupt() this will not happen.
}

A: You can use Barriers to start some action (maybe another thread) after a number of threads finished.
Check: http://programmingexamples.wikidot.com/java-barrier for more information.
But to wait for only one thread really doesn't make to much sense...

A: Do something like this:
        Thread T1 = new Thread(new ThreadExm);  // where ThreadExm implements Runnable
        Thread T2 = new Thread(new ThreadExm);

        try {
            // Start the thread1 and waits for this thread to die before
            // starting the thread2 thread.
            T1.start();
            T2.join();

            // Start thread2 when T1 gets completed
            thread2.start();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }


text:
Q: Setting a className when using Dropdown.item as Link I am using code below to avoid " nested" JS error and keeping Link properties inside a react-bootstrap Dropdown.
<Dropdown.Item className="dropdown-item" as={Link} href={`/example`}>
    Example
</Dropdown.Item>

Result is as follow on the DOM:
Example

Problem is: className="dropdown-item" has been ignored.
How could I get this result: Example while keeping the code "react-friendly"?

A: you can use bsPrefix to override the bootstrap styling ...
Docs reference ...

A sample e.g. here in below link - see dropdown first item's bg color... Please fork it for reference

A: You can try to wrap it around.
<Link to={`/example`}><Dropdown.Item className="dropdown-item">
    Example
</Dropdown.Item></Link>


text:
Q: Functions are specific kind of sets I am just interested in really pining down the idea of functions. Given two sets X and Y together with function $f : X \rightarrow Y$ connecting X and Y. Is a function just the set that is realized through axiom of specification, i.e are we just looking at the following set ?
$$\{y \in Y : P(x,y) \ is \ true \ for \ x \in X \}$$

A: There are essentially two ways to look at functions, as either mappings from $X$ to $Y$ as a relation $\ R \subset X \times Y$ that satisfies the constraint that if $(x,y) \in R$ and $(x,y') \in R$ then $y=y'$. If you graph a few functions you can convince yourself this is just the vertical line test as suggested in the article. I recommend small, finite sets to see what's happening. You can also draw a directed graph with vertices given by the disjoint union of $X$ and $Y$ with an edge given by $(x,y)$ to see how the mapping explicitly with arrows to reconcile the two notions of a function.


text:
Q: select the front camera I'm using the following code to take a picture:
private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            //...
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

Is there any way to select the front camera?

A: You can try this.
takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 1);

But not all camera apps supports that flag

A: You can use Camera.CameraInfo.CAMERA_FACING_FRONT
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
    Camera.getCameraInfo(camIdx, cameraInfo);
    if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        try {
            cam = Camera.open(camIdx);
        } catch (RuntimeException e) {
            Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
        }
    }
}

and add permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false"/>


text:
Q: Plastic SCM Sync View Connection Refused
I'm trying to replicate a unity3d repo from Plastic SCM Cloud into my NAS Drive which is mapped at V:
The above error is what I get when I add my cloud repo as SRC and my local as DST so I can replicate it locally.
I have tried searching the plastic SCM forums for a solution but to no avail.
I am connected to the company intranet on a laptop that is not joined to a domain. The above error shows this is happening on local host so i'm assuming this is not related to the IT department blocking ports (they're using a PFSense firewall).
I expect to replicate my repos through the sync view for a couple of repos that we have; as it will be the start of a process of removing the repos from the cloud to our local server.

A: A cloud server cannot be set as the source, it always has to be the local one.
Try to set the sync backwards: local as source and cloud as destination.


text:
Q: New Silverlight app. MVVM. RIA Services vs CSLA Another 2 days of reading and watching demos and here we go.
For my enterprise LoB Silverlight app I'm going to use:

*

*Prism for UI aspects and modularity.

*MVVM pattern (using Prism)

*??? to bring data over and validations...

*Entity Framework for Data access

*SQL Server for data

Ok, main dilemma is #3. If I won't use any framework then I will have to figure out how to do all CRUD stuff myself. I can do RESTful WCF, I can do SOAP. All that == MANUAL coding.
I can do RIA Services. I kind of see what it does and it is nice for direct match with my data layer BUT it is not that great if there will be lot of business logic. Where would I put it? In my ViewModel? Another question is how those services maintained. Once I generated it - I should maintain them by hand if data changes?
I also found CSLA which seems to be nice on one hand but receives lot's of critique.. CSLA will allow me to write business logic and shape object as I needed and than I can pass it "through" ViewModel and all is well.
Something tells me that RIA Services will be much quicker to write. Also, I like the fact that I don't have to include extra dependencies.
There is no blogs or mentioning of RIA Services since 2010. Is it going under table? Not widely accepted? Not scaling well for big apps?
I'm trying to decide which one I need to bet on. CSLA or RIA Services. OR?

A: I am working on a WPF and Silverlight (two separate clients) project that makes heavy use of the CSLA.NET Framework. We've had very little trouble from the CSLA.NET Framework which is mature, very well tested, has excellent support from Rocky and the community, and provides solutions to a lot of the problems one has developing modern .NET applications (data-binding, data-access, validation, authentication, to name just a few).
The CSLA.NET is not perfect, perhaps in that it doesn't fit perfectly into the message bus type architectures; but if your goal is a line-of-business application sat on top a database, then CSLA.NET is a sensible choice. Perhaps another issue is the learning curve but the educational material is comprehensive and well written.

A: I have recently been working on some line-of-business Silverlight projects.  For one we used straight WCF and did all the CRUD, state tracking, entity relationship, etc. ourselves.  For the second project we are using RIA Services and had it manage all of that stuff for us.
However, we did NOT have RIA Services directly generate services based on our ORM model.  We had a layer of interfaces and "dumb objects" in between.  So we had a distinct data tier, business logic tier, and service tier.  RIA Services was only involved at the service tier.
If you are going to use RIA Services, I recommend limiting how much of the layers of your application you let it influence.  It does force you down certain paths as far as design is concerned, so the more you contain it the more flexibility you will have.  This advice is probably sound for CSLA as well.  If you are going to "bet" on a particular framework, hedge your bet as much as possible.
In summary, RIA Services will definitely save you time, but it does limit your flexibility a bit compared with raw WCF.  And it has some kinks and weaker areas that still need improvement.
I haven't worked with CSLA, but I have seen Rocky Lhotka give talks on it several times so I know the basics.  It seems like a solid framework.  However, the main disadvantage it will have compared with RIA Services is that it isn't directly from Microsoft, so CSLA won't mesh as cohesively with other MS stuff as much as RIA Services will.  Also, in the long run I'm guessing it will be easier to find people that know RIA Services versus people that know CSLA.
If it helps, I gave a talk on RIA Services you can find the presentation and some sample code on my blog.
http://rationalgeek.com/blog/post/WCF-RIA-Services-Silverlight-Guild.aspx

A: We're about 1.5 years into a 3 year project using CSLA, Prism, TSQL and Silverlight. Given the chance, I'd toss CSLA out as quickly as possible. One of the biggest problems I have with CSLA is that it tries to do everything. If you watch Rich Hikey's talk on Simple vs Easy (http://www.infoq.com/presentations/Simple-Made-Easy) you'll notice he talks about "complecting" things. That is, entangling code so that a single object is responsible for more than one thing.
CSLA violates this principle (and that of SOLID) left, right, and center. You basically end up with a situation where your business rules are in your data transfer objects. You end up using the same object that you populated with DB data (either directly from EF or via DTOs), and that same exact object ends up on the client being bound to the UI. Or you can wrap them in View Models, if you wish, but that just adds more and more complexity.
On top of that you're locking your client software into a .NET language. If in the future you want to provide service feeds or simply access your data from JS and HTML, you're suddenly forced to wrap hundreds of lines of code to present to these different platforms.
Keep it simple...have your web server spit out JSON...have you client and servers completely de-coupled (share code files if desired, but don't couple them). The simpler your code is, the easier it will be to fix bugs, understand what's going on, and keep everything under control


text:
Q: How come website be random slow? Open sleep processes? My website is randomly very slow by high MYSQL CPU, and I have no idea what the problem is. Hopefully I will come closer to the solution with this post.
If I check the mysql processes, I see a lot of open sleep commands when the website is slow. When there are none open sleep commands, there is no problem. So probably the problem lies there.

Curiously, this problem only happens sometimes. Sometimes I have no problems for 4 weeks, now the website is already 3 days in a row slow.
I already set the time_out mysql settings to 30 secs, but that does not help to solve the problem. So now I try to figure out what the problem is. Here are the alert status variables. Perhaps that gives some extra insights.

Could it be spambots/brute-force attacks?
Heavy/slow query's in the website?
Bad server settings?
Sql injections?
Other things that this problem can cause? What is the best way to tackle this problem now? Sending any direction will already help.


text:
Q: How to implement nested loop using map in react Js I know that there is a lot of thread that already answer about this nested loop using map in react js problem, but I'am quite confused as how can I implemented it in my code. I tried several time but got an an error,
this is some topic that I tried, but I can't seem to implement it:

*

*react-create-nested-components-with-loops

*how-to-have-nested-loops-with-map-in-jsx

*react-map-over-nested-array-of-objects
this is my Json that I want to get:
"costs": [
          {
            "service": "CTC",
            "description": "JNE City Courier",
            "cost": [
              {
                "value": 234000,
                "etd": "1-2",
                "note": ""
              }
            ]
          },
          {
            "service": "CTCYES",
            "description": "JNE City Courier",
            "cost": [
              {
                "value": 468000,
                "etd": "1-1",
                "note": ""
              }
            ]
          }
        ]

What I want is to get the value from this JSON example, but still no luck
this is my component that I want to loop:
<MDBDropdown className="select-type">
 <MDBDropdownToggle caret className="select-btn">
  Choose Your Courier Service
 </MDBDropdownToggle>
 <MDBDropdownMenu basic onClick={this.serviceData}>
  {shipmentFees != null ? shipmentFees.map(
    shipmentFee => (
     <MDBDropdownItem key={shipmentFee.cost.service} name={shipmentFee.cost.description + "," + shipmentFee.cost.etd} value={shipmentFee.cost.value}>
      {shipmentFee.cost.description}, {shipmentFee.cost.etd} Days
     </MDBDropdownItem>
    )
   )
  :
    <MDBDropdownItem value="-">There is no service</MDBDropdownItem>
  }
 </MDBDropdownMenu>
</MDBDropdown>

from reference number 3, I tried this solution but I got unexpected token, expected ","
<MDBDropdown className="select-type">
 <MDBDropdownToggle caret className="select-btn">
  Choose Your Courier Service
 </MDBDropdownToggle>
 <MDBDropdownMenu basic onClick={this.serviceData}>
  {shipmentFees != null ? shipmentFees.map(
   shipmentFee => (
    {
     shipmentFee.cost.map(
      cost => (
       <MDBDropdownItem key={cost.service} name={cost.description + "," + cost.etd} value={cost.value}>
        {cost.description}, {cost.etd} Days
       </MDBDropdownItem>
      )
     )}
    )
   )
   :
   <MDBDropdownItem value="-">There is no service</MDBDropdownItem>
  }
 </MDBDropdownMenu>
</MDBDropdown>

can someone help me to solve this?

A: I just follow your 2nd block of code
1) I think your shipmentFee.cost.map( should be shipmentFee.costs.map(
2) Next line cost => (   here    cost will give you service, description and cost[]
3) cost[] as it is an array you have to do another map/loop to extract value, etd and note. this value is your expected value I think


text:
Q: xcode 4.2.1 - custom keyboard - two UITextFields I have created a custom keyboard and I have two text fields.
I am calling [firstTextField becomeFirstResponder] in my viewDidLoad
to have my keyboard visible.
How can I know which text field is currently active so that I write what the user is typing from the keyboard to the respected textField?
I have tried - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField but it is not being called
any idea?

A: To get textFieldShouldBeginEditing to be called, you need to set the delegate outlets for both your text fields to whatever view controller (or wherever) the textFieldShouldBeginEditing method lives in.
You can set the delegates programmatically (e.g. firstTextField.delegate = self;) or via the XIB file.
And your intuition is correct, once textFieldShouldBeginEditing gets called, you will know (from the textField parameter) which field the user is currently typing in.

A: You should be able to use isFirstResponder to determine which of your two UITextFields is currently active.
if ([firstTextField isFirstResponder]) {
    ...
}
else {
    ...
}


text:
Q: How to handle Click event or any other Event in GWT Cloud? I am using tagcloud_0.4.jar for using Tag Cloud in GWT. Now, when I click on any tag inside the tag cloud, then how can I handle that event or how can I do RPC call when user select any tag from cloud?
Thanks.

A: Here is an example to catch a ClickEvent on the cloud. But this is a workaround as the library may change. As the developper do not offer to manage events on the cloud neither on tags, this is perhaps for a good reason...
So use this code at your own risk. Pray for no change of the widget's structure DOM. I suggest you to ask the developper some enhancements on its widgets, like managing such events.
    final TagCloud cloud = new TagCloud();

    cloud.addWord(new WordTag("AAA"));
    cloud.addWord(new WordTag("AAA"));
    cloud.addWord(new WordTag("BBB"));
    cloud.addWord(new WordTag("CCC"));
    cloud.addWord(new WordTag("CCC"));
    cloud.addWord(new WordTag("CCC"));

    cloud.addDomHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            // Prevent the click from the tag to be executed
            event.preventDefault();

            Element e;
            // For each tag present in the cloud, look for the one that is triggered
            for (int i = 0; i < cloud.getTags().size(); ++i) {
                // Gets the element in the cloud, this really is the unsafe part of the code
                // if the developer change the dom of its widget
                e = DOM.getChild(DOM.getChild(cloud.getElement(), 0), i);
                // Is the current element targeted by the event?
                if (event.getClientX() >= e.getOffsetLeft() && event.getClientY() >= e.getOffsetTop()
                        && event.getClientX() <= e.getOffsetLeft() + e.getOffsetWidth()
                        && event.getClientY() <= e.getOffsetTop() + e.getOffsetHeight()) {
                    // Gets the abstract tag
                    Tag t = cloud.getTags().get(i);
                    // Gets tag descendant
                    if (t instanceof WordTag) {
                        // Do what you want with your WordTag, maybe an RPC call
                    } else if (t instanceof ImageTag) {
                        // Do what you want with your ImageTag, maybe an RPC call
                    }

                    break;
                }
            }
        }
    }, ClickEvent.getType());


text:
Q: R set default origin for as.Date Is there a way to set default origin for as.Date?
I did this function to workaround:
as.date=function(x, origin='1970-01-01') as.Date(x, origin=origin)

For example:
as.Date(0)
Error in as.Date.numeric(0) : 'origin' deve ser especificado

as.date(0)
[1] "1970-01-01"

A: There is an elegant and simple solution, like zoo, but allows for some tweaking if you need it:
require(anytime)
The base is simply:
anytime(0)
which returns for me in eastern standard time:[1] "1969-12-31 19:00:00 EST"
If you want to be able to force it to the UTC center of the temporal universe
anytime(0, asUTC=TRUE)
which returns
[1] "1970-01-01 UTC"
And if you want to tell R that you your data is from a given time zone :
Sys.setenv(TZ= 'desiredTimeZone') with anytime:::getTZ() as your desired time zone if that is the one, in which, your dates were gathered.
Any of the answers will work, this one just gives you control over the integer (or string) of numerals as well as the time zone...so it is pretty universally useful if you are working with data gathered remotely.

A: Not really. There is no way the origin date can be changed and remain applicable forever in a session.
If you look at parameters for as.Date (i.e.  function then origin does not has a default value when x is in numeric.
## S3 method for class 'numeric'
as.Date(x, origin, ...)

Perhaps, it would have been a good extension to as.Date function to provide default value for origin.
OP has done write thing to create a wrapper function to remove dependency on origin. Perhaps the function can be improved slightly like:
Modified function based on suggestions from suggestions from @sm1 and @Gregor.
## if date.origin is not defined then origin will be taken as "1970-01-01
options(date.origin = "1970-01-01")
as.date <- function(x, origin = getOption("date.origin")){
  origin <- ifelse(is.null(origin), "1970-01-01", origin)
  as.Date(x, origin)
}

## Results: (When date.origin is not set)
## > as.date(0)
## [1] "1970-01-01"
## > as.date(2)
## [1] "1970-01-03"
## Results: (When date.origin is set)
## > options(date.origin = "1970-01-05")
## > as.date(2)
## [1] "1970-01-07"

A: The lubridate package has been specically made the work with dates easier :
library(lubridate)
as_date(0)
#[1] "1970-01-01"

A: The zoo package adds a default origin:
library(zoo)

as.Date(0)
## [1] "1970-01-01"

Update
This is several years later but it looks like R has added .Date so we can now do this using only base R.
.Date(0)
## [1] "1970-01-01"


text:
Q: my c# windows form application and azure i have an azure database and its connected to my c# application, i used App.config to create the connection string. when i run my program it becomes very slow, but when i connect to a local sql server its very fast. How do i make my azure connection on my application fast?
My App.Config
<?xml version="1.0"?>
<configuration>
  <configSections>
  </configSections>
    <connectionStrings>
  <clear />
  <add name="fudz" connectionString="Data Source=[my server];Initial Catalog=[databasename];Persist Security Info=True;User ID=[my user name];Password=[my password];Encrypt=true;TrustServerCertificate=False;Connection Timeout=30;"/>
</connectionStrings>
<startup useLegacyV2RuntimeActivationPolicy="true"><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/></startup></configuration>

A: It is likely to be a the network latency between your machine and Azure database. You can use certain network tools like ping, tracert, etc to see the network latency. You can then look at increasing your network connection speed (usually, via your ISP).
You can also select the Azure hosting that is closest to your location in which you are running your application
Azure locations - https://azure.microsoft.com/en-us/regions/?cdn=disable


text:
Q: Collect selected value text from a dropdown box that doesn't change anything on the element upon click I open this page with selenium webdrive Firefox.
Here there is a dropdown box:

  <select name="competition_id">

      <option value="89" selected="selected">Serie B - 2023</option>

      <option value="239">Paulista A1 - 2023</option>

      <option value="231">Copa do Brasil - 2023</option>

  </select>

That when selecting another option, the visual text changes, but nothing in the element changes, including it keeps saying that the first option is selected:

  <select name="competition_id">

      <option value="89" selected="selected">Serie B - 2023</option>

      <option value="239">Paulista A1 - 2023</option>

      <option value="231">Copa do Brasil - 2023</option>

  </select>

How can I get the new value of the box after selecting it while the element remains unchanged?
I tested several shapes with the webdriver and with Beautifulsoup, but none delivered correctly, including getting the text without setting any other details:
soup = BeautifulSoup(driver.page_source, 'html.parser')
season_opt = soup.select('table.section-dropdowns select[name="competition_id"]')[0]
season = season_opt.text.strip()

A: The method is_selected() returns true if an element is selected, false otherwise. Following code loops through all the values, select the corresponding option and prints the selected option.
from selenium.webdriver.support.ui import Select
dropdown = driver.find_element(By.XPATH, "//select[@name='competition_id']")
options = dropdown.find_elements(By.XPATH, './option')
for value in ['89','239','231']:
    Select(dropdown).select_by_value(value)
    print( [o.text for o in options if o.is_selected()] )

output
['Serie B - 2023']
['Paulista A1 - 2023']
['Copa do Brasil - 2023']