C# Small database project with sql server ce

Question: I am developing a simple database desktop application using windows forms and c#. I have decided to use Sql Server CE for my app. I am using following things:
1) Sql server ce 4.0
2) .net framwork 4.0
3) ms visual studio 2010
Now sorry but I have a thousand questions to ask
1) Is my choice of sql server ce correct or what are the alternatives
2) Basically i have developed apps on android and there i dont need to check if the database is already created or not but here in forms apps, do i need to:
a) check if the database is already created
b) then check if all tables have been created
c) can i do the above two steps( a and b ) just by checking if my sdf already exists and be rest assured
3) Do I need to have .net installed on my client's pcs or my app is a stand alone one( because i used sql server ce - no sql server installation)
Buddies these all questions have made me puzzled.
Please help and share your experiences.
Cheers and thanks in advance!!!
Comment: did you find an answer to your question?
Comment: Ya I did but didnt accepted any answers because I think all three are right up there. What to do in such case???
Answer:
Depends on the nature of your program. Understand that SQL CE is most suitable for deployed client applications as SQL CE can be privately deployed.
When your program first loads,  you should check if the database file already exists. If the database does not exist you should create the database and create the appropriate tables like this.
The client machine must have the net framework installed! In addition, you will either have to require that the end-user has a public installation available or privately deploy the appropriate class libraries with your applications.
Answer: 1) It is correct
2) c) should be enough - just create your db when there is no sdf - as long as the tables are always the same it is ok.
3) Yes because you're developing a .NET application. Use of SQL CE does not change anything. Your client machines will need .NET 4.0 installed. SQL CE itself doe not have to be installed - you need to include all the SQL CE files within your app. All files needed are in the 'private' folder in the SQL CE package.
Answer: 1) Is my choice of sql server ce correct or what are the alternatives

I would say it depends on your need or requirement. But SQL Server CE
  has limitations specially you can store upto 4GB data. So before
  choosing the database think of your need.

2) forms apps, do i need to: a) check if the database is already created b) then check if all tables have been created.

Not necessary, But during the database operations if those are not available you can display message.

3) Do I need to have .net installed on my client's pcs or my app is a stand alone one( because i used sql server ce - no sql server installation)

Yes, Client machine should have .net frame work installed. But .net
  frame is packed with windows OS. But you have to make sure right
  version is available. If you are building MSI package it will do it
  for you, It can check .net frame work version exist in the client
  machine.


CardView styling not showing on device

Question: I am trying to make a custom style for a cardview on my activity. It works just as I want to in Android Studio. But when I run it on my device - Galaxy S7 Edge android 7.0 - the cardview attributes are not changing. It uses the background from the style of the layout, and the rest of the attributes - elevation, corner radius and card background seem to be ingnored.
I dont get any errors in the log.
The layout uses style="@style/AddItemStyle"
The card uses style="@style/AddItemStyle.CardView"
Thats the card style

Thats the layout style

In android studio
On my phone
Answer: For some reason removing android:theme="@style/AddItemStyle" from the activity in manifest fixed the problem. I don't know why but it worked.

CardView styling not showing on device


What is the conditional probability of variables in a multivariate gaussian?

