text:
Q: Find package for extension method? I have two solutions. Both call extension method "AddDbContext" on an object of type IServiceCollection. Both solutions are .NET 5.
It works fine in one project, but the other project doesn't know about the extension method. Is there an easy way to determine which Nuget package I need to install? Short of Googling (which I can do), is there a simple way in Visual Studio to determine which package contains the extension method?
In the working solution I right click on the call to "AddDbContext" and go to definition. It's in namespace "Microsoft.Extensions.DependencyInjection" in file EntityFrameworkServiceCollectionExtensions.cs. Both solutions have package Microsoft.Extensions.DependencyInjection version 5.0.2 installed on the only project.
The solutions don't have all the same packages installed, but from their names I can't decipher which package installed might be adding IServiceCollection.AddDbContext.
I can Google this, of course, I just wonder if there is some menu in Visual Studio which can just tell me which package contains the extension method?
In this particular case, installing package Microsoft.EntityFrameworkCore v5.0.10 fixed the issue. But why was that package needed, and how could I have determined that using Visual Studio?

A: If you choose "Peek definition" instead of "Go to definition", then you see the full path of the assembly inside the region at the top of the definition. In the path you see what package it is from.
Some decompiler extensions (such as ILSpy or dotPeek) might also show it in the "Go to definition" view.


text:
Q: What is a good algorithm for Second Order Polynomial Curve Fit without Cramer's Rule? I'm writing some code in C++ to extract a 2nd Order Polynomial Curve out of a set of data to remove non-periodic elements from it before performing signal analysis. My strategy for generating the curve was to use Least Sum Squares using Cramer's Rule, where the coefficients of the polynomial, $a_k$, is
$$a_k=\frac{det(M_k)}{det(M)},$$
$$M=\begin{matrix}
N & \sum^N_{i=1}x_i & \sum^N_{i=1}x^2_i \\
\sum^N_{i=1}x_i & \sum^N_{i=1}x^2_i & \sum^N_{i=1}x^3_i \\
\sum^N_{i=1}x^2_i & \sum^N_{i=1}x^3_i & \sum^N_{i=1}x^4_i \\
\end{matrix}$$
where $N=$ number of samples taken,
$x_i=$ independent variable value at sample $i\in [1,...N]$, and $M_i=$ the matrix $M$ with the $k$th column (for $k\in[1,2,3]$) replaced by
$$b=\begin{matrix}
\sum^N_{i=1}y_i \\
\sum^N_{i=1}x_iy_i \\
\sum^N_{i=1}x^2_iy_i
\end{matrix}$$
For example,
$$M_1=\begin{matrix}
\sum^N_{i=1}y_i & \sum^N_{i=1}x_i & \sum^N_{i=1}x^2_i \\
\sum^N_{i=1}x_iy_i & \sum^N_{i=1}x^2_i & \sum^N_{i=1}x^3_i \\
\sum^N_{i=1}x^2_iy_i & \sum^N_{i=1}x^3_i & \sum^N_{i=1}x^4_i
\end{matrix}$$
This works to generate the coefficients of the 2nd order polynomial function that fits the set of data $$y=a_2x^2+a_1x+a_0$$
Working with the data set that I have, I am capable of making the assumption that the time change between samples is constant across all the samples; therefore, I am handing the summation of $x$ independent variables as simply the summation of integer values up to the Sample $i$ in question (for simplicity sake. I'd rather only have to handle a collection of dependent variable values rather than that and maintaining the independent variables as well).
The problem is I have sample sizes upwards of 400 samples per data set, and performing some of the summations using this (such as $\sum^{400}_{i=1}x^4_i$) causes... well, let's just say that the memory required for that calculation is not available for use. Positive numbers turn to negative numbers, cats sleep with dogs, etc.
So, my question is: is there a more efficient algorithm for finding $a_k$ coefficients that would not be as taxing on memory requirements?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove focus from a Tk() element in tkinter? In Python 3, can you prevent focus from a root-level Tk() element when clicked?
After unfocusing, focus must be returned to the previous window that had focus.

A: Here is an example of how to switch focus between two tkinter windows:
from tkinter import Tk, Button

first = Tk ()
second = Tk ()

first.title ('First Window')
b1 = Button (first, text = 'Goto Second Window')
b1.config (command = second.focus_force)
b1.pack ()

second.title ('Second Window')
b2 = Button (second, text = 'Goto First Window')
b2.config (command = first.focus_force)
b2.pack ()

first.mainloop ()


text:
Q: Recurrence of walks with growing range of step Let $f:\Bbb{N}\to\Bbb{N}$ be a function where $f(n)\to\infty$ as $n\to \infty$.
Given $f$, we can define a random walk on $\Bbb{Z}$, $Y(f,1)=Y_0,Y_1,\dots$, where $Y_0=0$, and $Y_{n+1}-Y_n=X_n$, where $X_n$ is chosen uniformly at random from $[-f(n),f(n)]\cap\Bbb{Z}$ and independent of the outcomes of all other $X_i$.
Similarly, given $f$, we can define a random walk on $\Bbb{Z}^2$, $Y(f,2)=Y_0,Y_1,\dots$, where $Y_0=(0,0)$, and $Y_{n+1}-Y_n=X_n'$, with $X_n': = X_n\cdot v_n$, where $v_n$ uniformly samples the two vectors $(0,1),(1,0)$, and $X_n$ is distributed as before. (here, we should have the set of random variables $\{v_i: i\in \Bbb{N}\}\cup\{X_i: i\in \Bbb{N}\}$ be independent)
I believe that if $f$ "does not grow too fast", then the walks $Y(f,1)$ and $Y(f,2)$ will be recurrent. In particular, I believe it would be sufficient for $\sum_{n=1} 1/f(n)^2$ to diverge. I am interested in proofs or disproofs for either case, as well as any techniques/gadgets which are useful for analyzing these kinds of walks.
Here is a sketch of the first case which a grad student showed me, I don't fully understand it yet:

*

*Let $f(n) = \sqrt{n}, Y_n = Y(f,1),$ with $X_n$ defined as above.

*We have that $\textrm{Var}(X_n) = O(n),\textrm{Var}(Y_n) = \sigma_n^2 = O(n^2), \sigma_n = O(n)$.

*Thus, as the standard deviation of $Y_n, \sigma_n$ is $O(n)$, almost surely, the long-run proportion of time where $|Y_n- 0|\le \sqrt{n+1}$ is $\Omega(1/\sqrt{n})$. (i.e. Let $\chi_n$ be the characteristic function that is one if $|Y_n-0|\le\sqrt{n+1}$ is true and zero otherwise. Let $V_n:= \sum_{i=0}^{n-1}\chi_i$. We have that there exists some absolute $C>0$ such that $\Bbb{P}\left(\lim_{n\to\infty} \frac{V_n}{n} > \frac{C}{\sqrt{n}}\right) =1$)

*It follows that almost surely, the long-run proportion of the time where $Y_{n+1} = 0$ is $\Omega(1/n)$, as $\Bbb{P}(Y_{n+1} = 0|\chi_n = 1) = \frac{1}{2\lfloor\sqrt{n+1}\rfloor+1}$.

*Through the same argument, replacing 0 with any $m\in \Bbb{Z}$, we have that almost surely, the long-run proportion of times where $Y_{n+1} = m$ is $\Omega(1/n)$. (alternatively, since $\Bbb{P}(Y_{n+1} = m| \chi_n=1, \textrm{sign}(Y_n)=\textrm{sign}(m),\sqrt{n+1}\ge m) = \frac{1}{2\lfloor\sqrt{n+1}\rfloor}$ so since the sign of $Y_n$ given $\chi_n$ should not be biased, and for all large $n$ we have $\sqrt{n+1}\ge m$ holds, the long-run proportion of times where $|Y_{n+1} = m|$ should also be $\Omega(1/n)$ almost surely)

*As the are countably many integers, and the intersection of countably many events that occur with probability 1 still occurs with probability 1, we have that almost surely for each integer $m$, the long-run proportion of times where $Y_{n+1} =m$ is $\Omega(1/n)$, implying each integer will be visited infinitely often.

For the most part, this makes sense, but I would appreciate some clarification on Step 3. I would assume that step 3 is "morally" supposed to follow from Chebyshev's inequality. However, formally I don't know how to justify this for our walk. A sketch explaining what conditions (independence and perhaps other stuff) allow us to prove step 3 would be much appreciated. Any commentary about what the most sound/clear way to justify step 5 is also welcome!
Update: the grad student further clarified that Step 3 should follow by Hoeffding's Inequality.

A: Let $G(n)=\sum_{k=1}^n f(k)^2$.
CLAIM: $Y(f,1)$ is recurrent iff
$\sum_n G(n)^{-1/2}=\infty$.
In particular, $f(n)=n^{1/2}\log(n)^\alpha$ yields recurrence of $Y(f,1) $ iff $\alpha \le 1$. (Note that for $\alpha>1/2$ the sum $\sum_n f(n)^{-2} $ converges.)
Proof sketch of CLAIM:
Let $\varphi_n(t)=E(e^{itXn})$ and $\psi_n(t)=E(e^{itY_n})=\prod_{k=1}^n \varphi_k(t)$.
Taylor expansion shows that $\phi_k(t)$ behaves like $e^{-cf(k)^2 t^2}$ near the origin, where $c$ is a constant. Since $\int_{-\infty}^\infty  e^{-a t^2}= (\pi/a)^{1/2}$, it follows that
$$P(Y_n=0)=\int_{-\infty}^\infty \psi_n(t)=\Theta(G(n)^{-1/2}) \,.$$
See [1] for a lovely account of such calculations. To conclude that $Y_n$ visits zero infinitely often iff the sum in the claim diverges, use the Kochen-Stone lemma [2].

For $Y(f,2)$ to be recurrent, $f$ has to grow much more slowly: $Y(f,2)$ is recurrent iff
$\sum_n G(n)^{-1}=\infty$. In particular, $f(n)=\log(n)^\beta$ yields recurrence of $Y(f,2)$  iff $\beta \le 1/2$. This can be verified by the same method.
For other methods to tackle related problems see [3].
[1] Kac, Mark. Statistical Independence in Probability, Analysis and Number Theory. Courier Dover Publications, 2018.
[2] https://projecteuclid.org/euclid.ijm/1256059668
[3] Benjamini, Itai, Robin Pemantle, and Yuval Peres. "Random walks in varying dimensions." Journal of Theoretical Probability 9, no. 1 (1996): 231-244.


text:
Q: Configuring a custom scrollbar in PyQt I am building a GUI for image processing in PyQt. One task that I need to be able to do is use a scrollbar to move through a directory of image files. Specifically, if there are 1000 images, say, in /my/dir, then I would like the distance scrolled along a scrollbar to correspond to the image number (between 1 and 1000). So the scrollbar all the way at the left would be image = 1, the scrollbar all the way at the right would be image = 1000, and if the scroll bar is 33% of the way from left to right, then the image displayed has the numeric value round(0.33333*1000) = 333.
Right now I have a working set of widgets that will draw an image from a directory, and then has 'Next' and 'Previous' buttons which you can use to navigate forward and backward. The point of this software is to allow for supervised learning via deep human annotations, so there is a need to rapidly scroll through large amounts of images in which no meaningful changes happen. That's why I need the slider bar.
If the whole slot/signal stuff works the same for scrollbars as it does for buttons, I am sure I can hack my way through that stuff to get it to manipulate the pixmap image name and update the displayed image. What help I need though is some basic syntax explaining how to create a scrollbar class, and place it beneath my pixmap on a QGridLayout frame.

An answer I found through surfing and tinkering is below.
I found another solution which interfaces well, although I like @Stephen Terry's suggestion to actually iterate over the files themselves. My solution is based off of tutorial code found here: http://zetcode.com/tutorials/pyqt4/widgets/
I modified this by first creating a small class of my own:
class InterpolatingScrollBar(QtGui.QWidget):

    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.testbar = QtGui.QSlider(QtCore.Qt.Horizontal,self)
        self.testbar.setGeometry(10,10,500,30)
        self.testbar.setFocusPolicy(QtCore.Qt.NoFocus)

and then creating an instance of this class in the main controller class,
    self.scrollbar = buttonUtils.InterpolatingScrollBar()
    self.scrollbar.testbar.setMinimum(self.overall_counter)
    self.scrollbar.testbar.setMaximum(self.max_image_num)

where max_image_num is computed by doing a similar call to glob() and checking for which are jpgs in the directory. Then I use this code to connect to the 'value changed' signal of the scrollbar:
    self.connect(self.scrollbar.testbar,QtCore.SIGNAL('valueChanged(int)'),self.getScrollValue)

def getScrollValue(self,value):
        self.overall_counter = value
        self.pb1.previousSlot(self.overall_counter)
        self.nb1.nextSlot(self.overall_counter)
        self.pixmap = QtGui.QPixmap(self.directory_name + self.pb1.new_image_str)
        self.label.setPixmap(self.pixmap)

where pb1 and nb1 are 'previous button' and 'next button', with corresponding functions that update counters displayed on those buttons, as well as the string name leading to the new image to be displayed.

A: The simplest way would be to use a QListWidget and populate it with your images as the icons of a QListWidgetItem.  An example would be something like this
self.list_widget = QListWidget()
files = glob.glob('YourDirectory/*.jpg') #Get all jpegs in your directory
for i in files:
    self.list_widget.addItem(QListWidgetItem(QIcon(i),'your text here'))
self.list_widget.setIconSize(QSize(400,300)) #Set your image size

That will give you close to the scrollbar behavior you want; the user will be able to see more than one image at a time unless you make the images large enough to fill the screen.  Hopefully you can tweak it to meet your needs.


text:
Q: Trouble-shooting with AngularJS in NPM start I've been receiving this error  NPM install and NPM start while trying to start an AngularJS app
I've tried
     npm install
and  npm start
( I've tried the above commands with sudo as well)
...
after executing the commands, I receive this error:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/nodejs', '/usr/bin/npm', 'start' ]
2 info using npm@1.2.18
3 info using node@v0.10.15
4 verbose read json /home/raheela/angular-phonecat/package.json
5 verbose run-script [ 'prestart', 'start', 'poststart' ]
6 info prestart angular-phonecat@0.0.0
7 verbose unsafe-perm in lifecycle true
8 silly exec sh "-c" "npm install"
9 silly sh,-c,npm install,/home/raheela/angular-phonecat spawning
10 info angular-phonecat@0.0.0 Failed to exec prestart script
11 error angular-phonecat@0.0.0 prestart: `npm install`
11 error `sh "-c" "npm install"` failed with 1
12 error Failed at the angular-phonecat@0.0.0 prestart script.
12 error This is most likely a problem with the angular-phonecat package,
12 error not with npm itself.
12 error Tell the author that this fails on your system:
12 error     npm install
12 error You can get their info via:
12 error     npm owner ls angular-phonecat
12 error There is likely additional logging output above.
13 error System Linux 3.8.11
14 error command "/usr/bin/nodejs" "/usr/bin/npm" "start"
15 error cwd /home/raheela/angular-phonecat
16 error node -v v0.10.15
17 error npm -v 1.2.18e
18 error code ELIFECYCLE
19 verbose exit [ 1, true ]

Thank you!
edit:  additional info
> angular-phonecat@0.0.0 prestart /home/raheela/angular-phonecat
> npm install

npm WARN cannot run in wd angular-phonecat@0.0.0 bower install (wd=/home/raheela/angular-phonecat)

> angular-phonecat@0.0.0 start /home/raheela/angular-phonecat
> http-server -p 8000

/usr/bin/env: node: No such file or directory
npm ERR! angular-phonecat@0.0.0 start: `http-server -p 8000`
npm ERR! `sh "-c" "http-server -p 8000"` failed with 127
npm ERR!
npm ERR! Failed at the angular-phonecat@0.0.0 start script.
npm ERR! This is most likely a problem with the angular-phonecat package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     http-server -p 8000
npm ERR! You can get their info via:
npm ERR!     npm owner ls angular-phonecat
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 3.8.11
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "start"
npm ERR! cwd /home/raheela/angular-phonecat
npm ERR! node -v v0.10.15
npm ERR! npm -v 1.2.18
npm ERR! code ELIFECYCLE
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR!
npm ERR! Additional logging details can be found in:
    npm ERR!     /home/raheela/angular-phonecat/npm-debug.log
    npm ERR! not ok code 0

A: I solved this with
sudo apt-get install nodejs-legacy


text:
Q: Como puedo integrar Pygame y PyQt4? Estoy usando Python 2.7 y Ubuntu 14.04.
Me encuentro intentando hacer esto para poder insertar mi ventana pygame en mi ventana PyQt4.

En algunas plataformas es posible incrustar el display de pygame en una ventana existente. Para hacerlo la variable de entorno SDL_WINDOWID debe contener un string con el id de la ventana destino. Esta variable es chequeada cuando el display de pygame es inicializado.

Este es mi codigo:
from PyQt4 import QtGui, QtCore
import os
import subprocess
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
    MainWindow.setWindowModality(QtCore.Qt.ApplicationModal)
    MainWindow.setFixedSize(800, 600)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)
    self.iniMap()

def iniMap(self):
    command = "xprop -root _NET_ACTIVE_WINDOW"
    output = subprocess.Popen(["/bin/bash", "-c", command], stdout=subprocess.PIPE)
    activeWindowID = str(output.communicate()[0].decode("utf-8").strip().split()[-1])
    os.environ['SDL_WINDOWID'] = activeWindowID
    import pygame
    pygame.init()
    screen = pygame.display.set_mode((565, 437), pygame.NOFRAME)

class frmMain(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(frmMain, self).__init__(parent, flags=QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setupUi(self)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    form = frmMain()
    form.show()
    sys.exit(app.exec_())

Pero esto no funciona, solo muestra mi ventana PyQt. No se si lo que estoy haciendo esta mal, o si directamente pygame no puede ser integrado con PyQt.
¿Qué debería hacer para poder incrustar mi pygame en frmMain?
Muchas gracias.

A: Me encontré con algo parecido y lo solucioné con:
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)

Antes del pygame.init, juega dando valores a x e y para ajustar a tu ventana.
No es elegante pero funciona :)


text:
Q: C# -> Entity Framework 6.1.3 -> Composite nullable foreign key string I'm integrating against an external system where they use a lot of composite keys and often strings. I'm now facing a problem where I need to make a composite foreign key nullable. If the value would be an int i could just mark it as nullable with int? but this is not possible here. I think I have to use fluent api but if it is possible with data annotations that is the preferred way. To make it even harder the first part of the foreign key is also used as the first part for the primary key and thus can not be nullable.
BillCurrency and DisbCurrency for FeeCalculation are the keys that needs to be nullable below. The models created are valid apart from the nullable part.
The obvious exception message:

The INSERT statement conflicted with the FOREIGN KEY constraint
  "FK_dbo.FeeCalculations_dbo.ExchangeRates_BusinessSystemId_BillCurrency". The conflict occurred in database "Project.Database", table
  "dbo.ExchangeRates". The statement has been terminated.

public class FeeCalculation
{
    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string BusinessSystemId { get; set; }

    [Key, Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CaseId { get; set; }

    public string BillCurrency { get; set; }

    [ForeignKey("BusinessSystemId,BillCurrency")]
    public virtual ExchangeRate BillCurrencyObject { get; set; }

    public string DisbCurrency { get; set; }

    [ForeignKey("BusinessSystemId,DisbCurrency")]
    public virtual ExchangeRate DisbCurrencyObject { get; set; }

}

public class ExchangeRate
{
    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string BusinessSystemId { get; set; }

    [Key, Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string ForeignCurrency { get; set; }

    public string HomeCurrency { get; set; }

    public DateTime EffectiveDate { get; set; }

    public double Rate { get; set; }
}

A: Turned out it was nothing wrong with the models, it was a FeeCalculation value that was corrupt and tried to insert a key that did not exist in ExchangeRate.


text:
Q: Every line parallel to $l$ to another line parallel to $l$
Let $T$ be a linear operator on $\mathbb{R}^2$. Prove that if $T$ carries a line $l$ to $l$, then it also carries every line parallel to $l$ to another line parallel to $l$.

I got stuck since a line is not a vector subspace if it does not contain $(0,0)$. Is their anything I am doing wrong? Please help.

A: Write the $\ell$ line in $\mathbb{R}^2$ as $\vec{p}+t\vec{v}$, where $t\in \mathbb{R}$ and $\vec{p},\vec{v}\in \mathbb{R}^2$.
Then by assumption,
$$
T(\vec{p}+t\vec{v})=\vec{p}+t\vec{v}\implies T(\vec{p})+tT(\vec{v})=\vec{p}+t\vec{v}\implies T(\vec{v})=\vec{v},\;T(\vec{p})=\vec{p}
$$
by equating coefficients.
Taking a line parallel to $\ell$ as having the same direction vector, but different starting point, i.e. $\vec{q}+t\vec{v}$, we have
$$
T(\vec{q}+t\vec{v})=T(\vec{q})+tT(\vec{v})=T(\vec{q})+t\vec{v}
$$
which is another line parallel to $\ell$.


text:
Q: How to delete repo on AWS Cloud9? Recently started working with AWS Cloud9 and ran into problem how to delete/remove local repository from a list.
GUI allows many actions by click, but remove repository is not one of them.
How do i remove repository from sourcecontrol panel?

A: What worked for me is treating Cloud9 as regular terminal.
To remove repository you need to run commands:
rm -rf your-repository/.git

And if you would like to clean up the files:
rm -rf your-repository


text:
Q: Get instance of containing class Is it possible to access an object from a member object without passing and storing a reference? In the example below, could a given chair object get access to the house object without the house having to pass its reference down the members hierarchy?
public class Chair {
    public string Material { get; set; }

    public Chair() {
       Material = "Wood";
    }

    public bool IsInMiami() {
       // Get instance of House where chair is found
       House house = ... // Reflection?
       return house.City.Equals("Miami");
    }
}

public class Room {
    private List<Chair> _chairs;

    public Room() {
       _chairs = new List<Chair>();
       _chairs.Add(new Chair());
    }
}

public class House {
    private List<Room> _rooms;
    public string City { get; set; }

    public House() {
       _rooms = new List<Room>();
       _rooms.Add(new Room());
       City = "Orlando";
    }
}

The answer could be via reflection but I don't have a clue how to do it, or is there another way to achieve the same.
Thanks in advance

A: There is no way to do that without the Chair having a reference to the House.  From the point of view of the Chair, there is no relationship between it and a House.  In fact, the Chair could belong to many Houses, or no Houses.

A: First off, is this an example of a real problem or just an example for learning purposes?
It's definitely not Chair's  responsibility to check the house location. If you want to find all chairs in Miami you have to traverse the whole tree or give it a reference.


text:
Q: Changing $|1-x|$ to $|x-1|$ I'm trying to get the limit $$\displaystyle\lim_{x \rightarrow 1} \frac{(x-1)(x-1)}{|1-x|}.$$ I think what I need to do is change $|1-x|$ to $|x-1|$ so I can cancel out one of the terms... but how do I get there?
Thanks so much.

A: First of all $(x-1)^2 = |x-1|^2$ for $x \neq 1$ (can you see why?). Secondly, $$|1 - x| = |-(x-1)| = |-1||x-1| = |x-1|.$$

A: A property of absolute value is that
$|u| = |-u| \quad\forall \quad u$
From here we can switch up that denominator:
Let $u=1-x$
$|(1-x)| = |-(1-x)|$
$|1-x| = |x-1|$
Thus
$\dfrac{(x-1)(x-1)}{|1-x|} = \dfrac{(x-1)(x-1)}{|x-1|}$


text:
Q: Create a shortcode in Wordpress, again There're lots of examples both here and on the internet, I've tried but don't seem to be able to achieve what I need although it does feel like it should be simple enough.
Basically, I want to be able to use a shortcode like this:
[download]http://site.com/file.doc[/download]

and I need Wordpress to output this:
download file
preview file

Your help would be greatly appreciated. Thanks so much!

A: // Declare your shortcode
add_shortcode("download", "downloadFunction");

// Second Declare your shortcode function
function downloadFunction($att, $content, $code){

    // your function is passed 3 Arguments
    // $atts : this is an array of the shortcode's attributes
    // $content : this is the content between the code. in your case the file url.
    // $code : this is the code used. in this case it will be download.
    // here we only need the $content of the shortcode which we place for the file

$return = 'download file';
$return .= 'preview file';

// we then return the result.
return $return;
}


text:
Q: MySQL and PHP INSERT is not inserting into Database I am running a PHP/MySQL insert query using the following code below. I am getting no error, and the query goes off with success. However the database is not updated. I have tested the SQL inside phpAdmin and it does work. I am using binding to add my variables to the SQL query. The only thing I can think of is that the bindings are not working. Is there any way to get the error logs. I cannot seem to find them on XAMPP or online, unless I am terrible at searching for them. Or perhaps someone can see the error in my code below.
<?php

$conn = mysqli_connect("localhost","root","M0nkwork", "blogs");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
else{

    $msg = '';
    $msgClass = '';

    if(filter_has_var(INPUT_POST, 'submit')){

            //Send PHP to database
        $SQL = "INSERT INTO Blogs(UserID, Title, Author, Blog, Date) VALUES (?,?,?,?,?)";
        $stmt = $conn->prepare($SQL);
        $stmt->bind_param("issss", $UserID, $Title, $Author, $Blog, $Date);

        $Author = $_POST['Author'];
        $Title = $_POST['Title'];
        $BlogEntry = $_POST['BlogEntry'];
        $Date = $date = date('m/d/Y h:i:s a', time());
        $UserID = 1;

        if(!empty($Author) && !empty($Title) && !empty($BlogEntry)){
            $stmt->execute();
            $stmt->close();

            $msg = 'Success';
            $msgClass = 'alert-success';
        }else{
            $msg = 'Please Fill in all fields';
            $msgClass = 'alert-danger';
        }
    }
}
?>

A: Thank you one and all for the responses and comments. I found the error and I will post the error here however I wanted to mark this thread as solved as a means for others to get the error logs posted. I believe adding these lines to the beginning of the php code gave me the errors I needed. In the end it turned out to be a disconnect.
If you noticed $BlogEntry is the variable I store my blog body. However $Blog is what I reference in my $SQL query.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);


text:
Q: designing a follower/following schema between two tables in SQL? suppose we have two tables:

*

*Brands

*Users

i want to design a system where:

*

*Brands can follow Brands

*Brands can follow Users

*Users can follow Brands

*Users can follow Users

this is what i have done so far:

*

*ed_id: user_id of the followed

*er_id: user_id of the follower

note: the two tables are different but i haven't written all the attributes to keep things simple
while this works fine among the Users and i can return the followers for each user with some simple queries, i don't know how to establish a relationship between Users and Brands so that they can follow each other.
any help is appreciated!

A: There are a few ways to do this.
It seems that "user" and "brand" are very similar. They share many attributes - in fact, if you replace "brandname" and "username" with "name", they'd be identical.
This could lead you to a range of different designs.
I you think "actually, there are lots of differences, I've just left them out to keep the question simple", you might say that there is a superclass called User, and two subclasses called Brand and Person. There are several ways to model inheritance in relational databases. You might then have a model as follows:
Users
-----
User_id (pk)
hashed_password
salt
phonenumber
address

Person
------
person_id (pk)
user_id (fk)
person_name
....

Brand
-----
brand_id (pk)
user_id (fk)
brand_name
....

Follow
-----
user_id_follower (fk)
user_id_followee (fk)

However, you might conclude that there is no meaningful semantic or behavioural difference between "person" and "brand" - that the type of user is merely an attribute of that user. In that case, life gets even easier:
Users
-----
User_id (pk)
hashed_password
salt
phonenumber
address
name
user_type ('brand', 'person')

Follow
-----
user_id_follower (fk)
user_id_followee (fk)

A: You can base on next tables schema:
-- all entities table
create table followers (
    id int primary key auto_increment,
    follower_type enum('user', 'brand')
);

-- users data extention
create table users (
    id int primary key,
    user_name varchar(255),
    foreign key (id) references followers(id)
);

-- brands data extension
create table brands (
    id int primary key,
    brand_name varchar(255),
    foreign key (id) references followers(id)
);

-- following rules
create table follow_rules (
    id int,
    follow_to int,
    unique key (id, follow_to)
);

Test SQL here


text:
Q: selenium testing on website content based on the unformatted content as the expected value I am able to successfully test the content in a website where the content does not have any html element formatting such as , , , etc. This is easy. I just use String.equals("expectedContent"). However, when there is an html element involved in the middle such as
 or
, the test fails because that is not included in the unformatted expected content. Is there a way for Selenium to ignore those html elements so I can compare apples to apples?
here is the sample html:

Paragraph-a.

paragraph-b.

paragraph-c.

my test content is: Paragraph-a. paragraph-b. paragraph-c.
Thanks in advance for your help.

A: The following results are based off the HTML in the question, slightly modified to include a
 tag in the first paragraph.

Para
graph-a.

paragraph-b.

paragraph-c.

The Python 2.7.6 code I'm using is as follows:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("file:///C:\testing\\test.html")
element = browser.find_element_by_xpath("/html/body")
print element.text
browser.close()

The simple XPath /html/body retrieves the elements without any of the tags.
Para
graph-a.
paragraph-b.
paragraph-c.

I can drill down to the contents of the first paragraph using /html/body/p/strong.
Para
graph-a.

Can you tell what I think the problem is yet? Tags disappear in the sense that it's not outputting the , but the
 tag translates into a newline. Let's add a few lines of code to the Python script, just before the browser close:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("file:///C:\testing\\test.html")
element = browser.find_element_by_xpath("/html/body/p/strong")
print element.text
print text == "Paragraph-a."
print text == "Para
graph-a."
print text == "Para\ngraph-a."
browser.close()

This script outputs the following:
Para
graph-a.
False
False
True

The conclusion is that while we can ignore most HTML tags, we need to be careful when comparing against elements that include line breaks.

A: Please try the given below scripting
int no_of_paragraphs = driver.findElements(By.tagName("p")).size();

for(int i=1;i<=no_of_paragraphs;i++)

{

   System.out.print(driver.findElement(By.cssSelector("p:nth-of-type("+i+")")).getText() + "\t");

}


text:
Q: Cannot delete Ubuntu as a EFI Boot Device I use a Lenovo Yoga 300 something.. Can't remember which, but I recently installed Ubuntu to have as an alternate OS. After a while, I noticed a few limitations to it, and issues that the Internet couldn't fix.
I googled how to get rid of it, and people said to delete the partitions. Great. I did that, but when I booted the laptop, Grub would come up. I found a solution to get rid of it, but Ubuntu is still a EFI device. I have tried using everything to remove it, including resetting my laptop. I did the command prompt thing, and it pops up in there, but everytime you try and delete it, it'll either say successful and come back or will say action failed. Now this wouldn't matter much if I was keeping the laptop, but I'm not. It's going to my mother, and she doesn't understand much about computers, nor the current need to spam F12 at start up to load boot devices. Ubuntu and Windows are both labelled with the same WDC WD5000LPCX-24C6HT0 legacy hard drive name. I have no idea how to fix it and don't want to do something so far fetched I break the laptop. Help?
The Version of Ubuntu was 17.10 Desktop
I've been trying bcedit and using the diskpart stuff
Nothing has been working

A: Grub is installed in the EFI partition. you need to manually delete it.
Boot a LiveCD, and use gparted to temporarily remove the ESP flag from the EFI partition.
Open the EFI partition and delete the folder /EFI/ubuntu.
Use gparted to set the ESP flag again and reboot.


text:
Q: Window image stays for forever in the workspace after closing it The problem
I've installed the latest Kubuntu 16.04, installed the latest release of Kubuntu, making a fresh install.
Now, whenever a "secondary" window is closed, the image will stay forever.
What I mean by a secondary window is that primary windows like, Chromium, Firefox, Ktorrent, etc. Will close normally without secondary effects. However, windows like the "Files are missing" from Ktorrent (or selecting a file from chromium), will close but leaving its track. This "track" will appear when changing from virtual desktop to virtual desktop, but dissapearing after about half a second (probably what the transition occurs), while staying forever in the virtual desktop where it was originally closed.
Example Images:
An example image is shown in the following image

An example taken just at the moment of a transition is as follows

Notes
The images are cumulative, clicking on them has no effect (i.e. like clicking below the image, if the image is over a folder, it will normally open such a folder).

A: I had the same issue. It has something to do with a bug when windows are set translucent. Go to system settings, desktop behavior, and then find anything that has a translucence setting and turn it off. Unfortunately thats an ongoing issue for now.
Hope that helps my friend.


text:
Q: Why is the fourier transform of the autocovariance function only integrated from $-\frac{1}{2}$ to $\frac{1}{2}$? in several time series texts like Shumway, the Fourier transform of the autocovariance function is integrated only over frequencies from $-\frac{1}{2}$ to $\frac{1}{2}$.
I do not understand why it doesn't integrate over $[-\infty, \infty]$ but I vaguely remember something from my numerical methods course about the interval and periodicity. (Could it be that this assumes a period of $1$?)
Could someone explain why we don't have to consider $f$ outside of $[-\frac{1}{2}, \frac{1}{2}]$ here:
$$ \gamma(h) = \int_{-\frac{1}{2}}^{\frac{1}{2}} e^{i2 \pi hf}df$$ where $f$ is the frequency and $h$ the lag?
many thanks in advance!


text:
Q: MongoDB $text operator matching documents where the search string is a substring I'm aware that $text operator doesn't work with regexes... But I need some search to work as the following.
Documents:
{ "field1": "some content", "field2:" "another content"}
{ "field1": "yet one more content", "field2": "the final content"}
If we search by string "ye ano", both documents should be in the results, because ye occurs in the second document and ano occurs in the first.
A workaround for that with $text operator would be really appreciated, because of case/diacritic insensitivity.
I would also accept something with a behavior not equal but close. The major concern is efficiency, because I already have an O(n lg n) solution, but this is very expensive for a search...

A: it looks like we need to have OR and perform search by regex on both fields,
first create indexes :-)

db.math.createIndex({field1:1})
db.math.createIndex({field2:1})

then use [0-4] to search for first signs in the text field, if you omit colscan will occur
db.math.find({$or:[{"field1":{$regex:/ye|ano[0-4]/}},{"field2":{$regex:/ye|ano[0-4]/}}]}
).pretty()

{
        "_id" : ObjectId("56d0c236854cc0de43173fa6"),
        "field1" : "some content",
        "field2" : "another content"
}
{
        "_id" : ObjectId("56d0c24b854cc0de43173fa7"),
        "field1" : "yet one more content",
        "field2" : "the final content"
}

and what is more important index is used for a search:
     db.math.find({$or:[{"field1":{$regex:/ye|ano[0-4]/}},{"field2":{$regex:/ye|ano
    [0-4]/}}]}).explain()
    {
            "queryPlanner" : {
                    "plannerVersion" : 1,
                    "namespace" : "test.math",
                    "indexFilterSet" : false,
                    "parsedQuery" : {
                            "$or" : [
                                    {
                                            "field1" : /ye|ano[0-4]/
                                    },
                                    {
                                            "field2" : /ye|ano[0-4]/
                                    }
                            ]
                    },
                    "winningPlan" : {
                            "stage" : "SUBPLAN",
                            "inputStage" : {
                                    "stage" : "FETCH",
                                    "inputStage" : {
                                            "stage" : "OR",
                                            "inputStages" : [
                                                    {
                                                            "stage" : "IXSCAN",
                                                            "filter" : {
                                                                    "$or" : [
                                                                            {
                                                                                "field1" : /ye|ano[0-4]/
                                                                            }
                                                                    ]
                                                            },
                                                            "keyPattern" : {
                                                                    "field1" : 1,
                                                                    "field2" : 1
                                                            },
                                                            "indexName" : "field1_1_field2_1",
                                                            "isMultiKey" : false,
                                                            "direction" : "forward",

                                                            "indexBounds" : {
                                                                    "field1" : [
                                                                            "[\"\",{})",
                                                                            "[/ye|ano[0-4]/, /ye|ano[0-4]/]"
                                                                    ],
                                                                    "field2" : [
                                                                            "[MinKey, MaxKey]"
                                                                    ]
                                                            }
                                                    },
                                                    {
                                                            "stage" : "IXSCAN",
                                                            "filter" : {
                                                                    "$or" : [
                                                                            {
                                                                                "field2" : /ye|ano[0-4]/
                                                                            }
                                                                    ]
                                                            },
                                                            "keyPattern" : {
                                                                    "field2" : 1
                                                            },
                                                            "indexName" : "field2_1"
    ,
                                                            "isMultiKey" : false,
                                                            "direction" : "forward",

                                                            "indexBounds" : {
                                                                    "field2" : [
                                                                            "[\"\",{})",
                                                                            "[/ye|ano[0-4]/,/ye|ano[0-4]/]"
                                                                    ]
                                                            }
                                                    }
                                            ]
                                    }
                            }
                    },
                    "rejectedPlans" : [ ]
            },
            "serverInfo" : {
                    "host" : "greg",
                    "port" : 27017,
                    "version" : "3.0.8",
                    "gitVersion" : "83d8cc25e00e42856924d84e220fbe4a839e605d"
            },
            "ok" : 1
    }


text:
Q: Xcode-Swift 5: Is it possible to turn off the GPS requirement when launching iOS app on a WiFi only device? I have an app written in Swift 5 using Xcode 13.3.1 that has sensor reads but also a speedometer that works by using GPS which is set as a requirement in "Custom iOS Target Properties" to track speed which works great on an iOS Phone as there is cell service but I want to run the app in an iPad that is Wifi only- no cell service. When I try to run the app in Xcode using the iPad as a test device, it stops on install saying that it can not install because the iPad doesn't support GPS.  I'm wondering if there is a way to disable the need for GPS in the Info Target Properties or in code, when a device that is WiFi only is attached?  I'm fine with the fact that the Speedometer will not function as a result, but the sensor reads will still work.

A:
GPS which is set as a requirement in "Custom iOS Target Properties"

That's the wrong approach. Basically using required hardware properties is frowned on. Just install anywhere, and then fail gracefully if the user tries to employ a feature that requires hardware that isn't there.


text:
Q: libgit2 - git_tree_walk didn't iterate all entries I'm using libgit2 v0.22.2, I put a directory of files into git repo, the odb&refdb is backed by mysql database. The blob,tree,commit object can be found in odb. Trees were written to odb using git_tree_builder and below tree structure table.
When I tried tree walk function to print directory structure, only several entries printed.
code:
int tree_walk_cb(const char *root, const git_tree_entry *entry, void *payload)
{
    const char *name = git_tree_entry_name(entry);
    git_otype type = git_tree_entry_type(entry);

    printf("entry: %s \n", name);

    return 0;
}

int git_mysql_tree_walk(git_mysql *mysql, git_repository *repo){
    int error;
    git_oid oid;
    git_tree *tree = NULL;

    git_oid_fromstr(&oid, "19ee624b3c2983ca0a09b7435dccdaae76a16cad");

    error = git_tree_lookup(&tree, repo, &oid);

    error = git_tree_walk(tree, GIT_TREEWALK_PRE, tree_walk_cb, NULL);
}

output:
entry: .gitattributes
entry: .gitignore
entry: .npmignore
entry: CMakeLists.txt
entry: LICENSE
entry: README.md
entry: cmake

root tree '19ee624b3c2983ca0a09b7435dccdaae76a16cad' content:
100644 .gitattributes ��u����d��K��c=�{100644 .gitignore �$m������V-�)�k100644 .npmignore ө���u�Ƴ�&�Գ�
100644 CMakeLists.txt ��}���# �6/�?f�h{)�100644 LICENSE O6sa/���m�����-�OY100644 README.md A�/B�74wJa����:�rƄ�40000 cmake yi����^Z���[e�l!ğ�#40000 native ��<���Ξ�} X3� �ϙ100644 package.json M-Iő������J$��K40000 script ��L�� ��� �y��#���40000 test K�]�B�n��`�K�֒���I