Question: Given $Y = [Y_1, Y_2, \ldots, Y_n]^T \sim N(0, \Sigma)$. That is $f_{Y}(y_1, y_2, \ldots, y_n)$ is a multivariate gaussian with mean $0$ and covariance matrix $\Sigma$.
I'm asked to compute the conditional correlation of $y_i, y_j$ given $y_k$, that is $\rho(y_i, y_j | y_k)$. I know that in order to do this, I need to compute $$E[y_i \cdot y_j|y_k] = \int_{-\infty}^{\infty} y_i \,y_k \,\, f(y_i, y_j | y_k) \,d$$.
How can I compute $f(y_i, y_j | y_k)$? I know that this expression can be computed by
$$f(y_i, y_j | y_k) = \frac{f(y_i, y_j)}{f(y_k)}$$
But I'm not sure how to find these expressions in closed form.
Comment: I would take a look at the [Schur Complement](https://en.wikipedia.org/wiki/Schur_complement), in particular the section labeled "Applications to probability theory and statistics."
Answer: The Schur Complement, is the goto for this kind of computation.  Let $Y \sim \mathcal{N}(0,\Sigma)$, where $Y$ and $\Sigma$ are organized such that the last element and row/column belong to the variable you wish to condition on.  Then, $Y_{-k}|Y_k$ is distributed, $\mathcal{N}\left(\mu_{-k}, \Sigma_{-k}\right)$, where

$Y_{-k}$ consists of the elements of $Y$ not including $k$;
$\Sigma = \left( \begin{array}{rr}
A & B\\ B^{T} & C\\
\end{array} \right)$ in slightly R'ish parlance $A = \Sigma[-k,-k]$, $B=\Sigma[-k,k]$, and $C = \Sigma[k,k]$;
$\Sigma_{-k} = A - BC^{-1}B^T$;
and $\mu_{-k} = BC^{-1}Y$.

The covariance of $Y_i$ and $Y_j$ given $Y_k$ can then be retrieved from $\Sigma_{-k}$.  A fast way to calculate this numerically is through the sweep function (Dempster 1969).
Dempster, A.P. (1969). Elements of continuous multivariate analysis. Reading, MA: Addison- Wesley.


How to change path using the Content: Link to Content

Question: In Block view I want to set the link of content with the title name
How to Rewrite Results using the Content:Link to Content?
Example showing node/8 to john-bartlett(content title name)
By using this {{ view_node_1 }} i am getting the node/8 path but i want the title name john-bartlett.

Please provide any solution regarding this
Comment: Try like this {{ title }} . It will display title with link to content for node/8.
Comment: @ajay its giving me the path of node like project_name/node/8. Its working fine but i want to know how to change with title name
Please provide solution for this . I am trying for long time
Comment: Do you want project_name/TITLE of node to redirected to node page?
If yes have you added alias for that?
Comment: yes i want to add project_name/TiTLE  space replaces with dashes in title using content:link to content
Comment: is I have to set custom  url alias every time when added the content ?
Comment: I am so close to the answer .is I have to set pattern for this like /artists-details/[node:title]?
Answer: Download Pathauto module. After installing go to http://YOURSITE/admin/config/search/path/patterns and click add patterns like below.

After adding pattern go to http://YOURSITE/admin/config/search/path/update_bulk and select content and check "Regenerate URL aliases for all paths" and click update. After this, ALL your node path alias should be generated with the title of that nodes.
Then in rewrite result's add this line:
{{ title }}

All your links and tags will be on your node titles.
Comment: i Have set the node[node:title] .its showing blank when added the content in specify content type like artists. And install the  Pathauto module.
Comment: Does your node has default title of any other field using as title?
Comment: Click on browse available tokens and check for your title in that and replace that with [node:title] if your using another field as title in artists content type
Comment: I think i miss this step http://d8.local/admin/config/search/path/update_bulk
Comment: http://YOURSITE/admin/config/search/path/update_bulk
Comment: task done @ajay it was great help from your site. i will submit  your answer as accept able and give you upvote after 15 repuation.


Are Audio Interfaces required for recording distorted guitar?

Question: Previously, when recording a basic guitar song, I would plug my guitar directly into my computer using a basic line-in adapter.
This still works if I add my amp into the mix. Specifically, when the headphones output of my amp is plugged into the line-in of my computer. However, when I add my RAT distortion pedal into the input of the amp, the sound becomes terrible with only the fuzzy highs being captured/recorded.
Do I need an Audio Interface to record my distorted guitar using a computer?
Answer: The first thing you want to check is to listen with a pair of headphones directly from the amp when the Rat pedal is hooked between your guitar and the amp. If the sound in the headphones is the way it's supposed to be then the problem is probably the level reaching the computer is too high. An audio interface will allow you to set the gain (recording level) for recording but a computer sound card doesn't have that feature so you have to use your external equipment (amp and pedal) to set a good level. Check the input meters on your DAW and make sure they are not spiking too high. Use your volume controls on the pedal and on the amp to set the volume and make sure you're getting signal but the VU meter in the DAW isn't hitting the top. When recording digitally it is better to record too soft than too loud because digital distortion is awful!
Computer sound cards are capable of being used with a DAW for recording but they do not have great sound quality and almost no features so eventually you may want to invest in an inexpensive 2 input sound card. They start at around $100 and you can probably even find one cheaper if you shop used.
Comment: Just to add on this good answer: computer sound cards are also not very good in terms of latency, which can be a problem for monitoring or overdubbing over an existing track.
Answer: What is the output of the amp? Is it line out? In such case you're omitting a very important component which is the speaker or cabinet.
Guitar speakers typically don't reproduce high frequencies (above several kHz) well. This plays crucial role in shaping distorted sound, which has very rich high frequency spectrum, which in most cases is not what we want to hear. This might be what you call "fuzzy highs".
An obvious solution is to record the speaker sound via a microphone. Alternatively, there are many ways to emulate guitar speaker in the digital domain. The simplest solution is to apply a low pas equalizer, but presently the most common method is to convolve the signal with an impulse response (IR) of the guitar cabinet.
There are many free and non-free programs and plugins to do this. Search the internet for phrases like "cab simulation", "guitar IR", "cab impulse response", "impulse response loader" etc...


How i can rotate a $m$ dimensional vector?

Question: I have an $m \ge5$ dimensional vector $x$. How i can construct a rotation matrix $A$ s.t: $x \cdot A$ would be a vector rotated by $\theta$ angle. This is trivial for 2 dimensions, but what for this case? For instance will it work if A is this:
$A = \begin{bmatrix}
cos \theta & -\sin\theta&0&0&0 \\
\sin\theta&-\cos\theta&0&0&0\\
0 & 0&cos \theta & -\sin\theta&0\\
0 & 0&sin \theta & cos \theta&0\\
0&0&0&0&1\\
\end{bmatrix}$
and i work in 5 dimensions? This matrix i assume that is says rotate with respect to the first plane of the two first dimensions by $\theta$ then rotate again with the same $\theta$ the other two. But what about the last one? Also what if i want to combine dimension 1 and 4 in order to rotate with respect to this plane?
Comment: Rotations aren't performed around axes; they're performed in planes.
Comment: You want to rotate by $\theta$ around what?
Comment: Around any two axis of the `m` of my choise
Comment: ok, then around the planes formed by any two dimensions
Answer: It's relatively easy to construct such a rotation map using clifford algebra; the hardest part is probably learning the clifford algebra itself.  However, if you can wrap your head around it, it's a very powerful tool to use for geometric problems in higher dimensions.

Clifford, or geometric algebra, is built upon a geometric product of vectors that obeys the following properties.  Let $e_1, e_2, e_3, e_4, e_5$ be a standard, orthonormal basis, let $i, j \in \{1, 2, 3, 4, 5\}$.  The geometric product has at its most basic form
$$e_i e_j = \begin{cases} 1, & i = j \\ -e_j e_i, & i \neq j \end{cases}$$
Along with associativity, distributivity over addition, and so on.
A key concept in GA is that of grading.  Like exterior algebra, GA assigns whole sets of geometric products of vectors a grade, based on reducing any pairs of the same vectors.  For instance, the geometric product $e_1 e_3 e_4 e_1 e_5 e_2 e_2$ is said to be grade-3.  Observe:
$$\color{red}{e_1} e_3 e_4 \color{red}{e_1} e_5 \color{blue}{e_2 e_2} = (-1)\color{red}{e_1} e_3 \color{red}{e_1} e_4 e_5 \color{blue}{(1)} = (-1)(-1)\color{red}{e_1 e_1} e_3 e_4 e_5 = \color{red}{(1)}e_3 e_4 e_5$$
This cannot be reduced through annihilation of basis vectors any further, so it is grade-3, called a trivector.  A geometric product actually consists of several grades.  Consider two vectors $a$ and $b$ in a 2d space:
$$\begin{align*}ab &= a^1 b^1 e_1 e_1 + a^2 b^2 e_2 e_2 + a^1 b^2 e_1 e_2 +  a^2 b^1 e_2 e_1 \\ &= (a^1 b^1 + a^2 b^2) + (a^1 b^2 - a^2 b^1) e_1 e_2 \\ &\equiv \langle ab \rangle_0 + \langle ab \rangle_2\end{align*}$$
You'll note that $\langle ab \rangle_0$ is precisely the dot product, while $\langle ab \rangle_2$ is similar to a cross product in terms of its components.  For this reason, the geometric product of two vectors is also often written as
$$ab = a \cdot b + a \wedge b$$
The wedge product being similar to a cross product, but inspired more by its exterior algebra counterpart.

With the geometric product in hand, there is a handy rotation formula.  Let $\hat B$ be a normalized bivector describing the rotation plane.  (This can be done through a geometric product of orthonormal vectors in the plane.)  The rotation of a vector $c$ is
$$\underline R(c) = c \cos \theta - \hat B \langle \hat B c\rangle_3 (1 - \cos \theta) - \langle \hat B c \rangle_1 \sin \theta$$
This is exactly an analogue of the Rodrigues rotation formula.  I will work an example.
Let $\hat B$ be the plane spanned by the vectors $e_1$ and $(e_3 + e_4)/\sqrt{2}$.  Then $\hat B = e_1(e_3 + e_4)/\sqrt{2}$, or $(e_1 e_3 + e_1e_4)/\sqrt{2}$.
You could be very vanilla here and only input basis vectors for $c$ so you can eventually extract a matrix, but I'll do something harder and input $c = e_2 + e_4$ just for fun.
First we compute $\hat B c$:
$$\hat B c = \frac{e_1 e_3 + e_1 e_4}{\sqrt{2}} (e_2 + e_4) = \frac{1}{\sqrt{2}} (e_1 e_3 e_2 + e_1 e_3 e_4 + e_1 e_4 e_2 + e_1)$$
The first three terms make up $\langle \hat B c \rangle_3$, so now we compute $\hat B$ multiplied with them.
$$\begin{align*}\hat B \langle \hat B c\rangle_3 &= \frac{1}{2} (e_1 e_3 + e_1 e_4)(e_1 e_3 e_2 + e_1 e_3 e_4 + e_1 e_4 e_2) \\ &= \frac{1}{2} (-e_2 - e_4 + e_3 - e_2) \\ &= -e_2 + \frac{e_3 - e_4}{2}\end{align*}$$
This allows us to compute, then, for any angle $\theta$, the overall rotation to be
$$\underline R(e_2 + e_4) = (e_2 + e_4) \cos \theta - \left(-e_2 + \frac{e_3 - e_4}{2} \right)[1-\cos \theta] - \frac{1}{\sqrt{2}} e_1 \sin \theta$$
I hope this example has convinced you that geometric algebra is a useful tool for doing geometric problems, whether in 3d or beyond.  There's a lot of stuff involved in just proving that extension of the Rodrigues formula, all made possible through the geometric product.  You can most certainly extract a matrix from these expressions by inputting basis vectors and looking at components.
Comment: I got lost with this answer...
Comment: What is '$\langle \hat B c \rangle_3$'?
Comment: $\hat B \wedge c$, the 3-vector formed by the plane $\hat B$ and the part of $c$ orthogonal to that plane.  Think of a parallelepiped.  In 4d, there are several such objects, unlike in 3d where each parallelepiped is essentially a scalar multiple of all the others.  The expression $\hat B \langle \hat B c \rangle_3$ means "take the plane $\hat B$, form a parallelepiped using $c$, and then find the part orthogonal to $\hat B$."   Essentially, it's just a way of finding $c_\perp$.
Answer: A rotation in the plane $\mathbb{R}^2$ is determined by a fixed point and a rotation angle around that point. A rotation in 3-dimensional space $\mathbb{R}^3$ is determined by a fixed line and a rotation angle around that line. The common generalization of this is that a rotation in $m$-dimensional space is determined by a fixed $m-2$ dimensional affine subspace and a rotation angle around that subspace. So just specifying a vector and a rotation angle is not enough information to determine the rotation. What you need to specify is the fixed subspace and the rotation angle.
Also, you ask for a rotation of the form $x \cdot A$, and this means that the fixed $m-2$ dimensional subspace is a linear subspace $V$. Let's say that you specify $V$ and the rotation angle $\theta$. Here's how to derive the matrix $A$.
Let $e_1,\ldots,e_m$ be the standard basis for $\mathbb{R}^m$ (written as column vectors). Let $b_1,\ldots,b_m$ be any orthonormal basis for $\mathbb{R}^m$ (again written as column vectors) such that $V = Span\{b_3,\ldots,b_m\}$ (however $V$ is specified you'll have to compute this basis $b_1,\ldots,b_m$, perhaps by the Gram-Schmidt process). Putting this basis in the columns of a matrix $M$ you get a linear transformation that maps the $n-2$ dimensional subspace $Span\{e_3,\ldots,e_m\}$ to the subspace $V$. Let $R$ be the $m \times m$ matrix that you get from the identity matrix by replacing the upper left $2 \times 2$ submatrix by the standard rotation matrix $(\cos(\theta),\sin(\theta);\sin(\theta),\cos(\theta))$, so this $R$ represents the rotation of angle $\theta$ with fixed subspace $Span\{e_3,\ldots,e_m\}$.
Then the matrix you want is
$$A = M R M^{-1}
$$
Geometrically this works because this formula says: map $R$ back to $Span\{e_3,\ldots,e_m\}$, rotate around that by $\theta$, and them map $Span\{e_3,\ldots,e_m\}$ back to $R$; the result is a rotation of angle $\theta$ around $R$.
Comment: Can you give a simple example say in 5D of how to construct this? Many Thanks


ScrollView Not Scrolling to The End of The View

Question: In my ViewController i added a ScrollView and a view inside the ScrollView using StoryBoard (set constraints on ScrollView and the View). now in my code i am using the View to add other views dynamically. the views are being added but my question is related to scrolling. i am able to scroll but it is not scrolling to the last view... i tried doing the following
override func viewDidLayoutSubviews() {
    ScrollView.contentSize.height = contentView.frame.height
}

but this did not work, also i noticed that the content view (view i am adding views to) height is printing 736 in viewDidLayoutSubviews() even when i add more views which of course should increase its size.
please any help would be appreciated.
i am adding the views to content view like this:
let Description = UILabel(frame: CGRectMake(20, CGFloat(position), self.view.frame.size.width-40, 40))
Description.addConstraint(NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 40))
Description.addConstraint(NSLayoutConstraint(item: view, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: self.view.frame.size.width-40))
contentView.addSubview(Description)
// i don't know if i should add constraints but i added anyway

Answer: it worked!
edit the viewDidLayoutSubviews like this:
 override func viewDidLayoutSubviews() {

        self.view.setupContentViewForViewWithScroll(contentView: contentView)

        let lastView : UIView! = contentView.subviews.last
        let height = lastView.frame.size.height
        let pos = lastView.frame.origin.y
        let sizeOfContent = height + pos + 10

        ScrollView.contentSize.height = sizeOfContent

    }

Comment: Thanks for the great help


Canvas create javascript object with methods

Question: Hi there i am starting javascript and a find some problems with objects.
I make a nice signature canvas, but now i need to transform to a object with methods...
Here my canvas code:

const canvas = document.querySelector("#canvas");
const contenu = canvas.getContext("2d");
canvas.width = 150;
canvas.height = 80;
let signer = false;

function demarrer(e) {
  signer = true;
  dessiner(e);
}

function arreter() {
  signer = false;
  contenu.beginPath();
}

function dessiner(e) {
  if (!signer) return;
  contenu.lineWidth = 2;
  contenu.strokeStyle = "#000";

  contenu.lineTo(e.offsetX, e.offsetY);
  contenu.stroke();
  contenu.beginPath();
  contenu.moveTo(e.offsetX, e.offsetY);
}
canvas.addEventListener("mousedown", demarrer);
canvas.addEventListener("mouseup", arreter);
canvas.addEventListener("mousemove", dessiner);
#canvas{
border: 2px solid #000;
}

<canvas id='canvas'></canvas>

and here my object 'project'

const canvasElts = {
  canvas: document.querySelector("#canvas"),
  cont: this.canvas.getContext("2d"),
  signer: false,

  dessiner: e => {
    this.canvas.addEventListener("mousemove", e => {
      if (!this.signer) return;
      this.cont.lineWidth = 2;
      this.cont.strokeStyle = "#000";

      this.cont.lineTo(e.offsetX, e.offsetY);
      this.cont.stroke();
      this.cont.beginPath();
      this.cont.moveTo(e.offsetX, e.offsetY);
    });
  },

  demarrer: e => {
    this.canvas.addEventListener("mousedown", e => {
      this.signer = true;
      this.dessiner(e);
    });
  },

  arreter: e => {
    this.canvas.addEventListener("mouseup", e => {
      this.signer = false;
      this.cont.beginPath(e);
    });
  },

  eventCanvas: () => {
    this.canvas.width = 150;
    this.canvas.height = 80;
    this.arreter;
    this.demarrer;
    this.dessiner;
  }
};
canvasElts.eventCanvas();
#canvas{
border: 2px solid #000;
}

<canvas id="canvas"></canvas>