From the raw root tree content, we can see there're other entries, but they're not printed in the tree walk call back. Also, the tree walk didn't recursively print the sub trees like cmake
Please advise, thanks!
odb:
oid                                   type  size    data
0015cd404c7fa06de9194221e04712f9551146fe    2   115 ...
19ee624b3c2983ca0a09b7435dccdaae76a16cad    2   401 ...
1f6808ef9c0bcb443005acf4542bc1264a5e68f6    3   285 ...
1fe1a4246df70ba6b9a805be1fe7562d9429d46b    3   723 ...
33bbc64e87a5f1baa138d802664a07bf87b81de0    3   366 ...
34832d8c0636fa9a92dbae10f4add7fafe6fc7ab    3   1104    ...
377cc807899a648240718d824306deec8943ab5b    3   7221    ...
37fc4881eff286f264f91aedce13ae7790806061    3   493 ...
41842f42ac3734774a6192c9d7f03ad972c684fc    3   1186    ...
4b825dc642cb6eb9a060e54bf8d69288fbee4904    2   0
4d2d49c591fe1795cfcd1ba8159b4a249c94014b    3   759 ...
4f3673611b2f0e93cdcb6ddaf69499832da94f59    3   1102    ...
5828d750c46503ba9defd5ea37b0d3c46e37b334    3   160 ...
5ac1ceb34a87a8ea589e26a19796e2239cc2e6c5    3   1188    ...
5bc42581996460da22fe58af4537ff454f37fe57    3   14506   ...
5e5af8327eb6ea85d85ea94fd2f64c7317ff3867    1   167 ...
7969f8b194a15e5ae6fec35b65c26c21c49fee23    2   85  ...
7c57e957a1e4abf47cfd58d7fc695262ffbb5673    3   260 ...
7c75467b21b5a8f17a6e5e68c1d12782d39649aa    3   415 ...
801dc03cbabb148dce9ef37d2058339f20b4cf99    2   64  ...
8231cec56dca4ae528ee1253759b0a5cef17de0c    2   408 ...
86b5584b35bcf27022deb9fbf14f3f14f54c4b42    3   8643    ...
8ae61ae3a4cc2882cf1ec883cc4b7ef1d134428b    3   332 ...
8ba87598aa1ed8180bc064e5c84ba7e0633d8e7b    3   37  ...
96c19f76ef41203ddfacba2c2b5975152946aa41    3   1387    ...
aa01580037fd3823bc35c194ee33942f7033246d    2   73  ...
b2811f77461ebaa1314a5c05def22c4220899756    2   145 ...
c2cf7d99a81a9b2300e1362feb3f66cb687b29fa    3   2756    ...
c78274783836eeb8a861d91a03869aab7a58b289    3   385 ...
cd5750aa5dd2214a861900876a905f7bff171970    3   3084    ...
d2a71c98dab94e48e73a262a86e8e79eb7ffdb29    3   78  ...
d3a9ebb5e41ae1751f8314c6b3c12693d4b39b0a    3   225 ...
d64277adcb7d5a41f9088d380f2b498b09341ce9    3   578 ...
e006733c8da938b4401bab8727c301f96abbaf9c    3   335 ...
e271f1db33845ada20afa51a630d68ad0c34a4bf    3   1253    ...
f29ee0d06a2c57bad8406921c6b8dd85e6f29ccc    3   1568    ...
f2cf4cb0e1209cd9df09ad799e0bf5231addd1d0    2   32  ...
f7532185429bb09a7e7c132e21e50a7ea33b4f13    3   10152   ...

tree structure:
tree                                       dir  entry   type    oid
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   .gitattributes  BLOB    8ba87598aa1ed8180bc064e5c84ba7e0633d8e7b
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   .gitignore  BLOB    1fe1a4246df70ba6b9a805be1fe7562d9429d46b
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   .npmignore  BLOB    d3a9ebb5e41ae1751f8314c6b3c12693d4b39b0a
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   CMakeLists.txt  BLOB    c2cf7d99a81a9b2300e1362feb3f66cb687b29fa
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   LICENSE BLOB    4f3673611b2f0e93cdcb6ddaf69499832da94f59
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   README.md   BLOB    41842f42ac3734774a6192c9d7f03ad972c684fc
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   cmake   TREE    7969f8b194a15e5ae6fec35b65c26c21c49fee23
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   native  TREE    801dc03cbabb148dce9ef37d2058339f20b4cf99
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   package.json    BLOB    4d2d49c591fe1795cfcd1ba8159b4a249c94014b
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   script  TREE    f2cf4cb0e1209cd9df09ad799e0bf5231addd1d0
19ee624b3c2983ca0a09b7435dccdaae76a16cad    /   test    TREE    4b825dc642cb6eb9a060e54bf8d69288fbee4904
7969f8b194a15e5ae6fec35b65c26c21c49fee23    /cmake/ FindMysql.cmake BLOB    96c19f76ef41203ddfacba2c2b5975152946aa41
7969f8b194a15e5ae6fec35b65c26c21c49fee23    /cmake/ FindNode.cmake  BLOB    5ac1ceb34a87a8ea589e26a19796e2239cc2e6c5
801dc03cbabb148dce9ef37d2058339f20b4cf99    /native/    addon   TREE    0015cd404c7fa06de9194221e04712f9551146fe
801dc03cbabb148dce9ef37d2058339f20b4cf99    /native/    mysql   TREE    8231cec56dca4ae528ee1253759b0a5cef17de0c
0015cd404c7fa06de9194221e04712f9551146fe    /native/addon/  addon.cc    BLOB    7c57e957a1e4abf47cfd58d7fc695262ffbb5673
0015cd404c7fa06de9194221e04712f9551146fe    /native/addon/  git_mysql.cc    BLOB    5bc42581996460da22fe58af4537ff454f37fe57
0015cd404c7fa06de9194221e04712f9551146fe    /native/addon/  git_mysql.h BLOB    34832d8c0636fa9a92dbae10f4add7fafe6fc7ab
8231cec56dca4ae528ee1253759b0a5cef17de0c    /native/mysql/  mysql_backend.c BLOB    377cc807899a648240718d824306deec8943ab5b
8231cec56dca4ae528ee1253759b0a5cef17de0c    /native/mysql/  mysql_backend.h BLOB    e271f1db33845ada20afa51a630d68ad0c34a4bf
8231cec56dca4ae528ee1253759b0a5cef17de0c    /native/mysql/  mysql_index.c   BLOB    cd5750aa5dd2214a861900876a905f7bff171970
8231cec56dca4ae528ee1253759b0a5cef17de0c    /native/mysql/  mysql_index.h   BLOB    7c75467b21b5a8f17a6e5e68c1d12782d39649aa
8231cec56dca4ae528ee1253759b0a5cef17de0c    /native/mysql/  mysql_odb.c BLOB    f7532185429bb09a7e7c132e21e50a7ea33b4f13
8231cec56dca4ae528ee1253759b0a5cef17de0c    /native/mysql/  mysql_odb.h BLOB    c78274783836eeb8a861d91a03869aab7a58b289
8231cec56dca4ae528ee1253759b0a5cef17de0c    /native/mysql/  mysql_refdb.c   BLOB    86b5584b35bcf27022deb9fbf14f3f14f54c4b42
8231cec56dca4ae528ee1253759b0a5cef17de0c    /native/mysql/  mysql_refdb.h   BLOB    37fc4881eff286f264f91aedce13ae7790806061
8231cec56dca4ae528ee1253759b0a5cef17de0c    /native/mysql/  mysql_repo.c    BLOB    f29ee0d06a2c57bad8406921c6b8dd85e6f29ccc
8231cec56dca4ae528ee1253759b0a5cef17de0c    /native/mysql/  mysql_repo.h    BLOB    1f6808ef9c0bcb443005acf4542bc1264a5e68f6
f2cf4cb0e1209cd9df09ad799e0bf5231addd1d0    /script/    mysql   TREE    b2811f77461ebaa1314a5c05def22c4220899756
b2811f77461ebaa1314a5c05def22c4220899756    /script/mysql/  index.sql   BLOB    d64277adcb7d5a41f9088d380f2b498b09341ce9
b2811f77461ebaa1314a5c05def22c4220899756    /script/mysql/  odb.sql BLOB    33bbc64e87a5f1baa138d802664a07bf87b81de0
b2811f77461ebaa1314a5c05def22c4220899756    /script/mysql/  refdb.sql   BLOB    e006733c8da938b4401bab8727c301f96abbaf9c
b2811f77461ebaa1314a5c05def22c4220899756    /script/mysql/  repo.sql    BLOB    8ae61ae3a4cc2882cf1ec883cc4b7ef1d134428b
4b825dc642cb6eb9a060e54bf8d69288fbee4904    /test/  mocha.opts  BLOB    d2a71c98dab94e48e73a262a86e8e79eb7ffdb29
4b825dc642cb6eb9a060e54bf8d69288fbee4904    /test/  test.js BLOB    5828d750c46503ba9defd5ea37b0d3c46e37b334