the problem is i dont have any console error to help me find the good way...
If some one can help me it would be so great.
thx
Comment: 1. declaring an Object isn't enough, you need to actually call its methods for anything to happen at all 2. your code logic seems off; event handlers are supposed to be added exactly once, not multiple times
Comment: 1. i was calling the object in another js file... i added to the snippet and for the logic i now i am off its because i am here :)
Comment: I guess you need `canvasElts.eventCanvas();` ES6 class example: https://jsfiddle.net/khrismuc/68c1b92d/ And an old school version: https://jsfiddle.net/khrismuc/8ox9e3rf/
Comment: Ok, I need to do a constructor... i was thinking i dont because i need only one canvas. i will try to do the same without watch your exemple again :) A big thx to you.
Comment: You can use your code, but `this.arreter;` for instance does nothing, you, again, need `this.arreter();`
Comment: If i change => Uncaught TypeError: this.arreter is not a function
    at Object.eventCanvas (canvas.js:36)
Answer: first don't use arrow function ()=>{} inside the object use normal function insteadfunction(){}
second call these method
/* not */ this.arreter; /*Do this*/ this.arreter();
/* not */ this.demarrer; /*Do this*/ this.demarrer();
/* not */ this.dessiner; /*Do this*/ this.dessiner();

there is the correct way of doing that
const canvasElts = {
    canvas: document.querySelector("#canvas"),
    cont: this.canvas.getContext("2d"),
    signer: false,

    dessiner: function(e) {
      this.canvas.addEventListener("mousemove", e => {
        if (!this.signer) return;
        this.cont.lineWidth = 2;
        this.cont.strokeStyle = "#000";

        this.cont.lineTo(e.offsetX, e.offsetY);
        this.cont.stroke();
        this.cont.beginPath();
        this.cont.moveTo(e.offsetX, e.offsetY);
      });
    },

    demarrer: function(e) {
      this.canvas.addEventListener("mousedown", e => {
        this.signer = true;
        this.dessiner(e);
      });
    },

    arreter: function(e) {
      this.canvas.addEventListener("mouseup", e => {
        this.signer = false;
        this.cont.beginPath(e);
      });
    },

    eventCanvas: function() {
      this.canvas.width = 150;
      this.canvas.height = 80;
      this.arreter();
      this.demarrer();
      this.dessiner();
    }
  };
  canvasElts.eventCanvas();

Comment: the name of `()=>{}` is arrow function read about it here [when 'not' to use arrow function](https://dmitripavlutin.com/when-not-to-use-arrow-functions-in-javascript/)


How to get $E[\int_{t}^T2B_sdB_s|\mathcal{F}_t]=0?$

Question: I am computing the following Ito integral
$$
E[\int_{0}^T2B_sdB_s|\mathcal{F}_t]=E[\int_{0}^t2B_sdB_s+\int_{t}^T2B_sdB_s|\mathcal{F}_t]
$$
$$
=E[\int_{0}^t2B_sdB_s|\mathcal{F}_t]+E[\int_{t}^T2B_sdB_s|\mathcal{F}_t]
$$
the first term $\int_{0}^t2B_sdB_s$ is independent of $\mathcal{F}_t$, then $E[\int_{0}^t2B_sdB_s|\mathcal{F}_t]=\int_{0}^t2B_sdB_s$.
But how to get
$$
E[\int_{t}^T2B_sdB_s|\mathcal{F}_t]=0?
$$
Comment: Use that $\int_0^T2B_s\,dB_s$ is a martingale.
Answer: Use Ito on $B_t^2$, and you find out that $d(B_t^2)=2B_tdB_t+dt\implies \int_{[t,T]} 2B_sdB_s=B_T^2-B_t^2-(T-t)$. By using the fact that $E[B_T^2-B_t^2|\mathscr{F}_t]=(T-t)$, the claim follows.


Should I remove electric guitar cord daily after practice?

Question: A friend of mine suggested that I leave the cord plugged into the guitar. Removing and inserting the cord daily for practice may damage it and reduce its life. Is it okay that I leave my guitar connected to the amp always and just switch off the amp supply, and turn it back on the next day for practice?
Answer: This should not be a problem, although there is no harm in unplugging the instrument. The instrument jacks and the cord are very durable. One danger with leaving it plugged in while you are not holding the guitar is that you might trip over the cord, which could pull on the guitar and knock the guitar off its stand, which might damage the guitar.
Furthermore, players sometimes, while standing up and playing the guitar, accidentally step on the cord and yank it out of the jack on the guitar. That could lead to damaging the cord (and it will make a very unpleasant loud sound through the amplifier).
Here is a YouTube video that shows the correct way to connect the cord to the guitar by looping it through the guitar strap to relieve the tension upon it.
Comment: Yeah, tripping over was the main reason why I used to unplug it everyday. Thanks, so I guess I will continue to do the same
Comment: I have broken the headstock of a guitar by stepping on a plugged-in cable and the pulling force tipped the guitar over and the impact cracked the headstock. +1 for pointing out that danger.
Comment: Hollow-body electric guitars like the one in the video are also prone to having the wood around the output jack ripped apart when the cable is kicked. That is less traumatic than a broken headstock, but I am sure it is expensive to repair.
Answer: While the quarter inch plug is known to be durable so that frequent unplugging should be ok, it is noteworthy that the pickup's preamp might be switched on and off by the plug. This integrated amp typically runs of a 9-volt battery (or sometimes two of them). Leaving it turned on by not unplugging the cord will therefore result in a faster discharge of the battery and a more frequent need to change it.
Note however that not all electric guitars are active, so check first before troubling yourself.
Comment: Correct, however most electric guitars do not have any preamp built in. The main reason is irrational "vintage" buzz, but this is actually a worthwhile point in favour of passive electronics: I have more than once forgotten to unplug my active bass, and ended up with an empty battery just when I needed it. (Normally, I power the active circuitry with a custom phantom power system, which eliminates the need for batteries entirely.)
Comment: @leftaroundabout, right, but then again it is quite easy to check whether it has one or not ;)
Comment: but many beginner guitarists probably never thought about it, and it wouldn't seem far-fetched to think that _every_ electric guitar must have a battery. I wouldn't want them to now start unplugging their instrument in every little pause, to avoid failure of a battery that doesn't in fact exist at all...
Comment: @leftaroundabout, sure but I guess no one is going to unplug for a cigarette break.
Comment: It is an important distinction and the rules apply differently depending on if you have a battery operated pre-amp in your guitar (as on many acoustics) or if you have passive pick up system (typical of most electric guitars).  Active battery powered pre-amp - unplug after playing to avoid depleting battery.  Passive pickup with no battery - okay to leave plugged in all the time to avoid wear on socket.
Comment: Yes, yes, you're all right. At other SE sites we're however fine to give suggestions, to not spell out all eventualities, to have people think for themselfes. I'd like to go with "Sapere aude". The answer gives just one option, one issue that might (but does not have to) occur. I maintain that anybody playing an instrument should familiarize oneself with it to the point to know whether it has a battery or not. And while this fact (battery or not) is quite easy to find out, knowing that the amp draws on the battery when the cord is plugged might be not known. Thus this advise.
Answer: 1) It does no harm to the connector in the guitar, or amp, or the connectors on the cord, to leave them plugged in.
2) If leaving the cord connected bends the cord tightly, curving it with a small radius, the cord itself or the cord-to-connector joint may be damaged. The vast majority of cord failures happen within 300mm/12inches of the end, usually right where the connector body or connector strain-relief ends. When a cord fails, cutting off that last foot or 300mm and re-attaching the connector will often revive it. Unless its been over-bent somewhere other than the ends, or stretched along a large area.
3) If you have battery operated effects boxes, a preamp in the guitar or anything else involving a battery, leaving cords plugged in to that item may leave it switched on, so you'd want to disconnect the cord and save the battery when not using the equipment.
4) Tripping over a connected cord and pulling over the instrument, amp, or both, is a constant danger. On stage or in a practice space, I might leave it connected. If there's foot traffic, disconnect. Be safe, not sorry.
Comment: I bought an active bass, and didn't really understand the relevance of having a battery for the pre-amp. It died out after four months. It has died during practice so I make sure I carry extra battery at all times and put a new one in my bass the day before a gig! GOD Bless you.


Logit Model for leaching test results

Question: I was kindly wondering whether you could shed a light onto the following concerns.

I have a data where there are 10-12 independent variable (Heavy metals) against 1 dependent variable (being hazardous or non-hazardous).
The sample size would be up to 25-30
I would like to ask whether I could use logit model to analyse the significance of heavy metals on being hazardous. I am afraid that the sample size is quite small but what would you suggest?

Thank you for all!
Comment: I am not fully sure I understand your question. You have 10-12 independent variables that represent some metals (the presence or absence? or the amount present? or what type of variables are they?) and each observation corresponds to a material that contains such metals? Please try to explain more understandably how your data is (numeric/categorical/dichotomous) and what each observation represents.
Comment: Thank you for your fast answer. These 10-12 independent variables represent the presence of a heavy metal. For instance Pb, Fe, Zn etc. And values of these variables are numeric and represent the amount of each variable in this sample.
To give a solid example: Pb - 0.01 mg/l  -----  Zn- 0.03 mg/l ----- like this 10-12 independent variables... In the end we have one dependent variable ---- output- hazardous or non hazardous. Binary variable
Answer: Logit is the right model, but the sample size is probably too small. Perhaps try first with less independent variables in the hope you find at least something (this is called stepwise regression). I guess you know that in particular for small sample sizes you need to use the deviance statics with a chi-square test to test whether a variable is significant rather than just trusting the "asterisks" of your software output generated with a Wald test.

Logit Model for leaching test results


Contador de links - sem página externa, utilizando JS onClick() ou outra solução em PHP + MySql

Question: Olá, busco ajuda para montar um contador de link. Não gostaria de utilizar uma página que de coleta, mas sim uma solução que rode em qualquer página. Exemplo em uma página com 03 links: link01.php, link02.php (que foi clicado) e link03.php, agora que o 02 foi clicado, este recurso pegaria este valor (link02.php) e colocaria em uma variável.
Answer: Pode fazer o listener de clicks com o jQuery:
<code>$('a').on('click', function(){
    alert(this.href);
});
</code>
mas para não haver bloqueio da navegação do usuário voce deve salvar no banco em uma chamada ajax:
<code> $('a').on('click', function(){
    var href = this.href;
    $.ajax({
        type: 'get',
        url: 'contador.php?href='+href,
        contentType: 'application/x-www-form-urlencoded',
        success: function(response) {

        },
        error: function(xhr, error) {

        }
    });
});
</code>
Comment: Olá @marcelobns, verifiquei que há um link contador.php no teu código, eu devo ter uma página onde todos os links vão passar por ele? Desculpe, não está claro pra mim, obrigado pelo retorno.
Comment: @EduardoCorreia o contador.php vai ser onde você vai salvar no seu banco o link que foi clicado


How to create a dynamic ui Rshiny

Question: I am a newbie in Rshiny, right now I try to design a dynamic ui Rshiny. Attached is my ui.R and server.R. It runs out an error. This is a dataset storms in different years.
ui.R
library(shiny)
library(hurricaneexposure)
library(hurricaneexposuredata)