A: the issue is with mysql backend, mysql_stmt_fetch in the odb_read function
mysql_stmt_fetch throw exception in debug mode, while in release mode, it's working fine, and all entries in the tree printed
logged a new question to tag: mysql to track the issue
mysql C API - mysql_stmt_fetch throw exception: access violation write at 0x00000008


text:
Q: About functions and little calculus Many a times I come upon an $x$ vs. $t$ graph in which the distance $x$ is given as a function of time like $x=f(t)=20+5t^2$.
Can its reverse be found? For example, given
at t=0 x=20
   t=1 x=25
   t=2 x=40
   t=3 x=65
   t=4 x=100

Also if acceleration is constant and given that the curve is a continuous, find the expression for $x=f(t)=?$
Please give a detailed proofs (I have just started calculus). Thanks.

A: With the information given in the example you gave, you can't be sure you would find $f(t)$ as given in the exercise. You could plot the values in a graph, and using any plotting software, you can approximate the function, and you would obtain the same answer. However, you can have a very wiggly continuous function such that the values of $t=0,1,2,3,4..$ are those you gave. So to give you a picture of how could you solve it analitically, you would have to take very "little" intervals of $t$ so to be sure that your function (although continuous) doesn't do whatever she likes in the intervals of $t$ you took.

A: This can be addressed by the finite difference method, i.e. computing pairwise differences.
In the given case,
$$20, 25, 40, 65, 100\to5,15,25,35.$$
Repeating this process,
$$5,15,25,35\to10,10,10.$$
Having a constant second order difference confirms that the quadratic model is compatible.
Indeed, let $f(t)=\frac12at^2+bt+c$. The first order difference is
$$\Delta f(t)=f(t+1)-f(t)=(\frac12a(t+1)^2+b(t+1)+c)-(\frac12at^2+bt+c)=a(t+\frac12)+b.$$
And the second order one,
$$\Delta^2 f(t)=\Delta g(t)=g(t+1)-g(t)=(a(t+1+\frac12)+b)-(a(t+\frac12)+b)=a,$$
a constant.
Hence we have identified that the acceleration is $a=10$.


text:
Q: Client does not support authentication protocol requested by server; consider upgrading MySQL client I am trying to connect MySQL client through a Perl script. But again and again I am getting error

ERROR 1251: Client does not support authentication protocol requested by server; consider upgrading MySQL client

My MySQL client has been upgraded from 5.1 to 5.6.
I am using Perl v5.12.0, DBD::mysql is 4.017, DBI is 1.613.
Is this problem with the Perl module or with MySQL.

A: in my.conf
add
[mysqld]
skip-secure-auth=true
it permiss use old protocol, but your security exists no more. Do it only in development ambient.


text:
Q: Php to only show the YEAR from sql DATETIME I have a function that I am using for a foreach loop that the 3 latest posts from the mySQL DB.
function latest_posts_footer(PDO $dbh) {
    global $dbh;

    $stmt = $dbh->prepare("
        SELECT      *
        FROM        posts
        ORDER BY    post_date DESC
        LIMIT       0, 3
    ");
    $stmt->execute();
    return $stmt->fetchAll();
}
latest_posts_footer($dbh);
$latest_posts_footer = latest_posts_footer($dbh);

The post_date type is DATETIME which works correctly.
I know that the query: SELECT YEAR(post_date) FROM posts; gives me the year out my post_date.
To just show the raw DATETIME I can simply do:

Which would bring me the output: 2000-01-01 00:00:00.
How do I only get the YEAR from that output with PHP? Help is more than appreciated. Thanks!
P.S. I've already looked into previous posts regarding the same thing, but they wont help.

A: $year = date("Y", strtotime($lpf['post_date']));

echo $year;

A: What do you exactly mean by YEAR?
$yearOnly = date("Y", $lpf['post_date']);

PHP DATE Manual

A: here's a hint
 $date = DateTime::createFromFormat("Y-m-d", "2068-06-15");
 echo $date->format("Y");

unless i'm misunderstanding something here


text:
Q: "The declaration 'setState' isn't referenced." warning for DropdownButton within StatefulWidget I have a stateful widget in which I put my DropdownButton. Inside DropdownButton's onChange event, I have a setState but it keeps warning me that the declaration 'setState' isn't referenced.
And it's actually not called whenever onChange event is fired.
Any suggestion would be highly appreciated.
Please see the code snippet below for more detailed.
class TypeSetup extends StatefulWidget {
  const TypeSetup({Key? key}) : super(key: key);

  @override
  _TypeSetupState createState() => _TypeSetupState();
}

class _TypeSetupState extends State<TypeSetup> {
  var _selectedType;
  List<Type>? _types;

  @override
  void initState() {
    super.initState();

    loadTypeJson();
  }

  Future loadTypeJson() async {
    String typeJson = await DefaultAssetBundle.of(context)
        .loadString("assets/data/types.json");

    Iterable typeIter = json.decode(typeJson)["accommodation-types"];

    setState(() {
      _types = List<Type>.from(typeIter.map((model) => Type.fromJson(model)));
    });
  }

  @override
  Widget build(BuildContext context) {
    final typeList = _types?.map((model) {
      return new DropdownMenuItem<String>(
        value: model.type,`enter code here`
        child: new Text(model.name),
      );
    }).toList();

    return Container(
      padding: EdgeInsets.all(DefaultPalette.defaultPadding),
      decoration: BoxDecoration(
        color: DefaultPalette.secondaryColor,
        borderRadius: const BorderRadius.all(Radius.circular(10)),
      ),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text(
          "Set up",
          style: Theme.of(context).textTheme.subtitle1,
        ),
        SizedBox(
            width: double.infinity,
            child: Center(
                child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Container(
                      padding: EdgeInsets.only(left: 16, right: 16),
                      decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey, width: 1),
                          borderRadius: BorderRadius.circular(13)),
                      child: DropdownButton(
                        hint: Text('Select  Type'),
                        dropdownColor: Colors.white,
                        icon: Icon(Icons.arrow_drop_down),
                        iconSize: 30,
                        isExpanded: true,
                        underline: SizedBox(),
                        style: TextStyle(color: Colors.black, fontSize: 22),
                        value: _selectedType,
                        onChanged: (newValue) {
                          setState() {
                            _selectedType = newValue;
                            print("Selected type changed.");
                          }
                        },
                        items: typeList,
                      ),
                    )
                )
            )
          )
      ]),
    );
  }
}

A: You need to call setState like this
setState(() {
  _selectedType = newValue;
});


text:
Q: Publishing in Shopify Appstore: Do you have to be using their API? So we have built a large platform that integrates completely with Shopify's API. As a result we've signed on hundreds of Shopify brands who have integrated our technology.
Now, we also have a separate influencer marketing tool that we make available to our partner brands. It doesn't involve the Shopify API at all, but it's made available exclusively to Shopify brands and they get a lot of use out of it.
Is it possible to publish into the Shopify appstore with something that doesn't actually use the Shopify API but is a tool for Shopify brands? Trying to use this as a lead generation tactic.

A: Shopify's App Store only accepts apps that use the Shopify API. You can find more information about the approval criteria here: https://help.shopify.com/api/listing-in-the-app-store/app-review-checklist


text:
Q: Discord Python Rewrite - Move channel Is it possible to move a channel on discord.py? Im making a nuke command that clones and deletes the channel, and it worked, but now i need to find out how to move the channel up to the origonal place, if there's a code / docs, please tell me a example. Thank's
Edit:
I Got a working edit but it's always drags it on top, i need it so it will drag the channel to the same position before it got nuked.
My code that i currently have
@client.command()
@commands.has_permissions(manage_channels=True)
async def nuke(ctx):

    channel = ctx.channel

    await channel.clone()
    await channel.delete()
    await channel.edit(position=0, sync_permissions=True)
    return

A: You can use await channel.edit(position=0) to change the position. In this case, since 0 is specified, the channel will be moved to the first position.
If you want to move it to the deleted channel's position then you can check channel.position.
@client.command()
@commands.has_permissions(manage_channels=True)
async def nuke(ctx):

    channel = ctx.channel
    channel_position = channel.position

    new_channel = await channel.clone()
    await channel.delete()
    await new_channel.edit(position=channel_position, sync_permissions=True)
    return


text:
Q: To know list of users having access to Views Please help me to find out the list of users who are having access to particular user defined views in Oracle.?

A: DBA_TAB_PRIVS is probably the best starting place. In that view, you can pass in the view you're looking for in the TABLE_NAME field. If you want to see who has permissions to more than one view, you could always use a sub-select on the DBA_VIEWS view to then see what the DBA_TAB_PRIVS on that view are.
However, depending on how your database was implemented, you may also need to look at role information. Using DBA_TAB_PRIVS may only show you the roles that have select on the view(s), from there you'll have to use the DBA_ROLE_* series of views to determine which physical users have been assigned those roles.

A: use this view  desc dba_tab_privs;


text:
Q: Github network graph not displaying correctly merge --no-ff I recently started a new project but it feels like github network is wrong, workflow went like this:

*

*From master create new branch develop

*From develop create new branch menu

*Some commits on menu branch

*Merge menu into develop using --no-ff

Network graph looks like this:

By using --no-ff I was expecting something like this:

Why is my workflow displayed this way? How can I make it like intended?
Edit: I tried using the 'git log --graph --decor' command and graph showed in terminal is correct so I guess it's just the github website representation that's wrong

A: The GitHub repository network is for:

displaying the branch history of the entire repository network, including branches of the root repository and branches of forks that contain commits unique to the network.

That means, for one repo, the branch view is "flattened": you won't see branches on multiple lines: only one line per repo, with the occasional "bump" done by one of the repo branches being merged back.


text:
Q: $f(a(x))=f(x)$ - functional equation I was reading "Functional Equations and How to Solve Them" by Small and the following comment pops up without much justification on p. 13:

If $a(x)$ is an involution, then $f(a(x))=f(x)$ has as solutions $f(x) = T\,[x,a(x)]$, where $T$ is an arbitrary symmetric function of $u$ and $v$.

I was wondering why this was true (it works for examples I've tried, but I am not sure $(1)$ how to prove this and $(2)$ if there's anything obvious staring at me in the face here).

A: Any function f(x) that is a solution to your functional equation f(a(x)) = f(x) must satisfy the property that it is unchanged when you plug in a(x) instead of x. In addition, f(x) clearly must be a function f(x) = T[x, a(x)] depending on the x and a(x); the question is to see why T must be symmetric.
Now, T[x, a(x)] = f(x) = f(a(x)) = T[a(x), a(a(x))] = T[a(x), x] since a(x) is an involution. In particular, this means that T must be symmetric in its two variables.


text:
Q: Hibernate: Is it possible to map multi-level inheritance to single table? I have following inheritance hierarchy:
Task
  |
SpecificTask
  |
VerySpecificTask

And I'd like to persist it usign single-table inheritance, so I annotated classes:
@Entity
@Table(name="task")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Task

@Entity
public class SpecificTask extends Task

@Entity
public class VerySpecificTask extends SpecificTask

When I try to save an object of VerySpecificTask class, I get an error:
Unable to resolve entity name from Class [com.application.task.VerySpecificTask]
expected instance/subclass of [com.application.task.Task]

What do I wrong? Is it possible to map multi-level inheritance to single table?
EDIT: Here was a lame bug, I've resolved quickly, so I deleted it to not mess this question.

A: OK, I've added discriminator column and now it works.
Changed code:
@Entity
@Table(name="task")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
        name="DTYPE",
        discriminatorType=DiscriminatorType.STRING
    )

@Entity
public class SpecificTask extends Task

@Entity
public class VerySpecificTask extends SpecificTask

(I'm adding it just to provide an accepted answer -- I wouldn't resolve it without the helpful comments to the question.)

A: The accepted answer is almost perfect. To make it more clear I want to add a @DiscriminatorValue to each inheritance level.
@Entity
@Table(name="task")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
        name="DTYPE",
        discriminatorType=DiscriminatorType.STRING
)
public class Task

---

@Entity
@DiscriminatorValue(value="DS")
public class SpecificTask extends Task

---

@Entity
@DiscriminatorValue(value="DV")
public class VerySpecificTask extends SpecificTask

And the materiliazed table looks like
---------------
Table: task
---------------
|...|DTYPE|...|
---------------
|...|DS   |...|
|...|DV   |...|
|...|DS   |...|
...

A: Try the @MappedSuperclass annotation :
@MappedSuperclass
public class BaseEntity {
    @Basic
    @Temporal(TemporalType.TIMESTAMP)
    public Date getLastUpdate() { ... }
    public String getLastUpdater() { ... }
    ...
}

@Entity
public class Order extends BaseEntity {
    @Id public Integer getId() { ... }
    ...
}

In database, this hierarchy will be represented as an Order table having the id, lastUpdate and lastUpdater columns. The embedded superclass property mappings are copied into their entity subclasses. Remember that the embeddable superclass is not the root of the hierarchy though.


text:
Q: R shiny: different behaviours of observeEvent and eventReactive The shiny app below displays an editable table built with rhandsontable().
Question: Can you explain me why "ping" is printed to the console whenever an edit is made to the data table while "pong" is never printed.
library(shiny)

ui <- fluidPage(
  rhandsontable::rHandsontableOutput(
    outputId = "data")
)

server <- function(input, output, session) {

  data <- data.frame(a = 1, b = 2, c = 3)

  output$data <- rhandsontable::renderRHandsontable({
    rhandsontable::rhandsontable(
      selectCallback = TRUE,
      data = data)
  })

  observeEvent(input$data$changes$changes, {
    print("ping")
  })

  edits <- eventReactive(input$data$changes$changes, {
    print("pong")
  })

}

shinyApp(ui = ui, server = server)

A: It's because edits() isn't called thereafter, so shiny thinks you don't need it, hence no reason to do any work on it, you need to add where it should go or what you want to do with it:
library(shiny)

ui <- fluidPage(
    rhandsontable::rHandsontableOutput(
        outputId = "data")
)

server <- function(input, output, session) {

    data <- data.frame(a = 1, b = 2, c = 3)

    output$data <- rhandsontable::renderRHandsontable({
        rhandsontable::rhandsontable(
            selectCallback = TRUE,
            data = data)
    })

    observeEvent(input$data$changes$changes, {
        print("ping")
    })

    edits <- eventReactive(input$data$changes$changes, {
        print("pong")
    })

    observe({
        edits()
    })

}

shinyApp(ui = ui, server = server)


text:
Q: Can't retrieve Double from HashMap Somehow I can't retrieve a Double from a HashMap I've made using Gson.
Map<Integer, Double> ratingMap = (Map<Integer, Double>) new GsonBuilder()
            .create().fromJson(json, Map.class);
Integer ifilmId = filmId;
Double rating = ratingMap.get(ifilmId);

In this code I've veried that the ratingMap contains {2=5.0}, but when I do ratingMap.get(ifilmId) (where I've verified that ifilmId is in fact 2), the variable rating is null. Am I missing something here?
I create the HashMap in the following way:
if (json.equals("")) {
        // noting ever saved
        ratingMap = new HashMap<Integer, Integer>();
        ratingMap.put(filmId, rating);

} else {
        ratingMap = (Map<Integer, Integer>) new GsonBuilder().create()
                .fromJson(json, Map.class);
        ratingMap.put(Integer.valueOf(filmId), rating);
}

I let Gson format the Integer to a Double, and that seems to work fine but I can't retrieve it.
The total code, including saving to Androids SharedPreferences
public void saveRating(int rating, int filmId) {
    SharedPreferences sharedPref = context.getSharedPreferences(
            LOCAL_MEM_KEY, 0);
    String json = sharedPref.getString(LOCAL_MAP_RATING_KEY, "");
    Map<Integer, Integer> ratingMap;
    if (json.equals("")) {
        // noting ever saved
        ratingMap = new HashMap<Integer, Integer>();
        ratingMap.put(filmId, rating);

    } else {
        ratingMap = (Map<Integer, Integer>) new GsonBuilder().create()
                .fromJson(json, Map.class);
        ratingMap.put(Integer.valueOf(filmId), rating);
    }

    json = new GsonBuilder().create().toJson(ratingMap, Map.class);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString(LOCAL_MAP_RATING_KEY, json);
    editor.commit();
}

/*
 * returns null if no rating found
 */
public Map<Integer, Integer> getRatingFor(int filmId) {
    SharedPreferences sharedPref = context.getSharedPreferences(
            LOCAL_MEM_KEY, 0);
    String json = sharedPref.getString(LOCAL_MAP_RATING_KEY, "");
    if (json.equals("")) {
        return null;
    }

    Map<Integer, Integer> ratingMap = (Map<Integer, Integer>) new GsonBuilder()
            .create().fromJson(json, Map.class);
    Log.d("map", ratingMap.toString());
    Integer ifilmId = filmId;
    Integer rating = ratingMap.get(ifilmId);
    if(rating == null) { //because of this we have to prevent a 0 rating
        return null;
    } else {
        Map<Integer, Integer> returnMap = new HashMap<Integer, Integer>();
        returnMap.put(filmId, rating.intValue());
        return returnMap;
    }
}

A: Make sure your not passing a null variable when saving
saveRating(int rating, int filmId){
    Log.d(TAG, String.valueOf(rating));
}

if (json.equals("")) {
    // noting ever saved
    ratingMap = new HashMap<Integer, Double>();    <--- Double not Integer
    ratingMap.put(filmId, 5.0);

} else {
    ratingMap = (Map<Integer, Double>) new GsonBuilder().create()
            .fromJson(json, Map.class);           <--- double not Integer
    ratingMap.put(Integer.valueOf(filmId), 5.0);
}

Make sure when using Doubles to
use 5.0
not 5

A: public void saveRating(Double rating, int filmId) {
    SharedPreferences sharedPref = context.getSharedPreferences(LOCAL_MEM_KEY, 0);
    String json = sharedPref.getString(LOCAL_MAP_RATING_KEY, "");
    Map<Integer, Double> ratingMap;
    if (json.equals("")) {
        // noting ever saved
        ratingMap = new HashMap<Integer, Double>();
    } else {
        ratingMap = (Map<Integer, Double>) new GsonBuilder().create().fromJson(json, Map.class);
    }
    ratingMap.put(filmId, rating);
    ratingMap.put(3, 5.0d); // JUST FOR TEST
    json = new GsonBuilder().create().toJson(ratingMap, Map.class);
    SharedPreferences.Editor editor = sharedPref.edit();

    editor.putString(LOCAL_MAP_RATING_KEY, json);
    editor.commit();
}

/*
 * returns null if no rating found
 */
public Map<Integer, Double> getRatingFor(int filmId) {
    SharedPreferences sharedPref = context.getSharedPreferences(LOCAL_MEM_KEY, 0);
    String json = sharedPref.getString(LOCAL_MAP_RATING_KEY, "");

    if (json.equals("")) {
        return null;
    }

    Map<Integer, Double> ratingMap = (Map<Integer, Double>) new GsonBuilder().create().fromJson(json, Map.class);
    Log.d("map", ratingMap.toString());
    Log.d("map", ratingMap.get(3) + ""); // JUST FOR TEST
    Integer ifilmId = filmId;
    Double rating = ratingMap.get(ifilmId);

    if (rating == null) { //because of this we have to prevent a 0 rating
        return null;
    } else {
        Map<Integer, Double> returnMap = new HashMap<Integer, Double>();
        returnMap.put(filmId, rating);
        return returnMap;
    }
}


text:
Q: Relation between integral curves Let $M$ be a manifold, $f:M\rightarrow\mathbb{R}$ a differentiable map and $X$ a vector field on $M$. I'm trying to find a relation between the integral curves of $X$ and $e^fX$.
I am not quite sure how to approach this problem, integrate doesn't seem a good idea and I don't manage to get anywhere that way.


text:
Q: How many parameters are too many in JavaScript? I came across the following question on StackOverflow: How many parameters are too many?
This got me thinking, is there a practical limit imposed on the number of parameters of a JS function?

test(65536); // okay
test(65537); // too many

function test(n) {
    try {
        new Function(args(n), "return 42");
        alert(n + " parameters are okay.");
    } catch (e) {
        console.log(e);
        alert(n + " parameters are too many.");
    }
}