data("hurr_tracks")
storms <- unique(hurr_tracks$storm_id)
storm_years <- as.numeric(gsub(".+-", "", storms))
storms <- storms[storm_years <= 2011]

years <- unique(storm_years)
years <- years[years<=2011]

## Split storm_id based on same year
stm <- split(storms, gsub(".+-", "", storms))

shinyUI(fluidPage(

  # Application title
  titlePanel("Hurricane"),

  sidebarLayout(
    sidebarPanel(
      selectInput("years",label = "years",years),

  # This outputs the dynamic UI component
      uiOutput("ui")
    ),
  mainPanel()
  )

))

And
server.R
shinyServer(function(input, output) {

output$ui <- renderUI({

switch (input$years,
  "1988"=selectInput("storm_id",label="storm_id",stm$`1988`)
)

})

As you can see in the ui part. I create variables "years" and "stm". "years" includes all years from 1988 to 2011. "stm" is a split dataset which is to split storms based on years.
> head(stm)

$`1988`
[1] "Alberto-1988"  "Beryl-1988"    "Chris-1988"    "Florence-1988" "Gilbert-1988"  "Keith-1988"
$`1989`
[1] "Allison-1989" "Chantal-1989" "Hugo-1989"    "Jerry-1989"

MY goal is to create two "selectInput" whose names are "years" and "storms".
In selectInput for years, I can select years from 1988 to 2011, for example, if I select 1989, then the second selectInput will show only the storms in 1989, which are
"Allison-1989" "Chantal-1989" "Hugo-1989"    "Jerry-1989"

Any good suggestions?
Comment: I'm also new to shiny and I had this question too. What I did is I create a reactive element that reacts to the change in your input (ie. input$years) and creates a subset of the data based on that. Something along the lines of df[df$year == input$years,] inside a reactive.
Answer: You should look into updateSelectInput, which is a function that lets you change your selectInputs that are already rendered on the ui side.
Look at this page for more detail.
With this, you can have a proxy selectInput for the storms and whenever the year input changes, you can alter the choices for the selectInput to the right ones.
Sorry, I could not test my solution, because I don't have your data sets. But try out the idea and comment + ask, if this isn't working for you.
library(shiny)
library(hurricaneexposure)
library(hurricaneexposuredata)

data("hurr_tracks")
storms <- unique(hurr_tracks$storm_id)
storm_years <- as.numeric(gsub(".+-", "", storms))
storms <- storms[storm_years <= 2011]

years <- unique(storm_years)
years <- years[years<=2011]

## Split storm_id based on same year
stm <- split(storms, gsub(".+-", "", storms))

ui <- shinyUI(fluidPage(
  # Application title
  titlePanel("Hurricane"),
  sidebarLayout(
    sidebarPanel(
      selectInput("years", label = "years", years),
      selectInput("storm_id", label = "Storms", choices = NULL)
    ),
    mainPanel()
  )
))

server <- function(input, output, session) {
  observeEvent(input$years, {
    updateSelectInput(session, "storm_id", choices = stm[[input$years]])
  })
}

shinyApp(ui, server)

How to create a dynamic ui Rshiny


Why are the seats of the Olympic track and field stadium different colors?

Question: With nobody in the seats, it can be plainly seen that the seats in the Olympic track and field stadium in Tokyo are of four different colors (maroon, light green, dark green, and white) in no discernible pattern.

Is there a reason the seats are these colors? Is there actually some pattern or logic to how they are arranged? If not, why not just use seats that are all one color, or put them in some sort of tidy pattern, such as a row of maroon seats, a row of white seats, etc?
Answer: While most US stadiums have single colored seats, the multicolor effect is used in many stadiums around the world.  The New Orleans Superdome has multicolored seats, but the overall effect is very muted rather than vibrant.  Probably there are different reasons in different places, but breaking up empty seats for television does come in handy.  It also means that if you have some color fade and have to replace a seat, you don't get blotchy effects from mismatched replacements.
Slate magazine had a piece on the Tokyo stadium and Kengo Kuma's design.  He doesn't say that it's the reason for the pattern, but does acknowledge that it looks good without people in the seats.

The stadium design, in which the 60,000 seats are colored in five
different earth tones to create a forest-pattern mosaic, makes the
stadium look occupied and alive even without spectators. "The mosaic
design is a natural solution to the problem of no spectators at the
Olympics," Kuma told me during a recent interview. "By accident, the
idea is perfectly fitting the situation with COVID."

A Stephen Wade AP article in 2019 says that there is actually a pattern to the arrangement.

The stadium seating rises in a steep gradient from the field level and
the nine-lane track, getting steeper the higher it goes. The colors of
the seats also get lighter the higher up you go with more brown seats
near the bottom — the earth — and more green, gray and white near the
top.
"Because of the gradient, it creates an atmosphere where people can
feel close," said Takeo Takahashi, another Japan Sport Council
spokesman.


Using a while loop to calculate the factorial of user input

Question: I'm trying to make while loop that calculates the factorial of user's input number. But now my program takes the factorial of the first input number and uses that result when calculating the next factorials. Any ideas on how to fix it?
This is what I have so far:
factorial=1
n=1
while True:
    num=int(input("Enter number: "))
    if num<=0:
        print("Thank you!")
        break
    while n<num:
        n+=1
        factorial*=n
    print(factorial)

Answer: factorial and n values are not reset to their default values in your loop. They store the values of previous iteration and use them in the current iteration.
You must include the factorial and n inside the while loop
while True:
    n = 1
    factorial = 1
    num=int(input("Enter number: "))
    if num<=0:
        print("Thank you!")
        break
    while n<num:
        n+=1
        factorial*=n
    print(factorial)

Answer: There are many ways to do it, but keeping your code same, you need to reset the values of factorial and n
factorial=1
n=1
while True:
    num=int(input("Enter number: "))
    if num<=0:
        print("Thank you!")
        break
    while n<num:
        n+=1
        factorial*=n
    print(factorial)
    # reset the values------------->>
    factorial=1
    n=1


Move Through Object List

Question:
{{teams[0].name}}

<button id="next">Next</button>

When the "next" button is hit I would like the team-name to be the next team name in the list, i.e. 0 becomes 1?
I have a feeling I need JS to do this - but I am not sure how I would use JS to do this.
Also, the list is generated from the server.
UPDATE
{{ }} is part of a templating system - Jinja2 to be precise.
The teams list is passed into the webpage through Jinja2 - so the webpage has access to the entire teams list - I hope that makes sense.
class Team(db.Model):
    __tablename__ = 'Team'
    name = db.Column(db.String(21))
    matches_total = db.Column(db.Integer())
    matches_won = db.Column(db.Integer())
    matches_lost = db.Column(db.Integer())

Comment: Is the `{{ }}` notation part of a templating system, or are you just indicating that you want the value in there?
Comment: {{ }} is part of a templating system - Jinja2 to be precise. Will update the question with the clarification too.
Comment: Are the other entries from the list available somewhere? If not you can't do that without server-side code.
Comment: And what does your `teams` array look like? (I'm assuming it's an array of objects, from the notation)
Comment: ^yes it's an array of objects
Comment: Updated question with extra clarifications
Answer: Make a list containing the names available as team_names and update your template like this:

{{teams[0].name}}

<button id="next">Next</button>

In case you are using flask which seems to be the case, pass this to your render_template() call:
team_names=[t.name for t in Team.query]

Then you can use the following jQuery snippet to do what you want:
$('#next').on('click', function(e) {
    e.preventDefault();
    var nameElem = $('#team-name');
    var entries = nameElem.data('entries');
    var index = (nameElem.data('index') + 1) % entries.length;
    nameElem.text(entries[index]).data('index', index);
})

Note: This answer assumes the list is not too big.
Comment: Is 50 items considered too big?
Comment: I get the following error: TypeError:  is not JSON serializable
Comment: Read my answer carefully. You should create a list containing just the names - not `Team` objects.
Comment: Yeah, you pinpointed my exact mistake lol #signsofanawesomeprogrammer. Thanks, that did the trick, so if I want my program to update, matches_total/won/lost etc, I just do the same technique for them, right?
Comment: Then you might want to json-serialize the Team objects (simply add a method that returns the interesting values in a dict) so you don't need tons of data attributes.
Comment: Thanks so much by the way! Also, I have pictures of team logos - do you know how to do json serialization with images?
Comment: Actually I figured out how to do it - i just changed the image's src attribute to entries[index]
Comment: I've had to temporarily uncheck your answer - as it only runs once, after one move through the list, it does not move again - it goes into the function - but the entries[index] is stuck with the same value since the first time it changed. Any ideas why it only runs once?
Comment: If I look at entries - it shows all the entries, but the index never changes after the first time the function runs.
Comment: I have figured out that nameElem.data('index') is always 0 for some reason that's the problem here the new nameElem.data('index') is never saved.
Comment: Do you know how to set the new nameElem.data('index') to its value - I am getting an error when I try to do it.
Comment: Oh heh, totally forgot that in my code. Answer updated. Now it should work properly.

Move Through Object List


Relacionar ID com nome na mesma tabela

Question: preciso de uma ajuda.
Tenho uma tabela de categorias que possui os campos:

id;
nome;
descricao;
id_categoria_pai;
id_user;

Quero pegar o nome da categoria quando o id_categoria_pai for igual ao id da categoria.
Exemplo:
A categoria Carro possui como pai a categoria Veículos
id = 4;
nome = Carro;
descricao = qualquer;
id_categoria_pai = 1(veiculos);
id_user = 1;
Preciso exibir o nome da categoria pai, nesse caso, Veiculos.
Como eu consigo fazer isso? Tentei de todo jeito e não consigo.
Ou eu crio as tabelas separadas? acho que nao ne.
Obrigado!
Comment: Você pode utilizar join, + ou - assim: SELECT * FROM categorias as cat LEFT JOIN categorias_pai as cat_pai ON cat_pai.id = cat.id_categoria_pai; Claro, você precisa alterar para a sua situação e nomes de tabela em fim...
Comment: Cara, to meio perdido hehe, mas isso vai funcionar na mesma tabela?
Comment: Como assim? Não entendi sua pergunta... o que acontece nesse caso, ele vai selecionar tudo das tabelas categorias_pai e categorias, quando o id da categorias_pai for o mesmo que id_categoria_pai da tabela categorias...; Desculpe é meio confuso mesmo, qual o nome de suas tabelas? Pode fornecer elas em sua pergunta? Assim ficaria mais fácil para ajudar;
Comment: Mas só existe uma tabela, a tabela categorias, dentro dela possui o campo id e id_categoria_pai, ou seja as categorias pai e filhas estão na mesma tabela
Comment: Ah... entendi, então ficaria + ou  - assim (Eu teria feito separado, mas tudo bem, sem problemas). SELECT * FROM categorias as cat1 LEFT JOIN categorias as cat2 ON cat2.id = cat1.id_categoria_pai WHERE cat1.id=1; Teste esse sql e diga se funciona... mas acredito que para melhor manutenção seria interessante separar, (categorias) e (subcategorias);
Comment: Funcionou perfeito Rafael, obrigado pela ajuda, mas pensei no que você falou e vou separar, obrigado.
Comment: Perfeito, forneci como resposta a solução para que não seja perdida caso aconteça alguma coisa com os comentários;
Answer: Analisando o que o usuário forneceu de informações (categorias pai e filhas estão na mesma tabela) a solução para o caso seria mais ou menos a seguinte:
<code>SELECT * FROM categorias as cat1 LEFT JOIN categorias as cat2 ON cat2.id = cat1.id_categoria_pai WHERE cat1.id=1;
</code>
Porém o interessante seria separar as tabelas em categorias e subcategorias para melhor manutenção e entendimento;

Relacionar ID com nome na mesma tabela


Creating a page footer div?

Question: I need to create a page footer, basically a div that stretch 100% width of the page. With a height of 300px. I need it to stick to the absolute bottom of the page. Could somebody please show me how to do this using CSS?
I have not included code as the code would simply be div tags.
Thanks
Comment: Have you tried anything yet? Some css code or anything like, except for simply your `` tags? :P
Comment: Hi - there are a hundred articles on how to do just this. A quick Google is all you need.
Comment: create dive with your given dimention add to css   position:fixed;
Comment: there is a Magic called "CSS" try to google it . . .  :P
Comment: possible duplicate of [Fix footer to bottom of page](http://stackoverflow.com/questions/18915550/fix-footer-to-bottom-of-page)
Answer: div {
    background-color:red;
    height:300px;
    position:fixed;
    bottom:0;
    width:100%;
}

Answer: If you are wanting a sticky footer, then you want to use the css position style fixed
e.g.
div#footer{
    position: fixed;
    display: block;
    bottom: 0;
    left: 0;
    right: 0;
    height: 300px;
}

With this, you would probably also want to set a padding of 300px on the content of the website, so if a user scrolls to the bottom, then they can see the bottom of the content without the footer overlapping it. You would also want to play about with your z-index to make sure nothing is appearing infront of the footer.
Answer: I created a fiddle for you: http://jsfiddle.net/X9gMD/
This is how the css could look like
.footerDiv{
width:100%;
height:300px;
background-color: yellow;
position: absolute;
bottom:0px;
}

Answer: JSFiddle: http://jsfiddle.net/Z6HMb/
Simple HTML example:

This a footer text

CSS
#footer{position:absolute; height:300px; width:100%; bottom: 0%; background-color:red;}

Answer: Use position fixed(fiddle).
CSS:
body {
    background-color: blue;
    height: 2000px;
}

div {
    background-color: red;
    position: fixed;
    height: 300px;
    bottom: 0;
    left: 0;
    right: 0;
}

HTML:

Footer

Answer: To fix the footer use position: fixed CSS property. Something like following shall help.
footer.div{
    height:300px;
    position:fixed;
    bottom:0;
    left:0;
    right:0;
    width:100%;
}

Hope that helps :)
Answer: If you set the footer to position: fixed, it will appear above your content, even if the page is longer than the window.
If what you want is only to keep the footer at the bottom, even when the content is really short, there's that answer : Sticky footer on Stack overflow
That way, your footer will stay at the bottom of the page OR at the end of the content.

Creating a page footer div?


Statistical test for change in traffic flow at border crossing point

Question: I have an assignment, where I'm supposed to measure whether an intervention at a border crossing point will an effect on the traffic flow.
We have a total of 7 border crossing points and we continously measure the traffic flow (n vehicles pr. hour).
Intervention period will be 3 weeks at one border crossing point.
My initial thought was to basically compare means (t-test) between intervention period (3 wks) vs non-intervention period (3 wks up to intervention). The problem is however that traffic flow is stochastic, hence flow changes could easily be contributed natural variation. Is it possible to some how adjust for these natural variations using the remaining 6 border crossing points?
Answer: I think the problem in this question raises on a regular basis. Mostly you are not able to isolate your experiment in the way that there are no other effects, than the one you want to investigate.
You are talking about stochastic variation in the traffic flow, so let's take about time scales. Do you see variation over hours, days, weeks. The longer these periods are relative to your intervention period, the more important for further considerations. When I hear variations in traffic flow I first think of holidays or similar. (Naive view: try to avoid times with obvious and distracting actions)
This leads to the  next point how to overcome the variation. Also trends could be possible in an other context. As you have the data of all seven border crossing points, you can try to estimate the flow on one points using the others. If the results are promising you can use the results in the intervention period, too. Include also estimation errors in further processing.
Nevertheless this way can make problems if your intervention also has side effects to the other crossing points. Like, this extreme example: closing one border crossing will increase the flow on a neighboring border crossing.
The estimated traffic flow without intervention can be compared to the traffic flow with intervention in known ways as you said.
Comment: First of all, thank you for your reply. Variation may not be that stochastic, as periodic variation is quite obvious on daily basis and yearly basis. If I draw trend lines,  both are bell-shapped with peaks mid day, mid year, respectively. Only exception is holidays, where n vehicles are generally lower.


Evaluation map infinite dimensional vector space

Question: In a finite-dimensional vector space, we have an isomorphism ev: $ V \to V^{**}$, where ev(v)$: V^* \to F$ and $f \mapsto f(v)$. But what exactly happens in the infinite-dimensional case? Why is ev$(v)$ not surjective?
Answer: If you follow the argument you see that there is a dual basis in $V^*$. So if $v_1, ...,v_n$ is a basis  of $V$, then $f_i$ where $f_i(v_j)=\delta_{ij}$ is a dual basis. But in the case of infinite dimensions this is not a basis, because there are many functions which take nonzero values on infinitly many of the basis $\{v_i\}$ of $V$. In any case they dont even have the same cardinality, $|V^*|=2^{|V|}$.


Usage of two SSD ubuntu server

Question: We have an ubuntu server with two SSD which host a few websites   running on nginx, mysql, postfix etc...
I am so confused if we are using the 2 SSD correctly
On webmin system info page, it says :
61.50 GB used, 188.45 GB total

Unix commant
~# sudo lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT,LABEL

NAME    FSTYPE              SIZE MOUNTPOINT LABEL
sda                       223.6G
|-sda1  linux_raid_member   953M            NC-PH-0456-19:0
| `-md0 ext4                953M /boot
|-sda2  linux_raid_member    32G            NC-PH-0456-19:1
| `-md1 swap                 32G [SWAP]
`-sda3  linux_raid_member 190.7G            NC-PH-0456-19:2
  `-md2 ext4              190.7G /
sdb                       223.6G
|-sdb1  linux_raid_member   953M            NC-PH-0456-19:0
| `-md0 ext4                953M /boot
|-sdb2  linux_raid_member    32G            NC-PH-0456-19:1
| `-md1 swap                 32G [SWAP]
`-sdb3  linux_raid_member 190.7G            NC-PH-0456-19:2
  `-md2 ext4              190.7G /

And df command:
Filesystem     1K-blocks     Used Available Use% Mounted on
udev            16437532        0  16437532   0% /dev
tmpfs            3291052     9420   3281632   1% /run
/dev/md2       196664572 54339476 132312020  30% /
tmpfs           16455244        0  16455244   0% /dev/shm
tmpfs               5120        0      5120   0% /run/lock
tmpfs           16455244        0  16455244   0% /sys/fs/cgroup
tmpfs           16455244        0  16455244   0% /run/shm
/dev/md0          944108   164368    714564  19% /boot
cgmfs                100        0       100   0% /run/cgmanager/fs
tmpfs            3291052        0   3291052   0% /run/user/0

So the total should be around 400GB ?
BTW, should we running the system on ssd1 and backup everything on ssd2 ?
Answer: You are running the two drives in RAID 1 - which is mirroring. As a result, the total drive space is n/2, and the resiliency is n/2. This will give you the performance of roughly one drive for writes, and up to 2n for reads (with caveats - worst case is 1n for reads).
What I assume you are looking for is RAID 0 - which is striping. That would give you the total space of 2n and zero drive resiliency. This will roughly give you the performance of the drives combined.
Unless you have a good backup, redundant server, and knowledge of handling the fault domain, I would highly recommend sticking with RAID1 as you will have the opportunity to replace a failed drive. With RAID0, if a single drive is lost, the entire array's dataset is lost.
Regarding your final question - I would definitely stick with RAID1. With two drives, there's no real advantage going with a single drive that is asynchronously backed up to it's mate. Performance will be similar (except when the backup is occurring - that will induce a large amount of IO), and you have to deal with how to keep them in sync. With MDADM and RAID1, the drives don't have anything particularly fancy for storing the data - the data is all on both drives, in the exact format you write (ext4 in this case). You could pop out one of the drives, hook it up to another machine, and have fully readable ext4 partitions.
Comment: @PhamHuyAnh No, RAID is **never, ever** a replacement for backup. If the server gets damaged, both disks are dead. If you delete a file, it gets deleted on both disks etc. RAID1 protects you from downtime due to a broken disk and nothing more. Even using the 2nd disk as backup and not in a RAID would be a crappy, useless backup.
Comment: Looks like each physical drive has 3 partitions which are mirrored on the other drive. This is software RAID. Performance of RAID 1, especially software RAID 1 is less than single drive, reduced by mirroring overhead AND software overhead. The software hit is harder with SSDs than the mirroring hit.  Hardware RAID 1 would improve the performance so that it would probably be almost indistinguishable from a single drive.  But I agree that RAID 0 is the way to go for a web server, with the caveat that good backups are required.  You end up with almost double space, and almost double throughput.
Comment: Absolutely not, RAID1 just give you the ability to replace a drive without taking the server offline - it does not provide any sort of backup. Always have offsite backups.
Comment: @PhamHuyAnh Research Grandfather, Father, Son backup rotation.  It is an example of a backup plan that utilizes offsite storage.
Comment: Actually, Xalorous, MDADM RAID1 can improve performance in certain situations - writes will be equivalent to the slowest drive as both drives have to write a block synchronously. However, for reads it can actually be considerably faster (up to 2n) as it can pull blocks from each drive independently. More information is here: http://superuser.com/questions/385519/does-raid1-increase-performance-with-linux-mdadm
Comment: Brennen Smith : So wiht RAID 1, unless some weird things happen, I don't need to backup the server as there is no disk failure ? I do backup the mysql databases from time to time, though. The user-files (photos , music files..etc ) are huge, like 3-40GB or so, and I just want to backup those files every few months.
Comment: That is interesting, and probably a good solution on laptops and mobile devices.  I'm curious as to which would be better for a web server.  The examples make it sound like a pair of long file reads demonstrates the peak performance of the utility where RAID 0 provides benefits all the time, reading 2 files or 100.  Plus the seek benefits.  I tend to prefer to leave RAID to the HW layer if it is available and assuming it's server quality and performance hardware.

Usage of two SSD ubuntu server


Returning an empty array of UITableViewRowAction in EditActionsForRow breaks swiping on a table cell

Question: I have a UITableView and I want to have some of the rows swipeable, and some not, but I want them all to be able to be selected via selection bubbles. The problem is, CanEditRow controls whether or not you can swipe a cell and whether or not you can select it via it's bubble.
So what I tried to do to get around this is: in EditActionsForRow just return a an empty UITableViewRowAction[] when I don't want the cell to be swipeable, and one with the appropriate UITableViewRowActions when I do want it to be swipeable. The problem is, as soon as I hit the case where the empty UITableViewRowAction[] array is returned, swiping no longer works.
One hack I tried was to return an array with just one UITableViewRowAction in it that has no text and does nothing. The only problem is that the Table Cell doesn't "bounce back" the same way it does the first time you try to swipe a cell that can't be swiped.
Does anyone have experience with this problem or know of a workaround?
Answer: If I understand your problem correctly, CanEditRow must always return true (for selection bubbles to work) and only some cells should have row action buttons.
The solution would be to override EditingStyleForRow method, check which row is about to be edited and return UITableViewCellEditingStyle.None if you do not want to add action buttons.
Example implementation of UITableViewSource (every second cell has row action buttons):
public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath)
{
    return true;
}