function args(n) {
    var result = new Array(n);
    for (var i = 0; i < n; i++)
        result[i] = "x" + i;
    return result.join(",");
}

Turns out, JavaScript imposes a practical limit of 65536 parameters on functions.
However, what's interesting is that the error message says that the limit is 65535 parameters:
SyntaxError: Too many parameters in function definition (only 65535 allowed)

So, I have two questions:

*

*Why this discrepancy? Is it an off-by-one error in the language implementations?

*Does the ECMAScript standard impose this limit on function parameters?

A: Argument length limited to 65536
https://bugs.webkit.org/show_bug.cgi?id=80797
There are different argument count limits, depending on how you test: http://mathiasbynens.be/demo/javascript-argument-count


text:
Q: Estimating a derivative of a linear data series using a parabolic fit Hi I've tried asking this on the signal processing stack exchange, and whilst the question has been upvoted, nobody's been able to help me.
I'm trying my best but my maths isn't good enough to implement the algorithm in python. It's for detecting the onset and offset of a wave on an ECG, and it's using a well validated method.
The steps it uses are:
A. Computation of the envelope of the ECG
B. Computation of the auxiliary signal
C. Windowing
Step A is straight-forward enough:
def calculate_qrs_envelope(self):
    self.hilbert = np.imag(hilbert(self.lead_data['y']))
    self.envelope = np.sqrt(np.add(self.lead_data['y'],self.hilbert))
    self.plot(x=self.lead_data['x'], y=self.envelope, pen='b')

Where my data is stored in lead_data['y'].
If I plot it, it looks correct (I can't show the picture here as I don't have enough karma).
And I'm confident that I won't struggle with step C.
However, B is difficult. It says in the paper:
Link to paper paragraph explaining method
So basically I need
$$AS = 2(ECG'_e(k))^2$$
Where the derivative at sample time $k$ of $ECG_e$ is estimated with a parabola which best fits the five points of the signal $ECG_e(k)$ around the time location of k, following the formula:
$$ECG'_e(k) ≈ \frac{1}{10} (2(ECG_e(k+2r) - ECG_e(k-2r)) \\\\
+ ECG_e(k+r) - ECG_e(k-r))$$
Where $r = [f_s/250]$
$f_s$ for me is my sampling frequency is 100Hz, but I can't figure out how to implement this stage of the algorithm. Obviously, once I've got the derivative, I can just get AS using:
def calculate_auxiliary_signal(self):
    self.aux_sig = np.multiply(2,pow(<derivative>,2))
    self.plot(x=self.lead_data['x'], y=self.aux_sig, pen='g')

Can anyone help me or point me in the right direction about how to estimate a derivative using a parabolic fit?
Thanks guys
EDIT: doing some reading I suspect a https://en.wikipedia.org/wiki/Savitzky–Golay_filter would be good, maybe I could just use savitzky_golay(y, window_size=5, order=2, deriv=1) on my numpy array for what I need? The issue is that doesn't take into account $r$ which is derived from the sampling frequency.


text:
Q: 2.1 Syntax not Working in 2.2. Update child record via parent class Hello OrientDB followers,
I have an issue that has been taking up more of my time than i would like to spend on.
In 2.1, I was able to update a parent record and child record from a single command or just the child record via an update of the parent class. However, in 2.2, it does not work.. I have used the same exact syntax in both.
Take the following sample data set
create class Users
create property Users.username
create property Users.password

create class Devices
create property Devices.name

insert into Users (username, password) values('johndoe','randompassword')

  update users add Devices = [{
            "@type": "d",
            "@class": "Devices",
            "name": "Note 7"
        }]

lets say that the Device class record that we just inserted ended up with an rid of #13:0
In version 2.1, I am able to execute the following syntax below, in order to update the parent and the child record. It works perfect
  update users set username = 'johndoethesenior', Devices = [{
            "@type": "d",
            "@rid":   #14:0,
            "@version":1,
            "@class": "Devices",
            "name": "Note 8"
        }] where username = 'johndoe'

There lies my issue. In 2.1 it works perfectly. However, in 2.2, even though i do not get an error and it shows the record as updated, the name on the Devices record does not change from Note 7 to Note 8.
The change on the parent record, does go through and changes from johndoe to johndoethesenior.
I looked through the release notes and changes of 2.1 -> 2.2 and could not find any references to this.
Did i discover a bug, or am I overlooking something that changed in the orient architecture after 2.2 release.
Last note, I have tried this on at least 4 versions of 2.2, on different servers and deployments. All have the same behavior.
Any guidance in the matter would be truly appreciated.
Thanks,

A: As work - around you can try with this easy JS function:
var g = orient.getGraph();
var b = g.command("sql","update users set username = '"+newUserName+"' where username = '"+userName+"'");
var c = g.command("sql","update devices set name = '"+newDeviceName+"' where name = '"+deviceName+"'");

This is how you call it in studio:
select newUpdate("new value of class users","value to replace of class users","new value of class devices","value to replace of class devices")

Hope it helps
Regards

A: As a workaround you could use the SQL BATCH.
I used your structure

I used this sql batch command
begin
let $a= update users set username="johndoethesenior" return after $current.Devices.@rid where username="johndoe"
let $b = update $a.value set name="Note 8" return after $current.@rid
commit
return [$a.size(),$b.size()]

and I got

Hope it helps.


text:
Q: I get this error Error: Unknown command: cask any ideas? putting the command 'brew cask install adoptopenjdk8' gives me that error, any ideas?
Error: Cask adoptopenjdk8 exists in multiple taps:
homebrew/cask-versions/adoptopenjdk8
adoptopenjdk/openjdk/adoptopenjdk8
in Mac M1...

A: Try:

*

*brew tap AdoptOpenJDK/openjdk first

*then brew install --cask <version you want>
the tap allows you to stay with the release you want. Also, your command above may not work because AdoptOpenJDK8 isn't the latest version


text:
Q: dplyr: R crash/errors with group_by, mutate I'm writing a function to remove duplicate observations of undirected relationships between firms when both parties report the relationship. For my ~1.3 million observation dataset, the function collapse_undirected below results either in R crashing during the mutate for hash or the error:
"translateCharUTF8 must be called on CHARSXP"
during the mutate for dup.
The goal of this function is to uniquely identify each pair of related firms by ordering and concatenating their IDs, and then dropping duplicate hashes reported in the same time period.
The data set I'm using is licensed so I can't provide it, but the "translateCharUTF8" error is reproducible with the randomly generated data I've included below. It occurs more frequently with larger sets. I'd say its common at around 9000 observations. I've also included a slow version of the function that runs without incident, which further leads me to believe that the problem occurs in the first mutate.
The function with the error:
collapse_undirected <- function(data, dir){

  out <- data %>% filter(REL_TYPE != dir)

obs <- data %>% filter(REL_TYPE == dir) %>%
  group_by(SOURCE, TARGET) %>%
  mutate(hash = paste(min(SOURCE, TARGET),max(SOURCE, TARGET))) %>%
  group_by(START, END) %>%
  mutate(dup = duplicated(hash)) %>%
  filter(!dup) %>%
  select(-hash,-dup)

bind_rows(out,obs)
}

The slow workaround:
jank_undir <- function(data, dir){

  obs <- data %>% filter(REL_TYPE == dir)
  out <- data %>% filter(REL_TYPE != dir)
  obs$hash <- NA

  for(i in 1:nrow(obs)){
        obs$hash[i] <- paste(min(obs$SOURCE[i], obs$TARGET[i]),
                     max(obs$SOURCE[i], obs$TARGET[i]))
      }

  obs %>% group_by(START,END) %>%
    mutate(dup = duplicated(hash)) %>%
    filter(!dup) %>%
    select(-hash,-dup) %>%
  bind_rows(out)
}

Here's a convenience function to randomly generate test data:
reroll <- function(n){

test_data <- data_frame(1:n)

test_data$SOURCE <- as.character(sample(1:27000, size = n, replace = TRUE))
test_data$TARGET <- as.character(sample(1:27000, size = n, replace = TRUE))
test_data$REL_TYPE <- "DUMMY"
test_data$START <- sample(1:2870, size = n, replace = TRUE)
test_data$END <- sample(1:2781, size = n, replace = TRUE)

test_data
}

And, varying with the random draw, this should demonstrate the error:
library(dplyr)

test_data <- reroll(9000)

test_cleaned <- test_data %>% jank_undir("DUMMY")

test_cleaned <- test_data %>% collapse_undirected("DUMMY")

I'd greatly appreciate any insight into why this is happening. The slow version is fast enough for now but I anticipate needing to use it for larger datasets. The R crashes occurred on both my Windows and Linux based R sessions with the main dataset but seems less frequent on the Linux version. My dplyr is 0.7.2
Thank you,


text:
Q: How do you turn an irrational, non-transcendental number, like 1.618... back to its form of (a + sqrt(b))/c. Looking at irrational numbers, I had an idea, as to computing square roots.
Take the golden ratio. Numerically, it's 1.618.... but I can also write it like this:
$\frac{1+ \sqrt{5}}{2}$
I want to figure an algorithm that can convert an irrational into the form
$\frac{u+ \sqrt{v}}{w}$, where $u, v, w$ are natural numbers.(If it is possible. I'm only considering square roots for the answer.)
Now if you could, I would love it if you could complete my idea.
I believe the given irrational can be a the root of a quadratic (not cubic or higher because I'm only considering square roots)
by comparing the form $\frac{u+ \sqrt{v}}{w}$to the quadratic equation, if i let the number say, $n = \frac{u+ \sqrt{v}}{w}$, i think, if i take another number say $m = \frac{u- \sqrt{v}}{w}$ and keeping them as the roots off the quadratic, all the coefficients will be, natural numbers. (I'm not sure if this is 100% true, but I'm confident it is).
This said algorithm is to be coded into a computer, which will take a large number of digits as the input for accuracy.
Thank you.

A: A quadratic irrational will have an eventually periodic continued fraction.

A: As asked the question has no solution. This is simply because, regardless of what numerical value you feed the computer, there will always exist infinitely many approximations to that numerical value of the form $(u+\sqrt v)/w$, $u,v,w\in\mathbb Z$ up to arbitrarily many digits. For example,
$$\frac{1+\sqrt5}{2}\approx \frac{10^n+\sqrt{5\cdot10^{2n}+1}}{2\cdot10^n}$$
where $n$ is a large positive integer. In fact, by making $n$ to be arbitrarily big, we can make this approximation to have infinite precision. There's nothing special about the base of the exponential; instead of $10$ it can be $2$ or $17$ or whatever number you like. We could also have in the square root, $5\cdot10^{2n}+2$, or $-1$, or $+7$ instead. We have so many approximations to the same number; even 100-digit precision won't suffice! One way to resolve this issue is to somehow make your program prioritize smaller $u,v,w$ in its numerical search, but this doesn't work perfectly.


text:
Q: Is http://example.com// handled differently than http://example.com/ for all clients? Question: Normally one gets the same HTML site for the URLs http://example.com// and http://example.com/ (the first URL has two slashes in the end). I guess, I can configure my website in a way, that the served HTML differs between the two URLs. Is this always handled correctly by all clients, i.e. do all client send a get request starting with GET // HTTP/1.1 in the first line? (Or are there clients/browser who shorten the request of http://example.com// to GET / HTTP/1.1 with one slash?)
Background of my question: I want to implement a JavaScript version of my website using the hash fragement #!. In this version the whole content shall be loaded dynamically. I thought that URLs like http://example.com/foo/bar/ shall become http://example.com//#!/foo/bar/ (short URL in the end) whereby I serve under http://example.com// the JavaScript for this site version (which differs from http://example.com/). I just asked myself, whether this approach is theoretically possible or not concerning todays standards for URLs.

A: Here are some results, I got so far:

*

*Firefox (Version 28.0): YES (sends two slashes)

*curl (and I hope therefore also programs using libcurl): YES (sends two slashes)

*wget: YES (sends two slashes)

*Chromium (Version 33.0): YES (sends two slashes)
Unfortunately I have no access to more browsers now. I will update this answer. But it would be good, if you can post some more experiences in the meanwhile ;-)
Comment of @Kevin B:

Definitely suggest cross-browser/os testing this before running with it, i've had issues in the past with linking to images for example with an erroneous // instead of / in the path working in chrome but not firefox.


text:
Q: How does a desktop environment developer test his code? I can't figure out how a desktop environment developer test his code. Usually, a C or C++ programmer compiles his code an then run it (i'm not one of those programmers, i'm a web one).
So, you usually build your gui application over some kind of desktop environment (windows, mac os x, gnome, kde, xfce...), sow how they build and test their gui desktop?
And if this is a silly question, how does a kernel programmer test his code? for example linux kernel? how do you know that what you just wrote works?

A: Testing is a very broad term there are many types (partial list):

*

*unit tests - test small pieces of code. test that the code behaves as expected.

*system tests - test whole application in real world scenarios.

*performance tests - test what is the performance of the application or part of it.

*GUI testing - test operation of GUI elements (not so common as automated tests)

*static analysis - compiler warnings on steroids

*dynamic analysis - at a minimum memory checks - check mem allocations and usage

*coverage tests - check that all code is executed.

*formal verification tests (very advanced) - e.g. check when assertions/assumptions are broken.

Kernel code can be debugged by connecting using a 2nd computer (host). Virtual machines uses the same principal and simplify the setup but can't always work as HW might not exist in the guest VM.
The kernel (all OSes) has trace mechanism(s) for printing progress/problems. In Linux the simple trace is shown via the dmesg command (prints a cyclic buffer).
User mode code can easily be stopped and debugged via a debugger.

A: Desktop Environments
Testing Desktop Environments in real world scenarios can be kind of annoying, so the developer would have to watch out for every small error he makes, if he doesn't, he will have a hard time developing the DE.
As stated by @egur, there are multiple ways of testing his code, the easiest one and most important (but cannot be used in some cases, of course), he can test that code in a simplified program.
A Desktop Environment consists of many parts, however, in your case, I suppose you're talking about the session manager (or window manager) which is responsible for almost everything.  So, if he were to test that, he would simply exit his current DE and use the new executable.  In case of some error, he can always keep a backup of the old executable or fix the faulty code using some commandline text editor (like vim, or nano).
Kernel
It's quite hard to test, some kernel developers just write some code and make sure it's fine and compiles, then simply let his users test (by ACK'ing the code, etc.), then it can be submitted into the kernel code.  Reasoning behind that is, the developer may not have the hardware needed to test the code.
Right now, you can compile and run the kernel in usermode (UML) if you have heard of it, so some developers may go for it.  However, some developers may also want to test it themselves (They of course back up the current kernel incase of a screw up).

A: The way to test a desktop application is related to the way of control the application unassisted or remotely.
The Cross Platform GUI Test Automation tool (I don't know if this project has a web) project helps you to chose the interfaces/libraries required to solve the problem.
In Linux[1] uses the accessibility libraries to control the application, you have Cobra[2] for Windows and PyATOM[3] for MacOS, but I don't know what kind of technology uses in this platforms.

*

*http://ldtp.freedesktop.org/wiki/

*https://github.com/ldtp/cobra

*https://github.com/pyatom/pyatom


text:
Q: Intellij will not start with the error: "Error: Could not find or load main class com.intellij.idea.Main" I killed an "idea" process in terminal after Intellij had frozen. The idea.sh script was missing after I killed the process (I ran a find command and checked other directories & the trash but no luck). I have since copied my friends "idea.sh" script into its former location. Now when I run ./idea.sh I get:

"Error: Could not find or load main class com.intellij.idea.Main".

I have tried searching for this class as well but got no results. Google has no info and I'm not very informed on Intellij.
Any hints on what I might need to do to avoid reinstalling Intellij?

A: I had the same issue after updating the android studio. I was not able to launch it from click on Android Studio icon and after running ./studio.sh it was giving me the same error
I do this to solve my issue
I downloaded the studio and install it in the new directory.

After installation success, copy all the files & folders and paste and replace it into the old location where the studio was installed.

And it is working fine.


text:
Q: Checkbox Toggle button: Activate TADOQuery when image is checked I'm doing a toggle switch, that when I click it changes its On/off state, I created it by overriding the Paint method in TCanvas, everything fine but the borders looked pixelated.
So I modified the component to load an image for each state depending on the checked of the image, in short I'm putting a TImage component inside a Checkbox inherited from TwwCheckbox
But when the image is pressed/clicked/checked, the Checked changes its state to true but it doesn't show the state that was saved in the database the next time I reopen the form, I mean, if I activate the toggle it is saved with an S and when opening the form where the Toggle is, it should be On and not off
{here I create the toggle in runtime and assign it a datasource
to connect it to the database}
procedure TForm1.FormCreate(Sender: TObject);
begin
   ToggleButton:= TinToggleButton2.Create(Self);
   ToggleButton.Name := 'ToggleButton';
   ToggleButton.Parent:= Self;
   ToggleButton.Left:= 200;
   ToggleButton.Top:=100;
   ToggleButton.Visible:= true;
   ToggleButton.ValueChecked:= 'S';
   ToggleButton.ValueUnchecked:= 'N';
   ToggleButton.DisplayValueChecked:= 'S';
   ToggleButton.DisplayValueUnchecked:= 'N';
   ToggleButton.DataField:= 'TAutoSave';
   ToggleButton.DataSource:= dsToggleButton;
   ToggleButton.DataSource.DataSet:= qryToggleButton;
end;

//here the query
procedure TForm1.Button1Click(Sender: TObject);
begin
  qryToggleButton.Active:= true;
end;

//i send the data to database
procedure TForm1.Button2Click(Sender: TObject);
begin
  qryToggleButton.Post;
end;

{here I create the component in another unit where the click event is
to switch between image}
constructor TinToggleButton2.Create(AOwner: TComponent);
begin
  inherited;
  Width:= 34;
  Height:= 15;
  Image:= TImage.Create(Self);
  Image.Visible:= true;
  Image.Picture.LoadFromFile('toggle_Toggle1.ico');
  Image.Parent:= Self;
  Image.OnClick:=Self.Image1Click;
  Self.Checked:= false;
 Checked:= false;
end;

procedure TinToggleButton2.Image1Click(Sender: TObject);
begin
   if DataSource <> nil then
    begin
      DataSource.Edit;
      if Self.Checked then
        begin
           Self.Checked:= false;
           DataSource.DataSet.FieldByName(DataField).Value:= ValueUnchecked;
           Image.Picture.LoadFromFile('toggle_Toggle1.ico');
        end
   else
      begin
         Self.Checked:= true;
         DataSource.DataSet.FieldByName(DataField).Value:= ValueChecked;
         Image.Picture.LoadFromFile('toggle_Toggle2.ico');
      end;
  end;
end;

I create the toggle in runtime but I put the other components such as the TwwDataSource and the TADOQuery in the form and I assign the DataField and the DataSource to the checkbox


text:
Q: How to conveniently find local HTML documentation? There are many doc packages in the repositories which provide documentation in HTML.
Is there an easy way to find locally installed HTML documentation, like info or man?
I guess I should clarify this a little.
The question is not about opening an HTML file. There are plenty of browsers out there and they do it pretty well.
The question is about working with the whole farm of documentation files on my computer, HTML docs in particular.
Among /usr/share/doc/* there are man pages, info files, some plain text files and a bunch of HTML files.
To look up information in man pages we use man utility, or info -- it looks through man too. But the situation with HTML docs is like if you had man pages on your computer but no man utility!
So, since there are HTML docs, there also could be a tool to work with them (to search for the documentation you need etc <-- and would be nice to have fuzzy search for that). Does such a tool exist?

A: you can view the local .html with any browser.

A: For the moment, no. You need to manually search using *.html | grep "what you want". The man and info utilities have their own databases maintained which is not the case of HTML documents.

A: The tools to browse local documentation are dhelp, dwww and some more (yelp in Gnome). You can find more of them in the wiki of the doc-base package.
doc-base registers documentation on the computer and all those programs are clients of this information.
Also, you can always navigate your broweser to: file:///usr/share/doc/ or any other directory and view html files from there. This way you avoid hassle with opening browser each time.


text:
Q: wcf throwing error on android client post I am getting this message when executing a client post from an android device (evo 4g).
--Data at the root level is invalid. Line 1, position 1.: 1
This web service is working for a microsoft client written in c#. Here is the Service Contract--
[OperationContract(Name="simpleGet")]
    [WebInvoke(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "resource/{username}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
string GetData(string username);

and here is the android client code--
HttpClient httpclient = new DefaultHttpClient();
                  String url = "http://dev.journalr12.com/RestService.svc/resource/yegua";
           HttpPost httppost = new HttpPost(url);
       httppost.addHeader("userpass", "20,yeguacreek,date,10-1-10,none");
           String result="";
           // Execute the request
           HttpResponse response;
                String xml = entryXML.sqlXML(entryData) ;

       StringEntity se = new StringEntity(xml);
       se.setContentType("text/xml");

      se.setContentEncoding("utf8");

       httppost.setEntity(se);

               response = httpclient.execute(httppost);

               // Get hold of the response entity
               HttpEntity entity = response.getEntity();
               if (entity != null) {

                              InputStream instream = entity.getContent();
                              result= convertStreamToString(instream);
                             String a = "";
               }

                return result;

After building the microsoft client and experiencing the different exceptions that would get thrown, I don't think this is making it to the getData function. I would love some suggestions.

A: This problem was caused by the xml stream not able to be read by a DataSet read operation. I thought I could put together the xml in the same way the Microsoft client DataSet did in the writexml operation. Linq to xml works much better!


text:
Q: Why does Lucene's IndexWriter updateDocument method take only one Term in its parameters? I have noticed that the updateDocument method takes only one Term in its parameters.
I find it strange because the deleteDocument can take multiple terms or even a query to select the document(s) to be deleted...
Why does updateDocument not let us specify more than one Term ? Is there a technical reason behind it or is it just that it hasn't been implemented yet ?

A: Disclaimer: I did not write this code nor I know the exact reasons, so I can only guess.
First of all, update in Lucene has always meant combination of delete + insert whereas delete has always been single operation. Yes, update is now atomic but you still need to .commit() for changes to take effect.
Secondly, I guess it's hard to design clean API for updating multiple documents. For each document (which itself is a collection of fields) you would have to pass a collection of terms, so for multiple documents you would have to have a collection of collections (or a specially designed command object), yuck. And when in doubt, leave it out! What's wrong with asking a customer to have a loop? It's not that complex really.


text:
Q: What is the $_SERVER variable $_SERVER["HTTP_TE"]? As I'm trying to configure my server, I made a var_dump of $_SERVER and noticed an (to me and a quick Google) unknown variable: what is the $_SERVER variable $_SERVER["HTTP_TE"]?

A: See the manual:

All HTTP headers sent to the script are made available through the $SERVER array, with names prefixed by 'HTTP'.

HTTP_TE will be a TE header sent by the client.

The TE request header specifies the transfer encodings the user agent is willing to accept. (you could informally call it Accept-Transfer-Encoding, which would be more intuitive).