public override UITableViewCellEditingStyle EditingStyleForRow (UITableView tableView, NSIndexPath indexPath)
{
    if(indexPath.Row % 2 == 0) // dummy condition
        return UITableViewCellEditingStyle.Delete;
    else
        return UITableViewCellEditingStyle.None;
}

public override UITableViewRowAction[] EditActionsForRow (UITableView tableView, NSIndexPath indexPath)
{
    UITableViewRowAction hiButton = UITableViewRowAction.Create (UITableViewRowActionStyle.Default, "Hi", delegate {});

    return new UITableViewRowAction[] { hiButton };
}


How namespaces work in Ruby?

Question: I'm using namespaces in order to organize my code, but now I'm with a small doubt. I have the following code:
module ShopApplication
  module Models
    class Product < ::Sequel::Model
      # Model code
    end
  end
end

All my models are contained into this module called Models. In another part of my application, I have the following:
module ShopApplication
  module WebInterface
    class App < ::Sinatra::Base
      get '/' do
        @products = ShopApplication::Models::Product.all
      end
    end
  end
end

I wanna use my models without specify the full path. Can I transform @products = ShopApplication::Models::Product.all into @products = Product.all? If yes, how? I tried include ::ShopApplication::Models into the App class, but don't worked.
Answer: Module#include is what you want to use here:
module ShopApplication
  module Models
    class Product < ::Sequel::Model
      # Model code
    end
  end
end

module ShopApplication
  module WebInterface
    class App < ::Sinatra::Base
      include ShopApplication::Models
      get '/' do
        @products = Product.all
      end
    end
  end
end

Here's a contrived example that doesn't have your dependencies in it, but shows both class methods and instance methods:
module ShopApplication
  module Models
    class Product
      def name
        "Product-name"
      end
      def self.all
        ["array", "of", "products"]
      end
    end
  end
end

module ShopApplication
  module WebInterface
    class App
      include ShopApplication::Models
      def instance_meth
        p Product.new.name
      end
      def self.class_meth
        p Product.all
      end
    end
  end
end

ShopApplication::WebInterface::App.new.instance_meth
ShopApplication::WebInterface::App.class_meth

How namespaces work in Ruby?


What is the best way to upgrade many linux desktop workstations at once?

Question: At work, we have several Ubuntu Linux workstations. I'm looking for a good/reliable/fast way to install a set of packages on all boxes at once. What I'm thinking of doing right now is:

Install Ubuntu on a brand new box and use that as a master disk image.
Clone or copy the partition contents to all boxes.
When a package/set of packages need updating, apply the changes on the master disk image.
Dump the master disk image to a central NFS server.
Use PXE/diskless booting to put all workstations in a recovery mode.
Clone the master disk image to all workstations once a week.
Use a configuration management tool (what should I use?) to set up /etc and friends.

Has anyone else done something similar? How did you approach it?
I'm already using NFS/NIS, so I won't lose any user data.
Comment: are you wanting to do a one time set up, or to have it install a package on one comp and have that package go to the other comps?
Answer: I think puppet can help you with this.  You're essentially managing a group of workstations instead of servers, but it should work the same way.  That way you can create different groups based on any hardware differences,etc.
Answer: You can ghost it over to them all, but most linux distributions include a method to script the installation process. The advantage is it will ask you if a problem occurs, whereas just ghosting it over doesnt.
With Fedora (amongst others) you can script it such that all workstations login to a central source of control/alert so that they will conduct package installation autonomously but ask when differences and problems occur.
As an alternative, if you have mixed machine types, group their MAC addresses into hardware setup groups and use a live CD to rsync and install grub, dependent on MAC/Hardware setup.
Tons of approaches really. Tutorials on headless installs will provide some nifty ideas with or without screens.
Scripting the Fedora/Anaconda install process
Comment: The google term for Ubuntu automated installs is "preseed files", and I definitely agree that is the way to go.  Imaging is so hard to maintain, and with the rate of security updates, it is important to be able to quickly update all your machines.  Automated/unattended installation + automated configuration management (i.e., puppet) + managed package repos if you really need them.
Answer: Another option you could consider is using the existing processes like "yum update" to pull packages from a repository that you run and force those workstations to all update at a specific time.  All you need to do is update a master workstation, note the packages you need to distribute, and put them into your internal repository.
Comment: You need to make a repository inside your network for faster access and run yum update -y. For apt-get to work he will have to mirror an Ubuntu repository.
Answer: I would suggest creating an APT repository.  You can add your own packages to the repository, and use a cronjob to update the packages using apt-get once a week.  The apt-get job can be made automatic, and since the repository is your own, you can update it or not as you desire.
All you would need to do is set up the repository and configure APT on all the machines to use it.  I would recommend cfengine to configure all of the systems; thus you don't have to visit each one to update APT on each one.
You could even create a package with the repository configuration built right into it; I would recommend it in fact.  Then when you build a new environment your local APT configuration is just an apt-get away.
Answer: I find it hard to believe that no one has mentioned Redhat Spacewalk.
It's the free open source equivalent to the Redhat Network's Satellite system. It allows you to manage your entire infrastructure of CentOS, Fedora, or Scientific Linux installations. It is essentially meant for what you're wanting to do.
Of course, you're using Ubuntu, as opposed to Redhat derived distros. Fortunately, the Ubuntu world has what you're looking for in Landscape. It comes free with a support contract, or it's $150/node. Expensive, but it's a trade off.
If you don't go with Landscape (or migrate to RH for spacewalk), then Puppet/CFengine might be your best bet.
Answer: ssh in to each box and run "apt-get install whatever".
consider having all the clients trust your public ssh key from your administration host so you do not need to provide password to do so.
Answer: If you're using a debian-based distro like Ubuntu, look into pre-seeding:
DebianInstaller Pre-seed
This allows you to specify just about everything you setup during install, like network, apt, packages, etc.  When you boot the install cd, append:
<code>preseed/url=http://blah/preseed.cfg
</code>
to the kernel boot menu, and it'll use your preseed config to do the install.
Comment: This will only help you with the initial install. The question is about upgrading packages on an existing installation.
Answer: I used to be an administrator in my Electrical Engineering computer lab, counting about 20 computers, all Ubuntu. I liked to always use the latest Ubuntu release as soon as it was released, so I upgraded a lot.
The setup of the computer lab was such that I had one Debian master-box (seldom updated/upgraded), which I used for hosting the student branch's web page, managing the user accounts (with LDAP, allowing the each user to sit at any computer and log in with his/her home folder available), running maintenance scripts, etc.
The method I used to update (which is somewhat crude in my opinion tbh) involved writing a CD with the latest release, when released, and manually placing them in the drives, rebooting and going through the regular installation procedure. When the install was complete I copied the public RSA key I had generated (once) to the host (into the /root/.ssh/ folder), and therefore giving the Debian box control over the host box. So on the master box I had a python script (it can of course be any scripting language) which brought the host computer up-to-speed with my wanted configuration, copying config files to the host box (such as the LDAP config files, pre-built gnome config files, etc.), apt-get the required packages (a lengthy process), configuring them (by copying their config files and menu-item files to the correct places) and otherwise setting the host box up.
This process, although crude and unsophisticated, only required my presence for actually booting the "to-be-updated" box up from the ubuntu setup CD and going through the few setup screens for ubuntu, configuring the /etc/network/interfaces file for access to the network, and then running the script on the master box, then I could be off doing something else.
If you want more info please post more specifically what you want to automate, whether it be just the actual process of setting up a new release version of a currently running linux distro or setting up programs that require building source files or such ('cause I used to also build my own packages for programs such as Eclipse (which doesn't play nice with Ubuntu straight from the package manager), XCircuit (which is "buggy" at best from the package repo, Matlab (which requires punching in a cd-key and more)...
Hope that helps! =)


A proof of why $y=mx$ grows faster than $y=\ln x$ for all $m \not = 0$

Question: Akin to the title, how do I prove that the linear function $y=mx$  grows faster than the logarithmic function? (It was easy to show graphically for a few examples but is there a more rigorous proof?)
Comment: Welcome to Mathematics Stack Exchange.  Looking at the derivatives, $m>\frac1x$ eventually
Comment: Just divide the first by the second and calculate the limit
Answer: Alternatively, you could prove as follows:
$$\lim_{x\to\infty}\frac{mx}{\ln(x)} = \lim_{x\to\infty}\frac{mx}{2\ln(\sqrt{x})} \ge \lim_{x\to\infty}\frac{mx}{2\sqrt{x}}=\lim_{x\to\infty}\frac{m\sqrt{x}}{2}=\infty, (m\not = 0)$$
which takes advantage of $\ln(x) < \sqrt{x}$
Answer: To prove this, consider the limit:
$$ L=\lim_{x \rightarrow \infty} \frac{mx}{\ln x} $$
$(m > 0$). Using, for instance, L'Hospital's rule, you can easily see that:
$$ L= \infty$$
This means that $f(x)=mx$ grows faster than $g(x)=\ln x$.
Comment: Thanks for the proof, is there a different way to solve it besides limits?
Comment: There are various methods to prove it. For instance, you can use derivatives (which however still involve limits by definition), as suggested by @J.W.Tanner. See also here: https://math.stackexchange.com/questions/511234/how-do-i-prove-that-a-function-grows-faster-than-another#:~:text=2%20Answers&text=There%20are%20many%20ways.,the%20ratio%20grows%20without%20bound for something more on this,
Comment: @Miko If you mean the proof besides anything that is related to limits (even derivatives), then it's almost impossible (unless you accept the graph proof).
Answer: Consider the sequence
$$\frac{mx}{\log x}=\frac{me^n}n.$$
We have
$$\frac{\dfrac{me^{n+1}}{n+1}}{\dfrac{me^n}n}=\frac{en}{n+1}\ge\frac e2>1$$ so that the sequence grows as fast as a geometric one.
Answer: Let $x>0$. Observe that
$$
e^x  = 1 + x + \frac{{x^2 }}{2} +  \cdots  > 1 + x > x.
$$
Taking logarithms and using that the $\log$ is monotonically increasing, we obtain
$$
\log x < x.
$$
Thus,
$$
\log x = 2\frac{1}{2}\log x = 2\log \sqrt x  < 2\sqrt x
$$
for any $x>0$. Finally, if $m>0$,
$$
\frac{{mx}}{{\log x}} > \frac{{mx}}{{2\sqrt x }} = \frac{m}{2}\sqrt x ,
$$
showing the desired result.


Is survival analysis suitable for this comparison?

Question: I'm monitoring a website where I have two kinds of users (say, A and B). These users are able to contribute to this site in a variety of ways and, for each contribution, its time is logged. What I want is to compare if the number of days that the user is active (contributing in some way) differ between the kinds of users.
I'm monitoring the website since it's beginning until four months ago. Not all users joined as soon as the site was created nor users that joined at the beginning are still contributing.
Is survival analysis suitable for this comparison ?
Answer: No. Survival analysis is for time to event data. You want to compare "number of days active" which is a count variable. You want to control (or seem to want to control) for number of days that the user might have contributed - number of days "joined".
This suggests a count regression (Poisson, negative binomial or variation) with "type of user" and "number of days joined" as independent variables.
Comment: She mentioned that some users are not contributing anymore, i.e. inactive. In this case maybe they should not be counted in. This sounds like survival analysis aspect to me.
Comment: No, because she isn't modeling whether they are in or not - that is a covariate not the dependent variable
Comment: I guess I got it. I would use survival analysis if I wanted to know if users A stop contributing earlier than users B, if I knew when they stopped contributing. Is that correct ?
Comment: Yes, exactly. Survival analysis deals with time to event data; it is particularly helpful when, as is often the case, some subjects are censored.


Is weight still a continuous variable if its measure is rounded to an integer?

Question: So it is obvious that weight is a continuous variable as it can be quantified with decimal precision;like 10.2 kg and 3.0122 kg.
If we were to round it to an integer like 10 kg and 3 kg. Would then this variable of weight be still considered a continuous numerical variable or discrete.
Asking because my stat text books says that only continuous numerical variables can be used with certain statistical analysis (Regression, ANCOVA .etc). And i wanted to make sure that I can still use certain "continuous variables" who's measurements have been rounded to integers.
Comment: Might I suggest you throw those books away?  Asserting that the measurement type of a variable determines or severely constrains how you can analyze it is a huge abuse of the concepts and theory of variable types and statistics.
Comment: @Nuclear If it helps you, that's fine.  But perceptive authors--John Tukey, Lee Wilkinson, and others--have argued very strongly that this only blinds you concerning other opportunities to analyze the data.  This is unrelated to the question of underlying distributional assumptions.  Historically, the most prominent challenge to your point of view is Lord's (1953) paper on football numbers -- and it [still gets attention](https://www.sciencedirect.com/science/article/pii/S0022249609000054), indicating the question cannot be considered wholly resolved.
Comment: I'm sure you mean *mass*, but I digress. In any case, whether you treat something as a continuous variable or discrete has more to do with how many unique values of that variable you have in your dataset. If all of your observations are either 2 or 8 kg, then I'd probably treat that variable as having a binomial (discrete) distribution. But if you have values ranging from 0 to 100 kg and the histogram of the data series looks pretty "smooth," I think a continuous distribution would be more appropriate. Regardless, regression can be performed on both discrete and continuous data series.
Comment: @whuber I rather disagree, I find that a thorough understand of my data type helps to frame the problem and narrow down potential approaches. Categorical data simply can't be handled the same as ordinal discrete data, which itself may or may not be a decent approximation of continuous data. Virtually all statistical tests have some underlying assumptions about the data, and to not appropriately match your method to your data is, IMO, a bigger abuse of the statistics.
Comment: Note that the same argument that applies to claiming that 3kg is a discrete value also applies to 3.0122 kg; it's an integer number of milligrams, after all. If you have measurements to n decimal places, then all of your measurements are an integer number of 10^-n kg (with some quibbles about base-10 vs. base-2).
Answer: The normal distribution is a theoretical continuous function.
In practice all data is, to some extent (if you look far enough behind the decimal point), discrete.
The normal distribution, in the end, is only used as a useful/easy/handy/simple/manageable approximation to the distribution of the data (this extends to variations from the theoretic distribution beyond the discreteness of data, e.g. different skew/kurtosis). Often unnoticed since the difference is so small, or in other words the approximation is so good (at least due to the aspect of discreteness).
Only in cases of few discrete levels do people consciously think about the deviation of the theoretic Gaussian distribution from the real distribution due to the discreteness of the data. For instance when using a continuity correction when applying a normal approximation to binomial or Poisson distributed data.
Comment: Something subtle and interesting has happened in this answer: you have implicitly conflated the concepts of (1) a *categorical* measurement type, which is defined in terms of a group of allowable transformations of its possible values; (2) a *discrete* set of numbers (which is a topological property); and (3) a *discrete* random variable, which refers to a property of a mathematical model for the data. Although in English "categorical" and "discrete" are practically synonyms, **these are completely different concepts.** It is only in sense (2) that your assertions about "in practice" are true.
Comment: The *question itself* concerns a categorical or ordinal variable, whereas your answer discusses *topologically discrete* data.  I wanted to call attention to the distinction between those, which I think is important for coming to a correct and useful understanding of the issues in this thread.
Comment: The question discusses continuous variables that are rounded, not? (such as weight measurements). Where does it implicitly refer to categorical data?
Comment: The issue, quite clearly, is whether the conversion of one measurement type to a "lower" type, such as rounding to a whole value--essentially conversion to an apparent ordinal or categorical variable--should affect how one can analyze data.  Discussing the resulting discretization, in the topological sense, seems to be less germane and less useful than focusing on the implicit misunderstandings of the role of measurement type in statistical analysis (as exemplified in some comments to the question).
Comment: I have edited my question a few times so maybe it is gone now, but I did not mean to speak about a *categorical* variable, I currently can't see this in my text.
Comment: I think the topological sense is useful (maybe less useful, I don't know about that) since it shows that, every measurement is in essence a conversion/discretization (and if you like every weight/mass measurement of an object is in theory discretized by being a sum  of the the weight of individual atoms or, if you dig deeper, quantum energy levels). The practical question boils down to 'how much harm' the discretization did. And even if it did harm, how one can correct for this, if necessary. I am still puzzled about the point were this answer is conflating concepts.
Answer: That assumption concerns more about the sample/population mean distribution, not how your data are recorded. In a way, 10 kg is also 0.01 metric ton, there is no magic introduced in rounding your readings to whole number here.
What you should be asking, however, is why the rounding to begin with. You lose some information that way so if that's not absolutely necessary, keep what they are, and perform necessary rounding only at the last stage when you present the results.
Answer: Yes, in that case you can still apply methods that work on continuous data.
One piece of the puzzle is that the integers are a subset of the reals ($\mathbb{Z+} \in \mathbb{R}$). They also follow the same order.
A lazy intuitive argument for this would be to simply consider the input being continuous measurements that take integer values "by chance".


search query in entity framework 3.5

Question: I need to build a search query on Customers table join with orders table
string firstname  = "Joe";
 string emailFilter = "firstname.lastname@example.com";
 string city=null;

In SQL we can make like this
SELECT @sql =
    'SELECT  * from
     FROM   dbo.Orders o
     inner join
     JOIN   dbo.Customers c ON o.CustomerID = c.CustomerID
        WHERE  1 = 1'

IF @firstname IS NOT NULL
   SELECT @sql = @sql + ' AND c.firstname= @firstname'

IF @city IS NOT NULL
   SELECT @sql = @sql + ' AND c.city >= @city'

I need to build a entity framework 3.5 linq query joined with orders and customers table
with dynamic search condition.
if the values are not null, i need to use in where clause in linq
I am new to Linq.
shall we need to use Iqueryable.
Any help appreciated.
Thanks
Comment: please compile your code and look at the error messages before asking a question
Answer: You can try something like :
var result = from o in context.Orders.include("customers")
             where o.city == (city == null ? o.city : city) && o.firstname == (firstname == null ? o.firstname : firstname)
             select o;

Answer: You can check Dynamic Linq here http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx it will help you or search stackoverflow.com for dynamic-linq tag questions and answers https://stackoverflow.com/questions/tagged/dynamic-linq

search query in entity framework 3.5


Find and Replace in Excel 2010 without losing cell formatting - unable to run on a cell that has 255 characters

Question: I am using this macro in Excel 2010 to find and replace words without losing cell formatting (e.g. some words are in bold, some are in italics so this macro just makes sure the cell keeps the same formatting when a word is replaced):
<code>' Replacement of characters in the range(s) with storing of original Font
' Arguments:
'   Rng         - range for replacement
'   FindText    - string being searched for
'   ReplaceText - replacement string
'   MatchCase   - [False]/True, True to make the search case sensitive
Sub CharactersReplace(Rng As Range, FindText As String, ReplaceText As String, Optional MatchCase As Boolean)
  Dim i&, j&, jj&, k&, v$, m&, x As Range
  j = Len(FindText)
  jj = Len(ReplaceText)
  If Not MatchCase Then m = 1
  For Each x In Rng.Cells
    If VarType(x) = vbString Then
      k = 0
      i = 1
      With x
        v = .Value
        While i <= Len(v) - j + 1
          If StrComp(Mid$(v, i, j), FindText, m) = 0 Then
            .Characters(i + k, j).Insert ReplaceText
            k = k + jj - j
            i = i + j
          Else
            i = i + 1
          End If
        Wend
      End With
    End If
  Next
End Sub
' Testing subroutine
Sub Test_CharactersReplace()
  CharactersReplace Range("A743:F764"), "Replace This", "With This", True
End Sub
</code>
When I run the macro, there is an issue where the code doesn't work when a cell has more than 255 characters.
I've been looking this up online but have got no real solutions for this! Does any know how to solve this?
Answer: EDIT::
It's not a simple solution, but basically what you need to do is this:

get an array filled with values for the FontStyle of each character in the cell
use Replace to replace each instance of your "old string" with your "new string"
move the values in the array to reflect the change in string length
write back both the string and the Fontstyle array to your cell

I managed to create something which works, it's a bit of a long one but I don't know of any other way of doing it.
Also, note that this only takes/replaces the Font Style (Bold, Italic etc) - it won't replicate any changes to color, size, font etc. These could easily be incorporated though, by adding more arrays and setting/amending their values inside the existing loops.
<code>Public Sub RunTextChange()

Dim x as Range

For each x in Range("A743:F764")
    Call TextChange(x, "Replace This", "With This")
Next x

End Sub

Public Sub textchange(TargetCell As Range, FindTxt As String, ReplaceTxt As String)

''''Variables for text and length
Dim text1 As Variant: Dim text_length As Long
text1 = TargetCell.Value: text_length = Len(text1)

'variables for lengths of find/replace strings and difference
Dim strdiff As Long: Dim ftlen As Long: Dim rtlen As Long
ftlen = Len(FindTxt): rtlen = Len(ReplaceTxt): strdiff = rtlen - ftlen

'font arrays and loop integers
Dim fonts1 As Variant: Dim x As Long: Dim z As Long
Dim fonts2 As Variant
'set font array to length of string
ReDim fonts1(1 To text_length) As Variant
'make font array to correspond to the fontstyle of each character in the cell
For x = 1 To text_length
    fonts1(x) = TargetCell.Characters(Start:=x, Length:=1).Font.FontStyle
Next x

'detect first instance of find text- if not present, exit sub
z = InStr(text1, FindTxt)
If z = 0 Then Exit Sub

'continue loop as long as there are more instances of find string
Do While z > 0
'replace each instance of find string in turn (rather than all at once)
text1 = Left(text1, z - 1) & Replace(text1, FindTxt, ReplaceTxt, z, 1)

    'if no difference between find and replace string lengths, there is no need to amend the fonts array
    If Not strdiff = 0 Then
        'otherwise, expand fonts array and push values forward (or back, if the replace string is shorter)
        fonts2 = fonts1
        ReDim Preserve fonts1(1 To text_length + strdiff) As Variant
        For x = z + ftlen To text_length
            fonts1(x + strdiff) = fonts2(x)
        Next x
        'set all the letters in the replacement string to the same font as the first letter in the find string
        For x = z To z + rtlen - 1
            fonts1(x) = fonts2(z)
        Next x
    End If

    'change text_length to reflect new length of string
    text_length = Len(text1)
    'change z to search for next instance of find string - if none, will exit loop
    z = InStr(z + rtlen, text1, FindTxt)
Loop

'change cell Value to new string
TargetCell.Value = text1
'change all characters to new font styles
For x = 1 To text_length
    TargetCell.Characters(Start:=x, Length:=1).Font.FontStyle = fonts1(x)
Next x

End Sub
</code>
Comment: Using the Replace function in VBA loses the text formatting in Excel which is why I haven't used it
Comment: @C.Ron do you mean words within the cell have different formatting, or do you just mean the cell format? I can't think of a reason why Replace would "lose" the cell format, since it's only working on the values - I'd assumed that this was what you meant by cell formatting
Comment: words within the cell have different formatting. Using the replace VBA function makes all text inside a cell have the same format which I am trying to avoid
Comment: @C.Ron I've completely changed my answer now - managed to create a working solution, and it does work for over 255 chars (I tested it on around 650). It's a bit of a long one though. Also, this function is just for a single cell - if you wanted to do this on a range, you'd have to set up a loop and just call this on every cell
Comment: thanks a lot! But how would I go about setting up a loop to call on a range of cells?
Comment: @C.Ron you've already done that in your original code - you just need to have a seperate macro which loops over For each x in Rng.Cells, like your original macro does - except the only thing you need to put in the loop is-
    Call textchange(x, "Find Text", "Replace Text")
Comment: I've tried to create a separate macro but I can't get it to run. Can you give me an example of how to set up the loop please. Thanks
Comment: @C.Ron - I've amended my answer to include the seperate macro - it's at the top of the code, above the main macro
Comment: The code currently incorporates the Font Style Bold & Italics. How would I incorporate underline??
Comment: @C.Ron the structure I've given you will work, but underline isn't defined in the FontStyle property for the characters- it has a separate property. You just need a second array (e.g. underlines1) and copy the method I've used for getting the font styles. For example, under the line -- fonts1(x) = TargetCell.Characters(Start:=x, Length:=1).Font.FontStyle -- you'll want to insert the line -- underlines1(x) = TargetCell.Characters(Start:=x, Length:=1).Font.Underline -- you can similarly copy the existing structure to add the underlines back in.
Comment: Using the existing structure I've tried inserting the underline array but can't seem to make it work. Can you amend your existing answer with the underline array included please? thanks.


Can I use parameterization to copy only specific columns from a number of parquet files

Question: I have a bunch of Salesforce objects being copied into an Azure Data Lake Storage Gen 2 as parquet files. I want to copy these into an Azure Synapse/Dedicated SQL Pool as tables, but I don't want every column, I only need a fraction of them.  I know I can do a copy action for each parquet and use the mapping function to map the columns I want, but has anyone had success parametrizing this in some way? Each table is going to have different column names, but I'm thinking I could create a control document somewhere and look up the table and maybe a boolean field for if I want the column? I have a general idea that I could make this work, but I don't want to re-invent the wheel if someone is already doing it or if there's a better way I just don't know about. Thanks in advance for your help.
I know I can do a copy action for each parquet and use the mapping function to map the columns I want
Comment: You can try for the approach Like getting the details for the files in ADLS metadata as the child Iteams and  then using the Get Metadata>For each>Inside the For Each Look Up> Copy activity.Using the data set data parameters
Answer: As far as my understanding you can build your Synapse Pipeline
Based on the metadata of the files existing in the ADLS Gen 2.
In my experience I have delt with the CSV file to dynamically copy the file to Azure synapse dedicated pool.
Rather than hardcoding or Copying individual file to each table. This approach may help you.
For example I have 2 csv files in ADLS
EMPLOYEE.CSV and DEPARTMENTS.CSV
First I Do the manual import schema to get the json body for the columns only that I need(For desired columns only).

from the above Json you can get the TYPE key and Mapping key.
which will point source and sink Column name. samefor the employee dataset. copy the Json body into a notepad.
Now In the Azure synapse I am creating a config table called
Table_Mapping. with below schema.
Create  table table_mapping
(
SourceFile Nvarchar(50),
SourceTableSchema NVARCHAR(50),
SinkaTableName NVARCHAR(50),
jsonMapping NVARCHAR(4000)
)

The Json Mapping column consist of the above json body of the Desired columns only.
Now Lets Build Dynamic Pipeline.
Get metadata activity To know what file we have in ADLS it should point only folder NOT TO any file.

For Each

Inside FOR EACH LOOK UP
In Look up we have the TABLE_Mapping so for each Iteration it will take the file name and table name and so on.

In the Query
select * from table_mapping where sourceFile='@{item().name}'

Next Copy activity Create Data set parameters for both Source and sink

here is the Expression for the Source and Sink dataset parameters
Source dataset:
FileName:   @activity('Lookup1').output.firstRow.SourceFile
Sink dataset:
Schema:
@activity('Lookup1').output.firstRow.SourceTableSchema
tabelName:
@activity('Lookup1').output.firstRow.SinkaTableName

In the Mapping ADD DYNAMIC CONTENT with below expression.
@json(activity('Lookup1').output.firstRow.jsonMapping)

This approach of having a configuration Table for the columns can dynamically copy the data from source(ADLS) to Sink(Synapse dedicated SQL).
Comment: That sounds like a good strategy! How do you accomplish the first step: "manual import schema to get the json body for the columns". Thank you!


Maximum of $\sum_{k=0}^{P} (-1)^{k+P}\binom{P}{k} k^N $ with $P\leq N$

Question: For a combinatorics problem, I would need to identify the value of $P$ that maximizes the function
$$\Omega(P) = \sum_{k=0}^{P} (-1)^{k+P}\binom{P}{k} k^N$$
with $P\leq N$. Numerically, I see that the maximum is roughly located at $P=3N/4$, but I don't know how to prove it.
I am wondering whether an extrapolation of $\Omega$ to real values of $P$ could be found, which would simplify the search for a maximum. Any idea?
Thanks a lot!
Answer: I'm going to use lower case letters instead of upper. The sum can be expressed as  $p! \, S(n,p),$ where $S(n,p)$ is the Stirling number of the second kind.  We can use asymptotic expansions of Stirling numbers to solve your problem for $n \to \infty.$  I want to reproduce analytically your observed zeroth order approximation, $p^*=\frac{3}{4}n.$  To find a maximum, take a derivative and set to zero, and an approximation to a derivative in $p$ is the difference
$$\Delta_p \;  p!S(n,p) = (p-1)!\big( p S(n,p) - S(n,p-1) \big) = 0$$
That is, to find $p^*$ we want $p$ such that
$$p=\frac{S(n,p-1)}{S(n,p)} = \frac{S(n+1,p)}{S(n,p)} - p $$
where the recursion relation has been used.  Now most approximations to the Stirling numbers of second kind depend on solving a transcendental equation (perhaps the Lambert W is involved.)  However, Guy Louchard in 'Asymptotics of the Stirling numbers of the second kind revisited' records a formula (among many) that is good enough in the region of interest, and is due to Moser and Wyman.  It can be written as
$$ S(n,p) \sim \binom{n}{p}\Big(\frac{2}{p}\Big)^{p-n} .$$
Insert, simplify, and we have the simple equation
$$p=\frac{1}{2} \frac{(n+1)p}{2(1+n-p)} $$ which has two solutions, one of which is $p^*=\frac{3}{4}(n+1).$
I've made plots of the approximation using the binomial and simple factor vs. the ratio of Stirling numbers, and the approximate curve results in a root that is a bit too large, but not terribly so. To go beyond the zeroth order would seem to be a tedious analytic task, and it depends on whether the Lambert W is in your toolbox.
Added 11/29/2021
With an expansion found in arXiv 1506.00699v1 that implies a more accurate $S(n,p)$ in the vicinity where the line $p$ intersects it, a more complicated equation for p can be derived:
$$p=\frac{\sqrt{(n+1)n}}{2\log{2}}\exp\Big(\frac{n(n+1)-4p^2\log^2{2}}{n(n+1)+2(\log{2} -1)} \Big)$$
An exact solution can be found in terms of the Lambda W.  Instead, take the solution and expand it asymptotically as $n\to\infty.$ Using some facts about the Lambert W and some simplification, then it can be shown
$$ p^* \sim \frac{1}{2\log{2}}\big(n+\frac{1}{2}-\frac{1}{8n} +...\big) $$
This solution shows the true zeroth order factor is $ 1/(2\log{2}) \approx 0.72135$, which is about 4% less than the empirically derived factor of 0.75 by the OP.
Comment: Thank you very much for this !! This zeroth order approximation is more than enough for what I need.
Comment: @hugues_myr Thanks.  Consider clicking the accept button.
Answer: Hint: Consider the differences $\Omega(P+1)-\Omega(P)$, and use Pascal's identity.