qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
67,366,685
I am running an Angular Application I am getting these popup in vs code whenever I am opening it. However, the ng serve command is working fine and it's serving(running) the app successfully. But I am getting this error in console. [![console error](https://i.stack.imgur.com/mX73o.png)](https://i.stack.imgur.com/mX73o.png) [![this popup coming in vs code](https://i.stack.imgur.com/uJkvM.png)](https://i.stack.imgur.com/uJkvM.png) [![ng serve is serving the app](https://i.stack.imgur.com/I1exq.png)](https://i.stack.imgur.com/I1exq.png)
2021/05/03
[ "https://Stackoverflow.com/questions/67366685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13975105/" ]
Angular Language Service Extension has one bug which is reported to their git repository. My solution will work for Angular Projects which is running < Version 9.0 To resolve this issue you have two ways. Solution 1: Downgrade extension version 1. Downgrade [https://marketplace.visualstudio.com/items?itemName=Angular.ng-template](https://i.stack.imgur.com/wyMlG.png) to 11.2.14 2. Remove Node Module 3. Run npm install 4. Run npm start or ng serve Solution 2: (For Version 12) 1. Open Vs Code 2. Go To Files ==> Preference ==> Setting 3. Under Extension Select Use Legacy View Engine Checkbox. 4. Run npm start (If you're facing any issue then kindly close VS Code and Remove node\_modules folder and Run npm install [![enter image description here](https://i.stack.imgur.com/wyMlG.png)](https://i.stack.imgur.com/wyMlG.png)
In my case it is a problem of vs code editor, and the solution is 1. Go to VS code settings and search for settings.json file. 2. In settings.json file add this line "extensions.autoUpdate": false, (as in below image) [Settings.json file changes](https://i.stack.imgur.com/LPMio.png) 3. Now go to angular language service extension settings in market place and install the previous stable version. This should resolve your error.
1,628,649
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another. My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
2016/01/27
[ "https://math.stackexchange.com/questions/1628649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/308347/" ]
Think about AM-GM, you get $(\frac{1}{n!})^{\frac{1}n}\le\frac{2}{n+1}$
Using Stirling's Approximation: $$n!\sim\sqrt{2\pi n}(\frac n e)^n \text{ as } n\to\infty$$ We have: \begin{align} \lim\_{n\to\infty}(\frac 1 {n!})^{\frac 1n}&=\lim\_{n\to\infty}[\sqrt{2\pi n}(\frac n e)^n]^{-\frac 1n}\\&=\lim\_{n\to\infty}[(2\pi)^{-\frac 1 {2n}}\cdot n^{-\frac 1{2n}}\cdot\frac en]\\&=\lim\_{n\to\infty} (1\cdot1\cdot0)\\&=0 \end{align}
1,628,649
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another. My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
2016/01/27
[ "https://math.stackexchange.com/questions/1628649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/308347/" ]
**An easy way :** Take , $\displaystyle a\_n=\frac{1}{n!}$. Then , $\displaystyle \frac{a\_{n+1}}{a\_n}=\frac{1}{n+1}\to 0 \text{ , as } n\to \infty $. So by **Cauchy's second limit theorem** , $\displaystyle a\_n^{1/n}\to 0 \text{ , as } n\to \infty$.
Another way considering $$A\_n=\left(\frac{1}{n!}\right)^{\frac{1}{n}}$$ Taking logarithms $$\log(A\_n)=-\frac 1n \log(n!)$$ Now, as Shailesh suggested, use [Stirling approximation](https://en.wikipedia.org/wiki/Stirling's_approximation) $$\log(n!)\approx n \log(n)-n+\frac 12 \log(2\pi n)$$ which makes $$\log(A\_n)\approx -\log(n)+1-\frac 1{2n} \log(2\pi n)$$ So, when $n\to \infty$, $\log(A\_n)\to -\infty$ and $A\_n \to 0$.
1,628,649
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another. My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
2016/01/27
[ "https://math.stackexchange.com/questions/1628649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/308347/" ]
Think about AM-GM, you get $(\frac{1}{n!})^{\frac{1}n}\le\frac{2}{n+1}$
Another way considering $$A\_n=\left(\frac{1}{n!}\right)^{\frac{1}{n}}$$ Taking logarithms $$\log(A\_n)=-\frac 1n \log(n!)$$ Now, as Shailesh suggested, use [Stirling approximation](https://en.wikipedia.org/wiki/Stirling's_approximation) $$\log(n!)\approx n \log(n)-n+\frac 12 \log(2\pi n)$$ which makes $$\log(A\_n)\approx -\log(n)+1-\frac 1{2n} \log(2\pi n)$$ So, when $n\to \infty$, $\log(A\_n)\to -\infty$ and $A\_n \to 0$.
1,628,649
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another. My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
2016/01/27
[ "https://math.stackexchange.com/questions/1628649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/308347/" ]
Another way considering $$A\_n=\left(\frac{1}{n!}\right)^{\frac{1}{n}}$$ Taking logarithms $$\log(A\_n)=-\frac 1n \log(n!)$$ Now, as Shailesh suggested, use [Stirling approximation](https://en.wikipedia.org/wiki/Stirling's_approximation) $$\log(n!)\approx n \log(n)-n+\frac 12 \log(2\pi n)$$ which makes $$\log(A\_n)\approx -\log(n)+1-\frac 1{2n} \log(2\pi n)$$ So, when $n\to \infty$, $\log(A\_n)\to -\infty$ and $A\_n \to 0$.
Let $[x]$ denote the largest integer not exceeding $x.\;$ For $n\geq 4$ we have $$[n/2]\geq (n-1)/2 \;\text { and } \quad n-[n/2]\geq n/2.$$ Therefore, for $n\geq 4$ we have $$n!\geq \prod\_{j=1+[n/2]}^n j\geq [n/2]^{(n-[n/2])}\geq ((n-1)/2)^{n/2}>1.$$ Hence $n\geq 4\implies n!^{1/n}\geq ((n-1)/2)^{n/2})^{1/n}=\sqrt {(n-1)/2}.$
1,628,649
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another. My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
2016/01/27
[ "https://math.stackexchange.com/questions/1628649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/308347/" ]
**An easy way :** Take , $\displaystyle a\_n=\frac{1}{n!}$. Then , $\displaystyle \frac{a\_{n+1}}{a\_n}=\frac{1}{n+1}\to 0 \text{ , as } n\to \infty $. So by **Cauchy's second limit theorem** , $\displaystyle a\_n^{1/n}\to 0 \text{ , as } n\to \infty$.
We start by writing $$\left(\frac1{n!}\right)^{1/n}=e^{-\frac1n \log(n!)}$$ Note that we can easily bound $\log(n!)=\sum\_{k=1}^n\log(k)$ using $$n\log(n)-n+1=\int\_1^n \log(x)\,dx\le \log(n!)\le \int\_1^{n+1} \log(x)\,dx=(n+1)\log(n+1)-n$$ Therefore, we have the inequalities $$-\left(1+\frac1n\right)\log(n+1)+1\le -\frac{\log(n!)}{n}\le -\log(n)+1-\frac1n$$ which obviously show that $\lim\_{n\to \infty}-\frac1n\log(n!)= -\infty$. Finally, we can conclude that $$\bbox[5px,border:2px solid #C0A000]{\lim\_{n\to \infty}\left(\frac1{n!}\right)^{1/n}=0}$$ And we are done!
1,628,649
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another. My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
2016/01/27
[ "https://math.stackexchange.com/questions/1628649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/308347/" ]
**An easy way :** Take , $\displaystyle a\_n=\frac{1}{n!}$. Then , $\displaystyle \frac{a\_{n+1}}{a\_n}=\frac{1}{n+1}\to 0 \text{ , as } n\to \infty $. So by **Cauchy's second limit theorem** , $\displaystyle a\_n^{1/n}\to 0 \text{ , as } n\to \infty$.
Let $[x]$ denote the largest integer not exceeding $x.\;$ For $n\geq 4$ we have $$[n/2]\geq (n-1)/2 \;\text { and } \quad n-[n/2]\geq n/2.$$ Therefore, for $n\geq 4$ we have $$n!\geq \prod\_{j=1+[n/2]}^n j\geq [n/2]^{(n-[n/2])}\geq ((n-1)/2)^{n/2}>1.$$ Hence $n\geq 4\implies n!^{1/n}\geq ((n-1)/2)^{n/2})^{1/n}=\sqrt {(n-1)/2}.$
1,628,649
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another. My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
2016/01/27
[ "https://math.stackexchange.com/questions/1628649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/308347/" ]
We start by writing $$\left(\frac1{n!}\right)^{1/n}=e^{-\frac1n \log(n!)}$$ Note that we can easily bound $\log(n!)=\sum\_{k=1}^n\log(k)$ using $$n\log(n)-n+1=\int\_1^n \log(x)\,dx\le \log(n!)\le \int\_1^{n+1} \log(x)\,dx=(n+1)\log(n+1)-n$$ Therefore, we have the inequalities $$-\left(1+\frac1n\right)\log(n+1)+1\le -\frac{\log(n!)}{n}\le -\log(n)+1-\frac1n$$ which obviously show that $\lim\_{n\to \infty}-\frac1n\log(n!)= -\infty$. Finally, we can conclude that $$\bbox[5px,border:2px solid #C0A000]{\lim\_{n\to \infty}\left(\frac1{n!}\right)^{1/n}=0}$$ And we are done!
Let $[x]$ denote the largest integer not exceeding $x.\;$ For $n\geq 4$ we have $$[n/2]\geq (n-1)/2 \;\text { and } \quad n-[n/2]\geq n/2.$$ Therefore, for $n\geq 4$ we have $$n!\geq \prod\_{j=1+[n/2]}^n j\geq [n/2]^{(n-[n/2])}\geq ((n-1)/2)^{n/2}>1.$$ Hence $n\geq 4\implies n!^{1/n}\geq ((n-1)/2)^{n/2})^{1/n}=\sqrt {(n-1)/2}.$
1,628,649
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another. My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
2016/01/27
[ "https://math.stackexchange.com/questions/1628649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/308347/" ]
Another way considering $$A\_n=\left(\frac{1}{n!}\right)^{\frac{1}{n}}$$ Taking logarithms $$\log(A\_n)=-\frac 1n \log(n!)$$ Now, as Shailesh suggested, use [Stirling approximation](https://en.wikipedia.org/wiki/Stirling's_approximation) $$\log(n!)\approx n \log(n)-n+\frac 12 \log(2\pi n)$$ which makes $$\log(A\_n)\approx -\log(n)+1-\frac 1{2n} \log(2\pi n)$$ So, when $n\to \infty$, $\log(A\_n)\to -\infty$ and $A\_n \to 0$.
Using Stirling's Approximation: $$n!\sim\sqrt{2\pi n}(\frac n e)^n \text{ as } n\to\infty$$ We have: \begin{align} \lim\_{n\to\infty}(\frac 1 {n!})^{\frac 1n}&=\lim\_{n\to\infty}[\sqrt{2\pi n}(\frac n e)^n]^{-\frac 1n}\\&=\lim\_{n\to\infty}[(2\pi)^{-\frac 1 {2n}}\cdot n^{-\frac 1{2n}}\cdot\frac en]\\&=\lim\_{n\to\infty} (1\cdot1\cdot0)\\&=0 \end{align}
1,628,649
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another. My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
2016/01/27
[ "https://math.stackexchange.com/questions/1628649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/308347/" ]
Think about AM-GM, you get $(\frac{1}{n!})^{\frac{1}n}\le\frac{2}{n+1}$
We start by writing $$\left(\frac1{n!}\right)^{1/n}=e^{-\frac1n \log(n!)}$$ Note that we can easily bound $\log(n!)=\sum\_{k=1}^n\log(k)$ using $$n\log(n)-n+1=\int\_1^n \log(x)\,dx\le \log(n!)\le \int\_1^{n+1} \log(x)\,dx=(n+1)\log(n+1)-n$$ Therefore, we have the inequalities $$-\left(1+\frac1n\right)\log(n+1)+1\le -\frac{\log(n!)}{n}\le -\log(n)+1-\frac1n$$ which obviously show that $\lim\_{n\to \infty}-\frac1n\log(n!)= -\infty$. Finally, we can conclude that $$\bbox[5px,border:2px solid #C0A000]{\lim\_{n\to \infty}\left(\frac1{n!}\right)^{1/n}=0}$$ And we are done!
1,628,649
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another. My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
2016/01/27
[ "https://math.stackexchange.com/questions/1628649", "https://math.stackexchange.com", "https://math.stackexchange.com/users/308347/" ]
**An easy way :** Take , $\displaystyle a\_n=\frac{1}{n!}$. Then , $\displaystyle \frac{a\_{n+1}}{a\_n}=\frac{1}{n+1}\to 0 \text{ , as } n\to \infty $. So by **Cauchy's second limit theorem** , $\displaystyle a\_n^{1/n}\to 0 \text{ , as } n\to \infty$.
Using Stirling's Approximation: $$n!\sim\sqrt{2\pi n}(\frac n e)^n \text{ as } n\to\infty$$ We have: \begin{align} \lim\_{n\to\infty}(\frac 1 {n!})^{\frac 1n}&=\lim\_{n\to\infty}[\sqrt{2\pi n}(\frac n e)^n]^{-\frac 1n}\\&=\lim\_{n\to\infty}[(2\pi)^{-\frac 1 {2n}}\cdot n^{-\frac 1{2n}}\cdot\frac en]\\&=\lim\_{n\to\infty} (1\cdot1\cdot0)\\&=0 \end{align}
53,937,335
**Complicated JOIN query as:** ``` SELECT FIRST.NAME, SECOND.FIRST_NAME, SECOND.LAST_NAME FROM FIRST_TABLE FIRST LEFT JOIN SECOND_TABLE SECOND ON (SECOND.FIRST_NAME = FIRST.NAME OR SECOND.LAST_NAME = FIRST.NAME) ``` Will result with bad performance. ***How to get better performance?***
2018/12/26
[ "https://Stackoverflow.com/questions/53937335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8142917/" ]
THIS ANSWERS THE ORIGINAL VERSION OF THE QUESTION. You may be better off with `exists`: ``` SELECT FIRST.ID, FIRST.NAME FROM FIRST_TABLE FIRST WHERE EXISTS (SELECT 1 FROM SECOND_TABLE SECOND WHERE SECOND.FIRST_NAME = FIRST.NAME) OR EXISTS (SELECT 1 FROM SECOND_TABLE SECOND WHERE SECOND.LAST_NAME = FIRST.NAME); ``` Then for performance, you want indexes on `SECOND_TABLE(LAST_NAME)` AND `SECOND_TABLE(FIRST_NAME)`.
You could try this, see what you get. It would depend a lot on the indexes on `FIRST_NAME` and `LAST_NAME`, but it avoids the `OR`. ``` SELECT FIRST.NAME, SECOND.FIRST_NAME, SECOND.LAST_NAME FROM FIRST_TABLE FIRST LEFT JOIN ( SELECT S1.FIRST_NAME as TEST_NAME, S1.FIRST_NAME, S1.LAST_NAME FROM SECOND_TABLE S1 WHERE S1.FIRST_NAME <> S1.LAST_NAME UNION ALL SELECT S2.LAST_NAME as TEST_NAME, S2.FIRST_NAME, S2.LAST_NAME FROM SECOND_TABLE S2 ) AS SECOND ON FIRST.NAME = SECOND.TEST_NAME ```
14,163,007
Textbox or richtextbox, only thing i want is triggering a function when scrollbar moves. I already found GetScrollPos and SetScrollPos. I thought of checking scrollbar position periodically but there must be a better way. So, what is the better way? Update: Using WinForms
2013/01/04
[ "https://Stackoverflow.com/questions/14163007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/766850/" ]
Assuming WinForms, you can try pinvoking: ``` public class MyRTF: RichTextBox { private const int WM_HSCROLL = 0x114; private const int WM_VSCROLL = 0x115; private const int WM_MOUSEWHEEL = 0x20A; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_VSCROLL || m.Msg == WM_HSCROLL || m.Msg == WM_MOUSEWHEEL) { // scrolling... } } } ```
Even better -- the hidden `MouseWheel` event: <https://stackoverflow.com/a/26672097/1037948> ``` public Form1() { InitializeComponent(); textBox1.MouseWheel += textBox1_MouseWheel; } void textBox1_MouseWheel(object sender, MouseEventArgs e) { throw new NotImplementedException(); } ```
14,163,007
Textbox or richtextbox, only thing i want is triggering a function when scrollbar moves. I already found GetScrollPos and SetScrollPos. I thought of checking scrollbar position periodically but there must be a better way. So, what is the better way? Update: Using WinForms
2013/01/04
[ "https://Stackoverflow.com/questions/14163007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/766850/" ]
Assuming WinForms, you can try pinvoking: ``` public class MyRTF: RichTextBox { private const int WM_HSCROLL = 0x114; private const int WM_VSCROLL = 0x115; private const int WM_MOUSEWHEEL = 0x20A; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_VSCROLL || m.Msg == WM_HSCROLL || m.Msg == WM_MOUSEWHEEL) { // scrolling... } } } ```
Adapted the accepted answer to include HorizontalScrollPosition and VerticalScrollPosition properties (to get and set the scroll positions) and ScrollChanged event (which uses .NET's ScrollEventArgs). ScrollChanged will also fire on key navigation and text modification as well as during selection drag, control resize, and font resize. ```cs /// <summary> /// TextBox with support for getting and setting the vertical scroll bar /// position, as well as listening to vertical scroll events. /// </summary> public class ScrollTextBox : System.Windows.Forms.TextBox { public ScrollTextBox() { _components = new System.ComponentModel.Container(); // Calculate width of "W" to set as the small horizontal increment OnFontChanged(null); } [ System.ComponentModel.DefaultValue(0) , System.ComponentModel.Category("Appearance") , System.ComponentModel.Description ( "Gets or sets the vertical scroll bar's position" ) ] public int VerticalScrollPosition { set { SetScroll(value, Win32.WM_VSCROLL, Win32.SB_VERT); } get { return GetScroll(Win32.SB_VERT); } } [ System.ComponentModel.DefaultValue(0) , System.ComponentModel.Category("Appearance") , System.ComponentModel.Description ( "Gets or sets the horizontal scroll bar's position" ) ] public int HorizontalScrollPosition { set { SetScroll(value, Win32.WM_HSCROLL, Win32.SB_HORZ); } get { return GetScroll(Win32.SB_HORZ); } } [ System.ComponentModel.Description ( "Fired when the scroll bar's vertical position changes" ) , System.ComponentModel.Category("Property Changed") ] public event System.Windows.Forms.ScrollEventHandler ScrollChanged; // Fire scroll event if the scroll-bars are moved protected override void WndProc ( ref System.Windows.Forms.Message message ){ base.WndProc(ref message); if(message.Msg == Win32.WM_VSCROLL || message.Msg == Win32.WM_HSCROLL || message.Msg == Win32.WM_MOUSEWHEEL ) TryFireScrollEvent(); } // Key-down includes navigation keys, but also typing and pasting can // cause a scroll event protected override void OnKeyDown ( System.Windows.Forms.KeyEventArgs e ){ base.OnKeyDown(e); TryFireScrollEvent(); } protected override void OnKeyUp ( System.Windows.Forms.KeyEventArgs e ){ base.OnKeyUp(e); TryFireScrollEvent(); } // Resizing can alter the word-wrap or fit the content causing the text // to scroll protected override void OnResize ( System.EventArgs e ){ base.OnResize(e); TryFireScrollEvent(); } // Clicking an empty space can move the carot to the beginning of the // line causing a scroll event protected override void OnMouseDown ( System.Windows.Forms.MouseEventArgs e ){ base.OnMouseDown(e); TryFireScrollEvent(); } protected override void OnMouseUp ( System.Windows.Forms.MouseEventArgs e ){ base.OnMouseUp(e); TryFireScrollEvent(); } // If the mouse button is down, a text selection is probably being done // where dragging the selection can caues scroll events protected override void OnMouseMove ( System.Windows.Forms.MouseEventArgs e ){ base.OnMouseMove(e); if(e.Button != System.Windows.Forms.MouseButtons.None) TryFireScrollEvent(); } // Changing the size of the font can cause a scroll event. Also, when // scrolling horizontally, the event will notify whether the scroll // was a large or small change. For vertical, small increments are 1 // line, but for horizontal, it is several pixels. To guess what a // small increment is, get the width of the W character and anything // smaller than that will be represented as a small increment protected override void OnFontChanged ( System.EventArgs e ){ base.OnFontChanged(e); using(System.Drawing.Graphics graphics = this.CreateGraphics()) _fontWidth = (int)graphics.MeasureString("W", this.Font).Width; TryFireScrollEvent(); } protected override void Dispose ( bool disposing ){ if(disposing && (_components != null)) _components.Dispose(); base.Dispose(disposing); } private void SetScroll ( int value , uint windowsMessage , int scrollBarMessage ){ Win32.SetScrollPos ( (System.IntPtr)this.Handle , scrollBarMessage , value , true ); Win32.PostMessage ( (System.IntPtr)this.Handle , windowsMessage , 4 + 0x10000 * value , 0 ); } private int GetScroll ( int scrollBarMessage ){ return Win32.GetScrollPos ( (System.IntPtr)this.Handle , scrollBarMessage ); } // Fire both horizontal and vertical scroll events seperately, one // after the other. These first test if a scroll actually occurred // and won't fire if there was no actual movement private void TryFireScrollEvent() { // Don't do anything if there is no event handler if(ScrollChanged == null) return; TryFireHorizontalScrollEvent(); TryFireVerticalScrollEvent(); } private void TryFireHorizontalScrollEvent() { // Don't do anything if there is no event handler if(ScrollChanged == null) return; int lastScrollPosition = _lastHorizontalScrollPosition; int scrollPosition = HorizontalScrollPosition; // Don't do anything if there was no change in position if(scrollPosition == lastScrollPosition) return; _lastHorizontalScrollPosition = scrollPosition; ScrollChanged ( this , new System.Windows.Forms.ScrollEventArgs ( scrollPosition < lastScrollPosition - _fontWidth ? System.Windows.Forms.ScrollEventType.LargeDecrement : scrollPosition > lastScrollPosition + _fontWidth ? System.Windows.Forms.ScrollEventType.LargeIncrement : scrollPosition < lastScrollPosition ? System.Windows.Forms.ScrollEventType.SmallDecrement : System.Windows.Forms.ScrollEventType.SmallIncrement , lastScrollPosition , scrollPosition , System.Windows.Forms.ScrollOrientation.HorizontalScroll ) ); } private void TryFireVerticalScrollEvent() { // Don't do anything if there is no event handler if(ScrollChanged == null) return; int lastScrollPosition = _lastVerticalScrollPosition; int scrollPosition = VerticalScrollPosition; // Don't do anything if there was no change in position if(scrollPosition == lastScrollPosition) return; _lastVerticalScrollPosition = scrollPosition; ScrollChanged ( this , new System.Windows.Forms.ScrollEventArgs ( scrollPosition < lastScrollPosition - 1 ? System.Windows.Forms.ScrollEventType.LargeDecrement : scrollPosition > lastScrollPosition + 1 ? System.Windows.Forms.ScrollEventType.LargeIncrement : scrollPosition < lastScrollPosition ? System.Windows.Forms.ScrollEventType.SmallDecrement : System.Windows.Forms.ScrollEventType.SmallIncrement , lastScrollPosition , scrollPosition , System.Windows.Forms.ScrollOrientation.VerticalScroll ) ); } private int _lastVerticalScrollPosition; private int _lastHorizontalScrollPosition; private int _fontWidth; private System.ComponentModel.IContainer _components = null; private static class Win32 { public const uint WM_HSCROLL = 0x114; public const uint WM_VSCROLL = 0x115; public const uint WM_MOUSEWHEEL = 0x20A; public const int SB_VERT = 0x1; public const int SB_HORZ = 0x0; [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern int SetScrollPos ( System.IntPtr hWnd , int nBar , int nPos , bool bRedraw ); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern int GetScrollPos ( System.IntPtr hWnd , int nBar ); [ System.Runtime.InteropServices.DllImport ( "User32.Dll" , EntryPoint = "PostMessageA") ] public static extern bool PostMessage ( System.IntPtr hWnd , uint msg , int wParam , int lParam ); } } ```
14,163,007
Textbox or richtextbox, only thing i want is triggering a function when scrollbar moves. I already found GetScrollPos and SetScrollPos. I thought of checking scrollbar position periodically but there must be a better way. So, what is the better way? Update: Using WinForms
2013/01/04
[ "https://Stackoverflow.com/questions/14163007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/766850/" ]
Adapted the accepted answer to include HorizontalScrollPosition and VerticalScrollPosition properties (to get and set the scroll positions) and ScrollChanged event (which uses .NET's ScrollEventArgs). ScrollChanged will also fire on key navigation and text modification as well as during selection drag, control resize, and font resize. ```cs /// <summary> /// TextBox with support for getting and setting the vertical scroll bar /// position, as well as listening to vertical scroll events. /// </summary> public class ScrollTextBox : System.Windows.Forms.TextBox { public ScrollTextBox() { _components = new System.ComponentModel.Container(); // Calculate width of "W" to set as the small horizontal increment OnFontChanged(null); } [ System.ComponentModel.DefaultValue(0) , System.ComponentModel.Category("Appearance") , System.ComponentModel.Description ( "Gets or sets the vertical scroll bar's position" ) ] public int VerticalScrollPosition { set { SetScroll(value, Win32.WM_VSCROLL, Win32.SB_VERT); } get { return GetScroll(Win32.SB_VERT); } } [ System.ComponentModel.DefaultValue(0) , System.ComponentModel.Category("Appearance") , System.ComponentModel.Description ( "Gets or sets the horizontal scroll bar's position" ) ] public int HorizontalScrollPosition { set { SetScroll(value, Win32.WM_HSCROLL, Win32.SB_HORZ); } get { return GetScroll(Win32.SB_HORZ); } } [ System.ComponentModel.Description ( "Fired when the scroll bar's vertical position changes" ) , System.ComponentModel.Category("Property Changed") ] public event System.Windows.Forms.ScrollEventHandler ScrollChanged; // Fire scroll event if the scroll-bars are moved protected override void WndProc ( ref System.Windows.Forms.Message message ){ base.WndProc(ref message); if(message.Msg == Win32.WM_VSCROLL || message.Msg == Win32.WM_HSCROLL || message.Msg == Win32.WM_MOUSEWHEEL ) TryFireScrollEvent(); } // Key-down includes navigation keys, but also typing and pasting can // cause a scroll event protected override void OnKeyDown ( System.Windows.Forms.KeyEventArgs e ){ base.OnKeyDown(e); TryFireScrollEvent(); } protected override void OnKeyUp ( System.Windows.Forms.KeyEventArgs e ){ base.OnKeyUp(e); TryFireScrollEvent(); } // Resizing can alter the word-wrap or fit the content causing the text // to scroll protected override void OnResize ( System.EventArgs e ){ base.OnResize(e); TryFireScrollEvent(); } // Clicking an empty space can move the carot to the beginning of the // line causing a scroll event protected override void OnMouseDown ( System.Windows.Forms.MouseEventArgs e ){ base.OnMouseDown(e); TryFireScrollEvent(); } protected override void OnMouseUp ( System.Windows.Forms.MouseEventArgs e ){ base.OnMouseUp(e); TryFireScrollEvent(); } // If the mouse button is down, a text selection is probably being done // where dragging the selection can caues scroll events protected override void OnMouseMove ( System.Windows.Forms.MouseEventArgs e ){ base.OnMouseMove(e); if(e.Button != System.Windows.Forms.MouseButtons.None) TryFireScrollEvent(); } // Changing the size of the font can cause a scroll event. Also, when // scrolling horizontally, the event will notify whether the scroll // was a large or small change. For vertical, small increments are 1 // line, but for horizontal, it is several pixels. To guess what a // small increment is, get the width of the W character and anything // smaller than that will be represented as a small increment protected override void OnFontChanged ( System.EventArgs e ){ base.OnFontChanged(e); using(System.Drawing.Graphics graphics = this.CreateGraphics()) _fontWidth = (int)graphics.MeasureString("W", this.Font).Width; TryFireScrollEvent(); } protected override void Dispose ( bool disposing ){ if(disposing && (_components != null)) _components.Dispose(); base.Dispose(disposing); } private void SetScroll ( int value , uint windowsMessage , int scrollBarMessage ){ Win32.SetScrollPos ( (System.IntPtr)this.Handle , scrollBarMessage , value , true ); Win32.PostMessage ( (System.IntPtr)this.Handle , windowsMessage , 4 + 0x10000 * value , 0 ); } private int GetScroll ( int scrollBarMessage ){ return Win32.GetScrollPos ( (System.IntPtr)this.Handle , scrollBarMessage ); } // Fire both horizontal and vertical scroll events seperately, one // after the other. These first test if a scroll actually occurred // and won't fire if there was no actual movement private void TryFireScrollEvent() { // Don't do anything if there is no event handler if(ScrollChanged == null) return; TryFireHorizontalScrollEvent(); TryFireVerticalScrollEvent(); } private void TryFireHorizontalScrollEvent() { // Don't do anything if there is no event handler if(ScrollChanged == null) return; int lastScrollPosition = _lastHorizontalScrollPosition; int scrollPosition = HorizontalScrollPosition; // Don't do anything if there was no change in position if(scrollPosition == lastScrollPosition) return; _lastHorizontalScrollPosition = scrollPosition; ScrollChanged ( this , new System.Windows.Forms.ScrollEventArgs ( scrollPosition < lastScrollPosition - _fontWidth ? System.Windows.Forms.ScrollEventType.LargeDecrement : scrollPosition > lastScrollPosition + _fontWidth ? System.Windows.Forms.ScrollEventType.LargeIncrement : scrollPosition < lastScrollPosition ? System.Windows.Forms.ScrollEventType.SmallDecrement : System.Windows.Forms.ScrollEventType.SmallIncrement , lastScrollPosition , scrollPosition , System.Windows.Forms.ScrollOrientation.HorizontalScroll ) ); } private void TryFireVerticalScrollEvent() { // Don't do anything if there is no event handler if(ScrollChanged == null) return; int lastScrollPosition = _lastVerticalScrollPosition; int scrollPosition = VerticalScrollPosition; // Don't do anything if there was no change in position if(scrollPosition == lastScrollPosition) return; _lastVerticalScrollPosition = scrollPosition; ScrollChanged ( this , new System.Windows.Forms.ScrollEventArgs ( scrollPosition < lastScrollPosition - 1 ? System.Windows.Forms.ScrollEventType.LargeDecrement : scrollPosition > lastScrollPosition + 1 ? System.Windows.Forms.ScrollEventType.LargeIncrement : scrollPosition < lastScrollPosition ? System.Windows.Forms.ScrollEventType.SmallDecrement : System.Windows.Forms.ScrollEventType.SmallIncrement , lastScrollPosition , scrollPosition , System.Windows.Forms.ScrollOrientation.VerticalScroll ) ); } private int _lastVerticalScrollPosition; private int _lastHorizontalScrollPosition; private int _fontWidth; private System.ComponentModel.IContainer _components = null; private static class Win32 { public const uint WM_HSCROLL = 0x114; public const uint WM_VSCROLL = 0x115; public const uint WM_MOUSEWHEEL = 0x20A; public const int SB_VERT = 0x1; public const int SB_HORZ = 0x0; [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern int SetScrollPos ( System.IntPtr hWnd , int nBar , int nPos , bool bRedraw ); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern int GetScrollPos ( System.IntPtr hWnd , int nBar ); [ System.Runtime.InteropServices.DllImport ( "User32.Dll" , EntryPoint = "PostMessageA") ] public static extern bool PostMessage ( System.IntPtr hWnd , uint msg , int wParam , int lParam ); } } ```
Even better -- the hidden `MouseWheel` event: <https://stackoverflow.com/a/26672097/1037948> ``` public Form1() { InitializeComponent(); textBox1.MouseWheel += textBox1_MouseWheel; } void textBox1_MouseWheel(object sender, MouseEventArgs e) { throw new NotImplementedException(); } ```
13,238
What constitutes a vampire "nest"? Is it just the home of several vampires, or does it have to actually be "nest" like (i.e. dirty, dark, stinky, unpleasant)? For instance, I've never seen the Cullen's house referred to as a nest, since they're sort of civilized. But in the first season of True Blood there were three vampires living in a house and it was referred to as a nest. Is there a distinction? Or just the preference of the author writing the vampires? Is Jean Claude's building in the Anita Blake series considered a nest? Also, what is the first mention of a 'vampire nest' in fiction?
2012/03/16
[ "https://scifi.stackexchange.com/questions/13238", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/3102/" ]
It depends on the series that is under consideration. Typically, a 'nest' of vampires is used by mortals who are exterminating vampires - Blade, Buffy, etc will use the term. This plays into their human desire to distance their foes from humanity. In works where vampires are portrayed more sympathetically, every effort is made to 'humanize' the vampires (or make them 'better than human'). I'm unable to find a reference to the first usage of 'nest' to refer to a group of vampires. The earliest I can recall is Blade (or possibly John Carpenter's Vampires) but both of those are fairly recent (in terms of movies).
The first time I encountered the term was in the movie The Lost Boys (1987).
13,238
What constitutes a vampire "nest"? Is it just the home of several vampires, or does it have to actually be "nest" like (i.e. dirty, dark, stinky, unpleasant)? For instance, I've never seen the Cullen's house referred to as a nest, since they're sort of civilized. But in the first season of True Blood there were three vampires living in a house and it was referred to as a nest. Is there a distinction? Or just the preference of the author writing the vampires? Is Jean Claude's building in the Anita Blake series considered a nest? Also, what is the first mention of a 'vampire nest' in fiction?
2012/03/16
[ "https://scifi.stackexchange.com/questions/13238", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/3102/" ]
It depends on the series that is under consideration. Typically, a 'nest' of vampires is used by mortals who are exterminating vampires - Blade, Buffy, etc will use the term. This plays into their human desire to distance their foes from humanity. In works where vampires are portrayed more sympathetically, every effort is made to 'humanize' the vampires (or make them 'better than human'). I'm unable to find a reference to the first usage of 'nest' to refer to a group of vampires. The earliest I can recall is Blade (or possibly John Carpenter's Vampires) but both of those are fairly recent (in terms of movies).
the word has different connotations in different works mainly because there are different kinds of vampires john carpenters vampires had a "queen" vampire that had a psychic link to his children (its been awhile but I think the sired vampires had a basic drone level of intelligence as well) in true blood Nests are described by Bill as causing the vampires living in them to become more cruel the behavior could be mystical or it could just be behavioral reinforcement buffy and angel both referenced nests but I dont think they meant anything more than a place where a group of vampires lived (unlived) together. they also used the word nest to refer to things other than vampires personally I always kinda assumed the word nest was the proper way to refer to a group of vampires, kinda like a murder of crows or a waddle of penguins as to the first usage I cant help you
13,238
What constitutes a vampire "nest"? Is it just the home of several vampires, or does it have to actually be "nest" like (i.e. dirty, dark, stinky, unpleasant)? For instance, I've never seen the Cullen's house referred to as a nest, since they're sort of civilized. But in the first season of True Blood there were three vampires living in a house and it was referred to as a nest. Is there a distinction? Or just the preference of the author writing the vampires? Is Jean Claude's building in the Anita Blake series considered a nest? Also, what is the first mention of a 'vampire nest' in fiction?
2012/03/16
[ "https://scifi.stackexchange.com/questions/13238", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/3102/" ]
It depends on the series that is under consideration. Typically, a 'nest' of vampires is used by mortals who are exterminating vampires - Blade, Buffy, etc will use the term. This plays into their human desire to distance their foes from humanity. In works where vampires are portrayed more sympathetically, every effort is made to 'humanize' the vampires (or make them 'better than human'). I'm unable to find a reference to the first usage of 'nest' to refer to a group of vampires. The earliest I can recall is Blade (or possibly John Carpenter's Vampires) but both of those are fairly recent (in terms of movies).
I think it is similar to a wasps' nest -- not something cozy but rather like what animals would build. For example, in the Fright Night remake (and maybe in the original, I don't recall) the head vampire simple stores his brood in the basement -- it is a practical place for them, out of the light but they have no comforts nor do they need them -- presumably the head vampire just throws victims to them occasionally and then they emerge from holes in the wall or floor.
13,238
What constitutes a vampire "nest"? Is it just the home of several vampires, or does it have to actually be "nest" like (i.e. dirty, dark, stinky, unpleasant)? For instance, I've never seen the Cullen's house referred to as a nest, since they're sort of civilized. But in the first season of True Blood there were three vampires living in a house and it was referred to as a nest. Is there a distinction? Or just the preference of the author writing the vampires? Is Jean Claude's building in the Anita Blake series considered a nest? Also, what is the first mention of a 'vampire nest' in fiction?
2012/03/16
[ "https://scifi.stackexchange.com/questions/13238", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/3102/" ]
First mention of the phrase I could find: Percy MacKaye's "[The Canterbury Pilgrims](http://en.wikipedia.org/wiki/The_Canterbury_Pilgrims)" play (1903) > > Oh, monstrous brood, hatched in a vampire's nest ! But I will be revenged > > > As far as what a nest is, it depends on the work in question. "Night/Day Watch" series by Lukyanenko defined a nest as vampires initiated by a given "originating" vampire - that is a frequent interpretation.
The first time I encountered the term was in the movie The Lost Boys (1987).
13,238
What constitutes a vampire "nest"? Is it just the home of several vampires, or does it have to actually be "nest" like (i.e. dirty, dark, stinky, unpleasant)? For instance, I've never seen the Cullen's house referred to as a nest, since they're sort of civilized. But in the first season of True Blood there were three vampires living in a house and it was referred to as a nest. Is there a distinction? Or just the preference of the author writing the vampires? Is Jean Claude's building in the Anita Blake series considered a nest? Also, what is the first mention of a 'vampire nest' in fiction?
2012/03/16
[ "https://scifi.stackexchange.com/questions/13238", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/3102/" ]
First mention of the phrase I could find: Percy MacKaye's "[The Canterbury Pilgrims](http://en.wikipedia.org/wiki/The_Canterbury_Pilgrims)" play (1903) > > Oh, monstrous brood, hatched in a vampire's nest ! But I will be revenged > > > As far as what a nest is, it depends on the work in question. "Night/Day Watch" series by Lukyanenko defined a nest as vampires initiated by a given "originating" vampire - that is a frequent interpretation.
the word has different connotations in different works mainly because there are different kinds of vampires john carpenters vampires had a "queen" vampire that had a psychic link to his children (its been awhile but I think the sired vampires had a basic drone level of intelligence as well) in true blood Nests are described by Bill as causing the vampires living in them to become more cruel the behavior could be mystical or it could just be behavioral reinforcement buffy and angel both referenced nests but I dont think they meant anything more than a place where a group of vampires lived (unlived) together. they also used the word nest to refer to things other than vampires personally I always kinda assumed the word nest was the proper way to refer to a group of vampires, kinda like a murder of crows or a waddle of penguins as to the first usage I cant help you
13,238
What constitutes a vampire "nest"? Is it just the home of several vampires, or does it have to actually be "nest" like (i.e. dirty, dark, stinky, unpleasant)? For instance, I've never seen the Cullen's house referred to as a nest, since they're sort of civilized. But in the first season of True Blood there were three vampires living in a house and it was referred to as a nest. Is there a distinction? Or just the preference of the author writing the vampires? Is Jean Claude's building in the Anita Blake series considered a nest? Also, what is the first mention of a 'vampire nest' in fiction?
2012/03/16
[ "https://scifi.stackexchange.com/questions/13238", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/3102/" ]
First mention of the phrase I could find: Percy MacKaye's "[The Canterbury Pilgrims](http://en.wikipedia.org/wiki/The_Canterbury_Pilgrims)" play (1903) > > Oh, monstrous brood, hatched in a vampire's nest ! But I will be revenged > > > As far as what a nest is, it depends on the work in question. "Night/Day Watch" series by Lukyanenko defined a nest as vampires initiated by a given "originating" vampire - that is a frequent interpretation.
I think it is similar to a wasps' nest -- not something cozy but rather like what animals would build. For example, in the Fright Night remake (and maybe in the original, I don't recall) the head vampire simple stores his brood in the basement -- it is a practical place for them, out of the light but they have no comforts nor do they need them -- presumably the head vampire just throws victims to them occasionally and then they emerge from holes in the wall or floor.
13,238
What constitutes a vampire "nest"? Is it just the home of several vampires, or does it have to actually be "nest" like (i.e. dirty, dark, stinky, unpleasant)? For instance, I've never seen the Cullen's house referred to as a nest, since they're sort of civilized. But in the first season of True Blood there were three vampires living in a house and it was referred to as a nest. Is there a distinction? Or just the preference of the author writing the vampires? Is Jean Claude's building in the Anita Blake series considered a nest? Also, what is the first mention of a 'vampire nest' in fiction?
2012/03/16
[ "https://scifi.stackexchange.com/questions/13238", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/3102/" ]
the word has different connotations in different works mainly because there are different kinds of vampires john carpenters vampires had a "queen" vampire that had a psychic link to his children (its been awhile but I think the sired vampires had a basic drone level of intelligence as well) in true blood Nests are described by Bill as causing the vampires living in them to become more cruel the behavior could be mystical or it could just be behavioral reinforcement buffy and angel both referenced nests but I dont think they meant anything more than a place where a group of vampires lived (unlived) together. they also used the word nest to refer to things other than vampires personally I always kinda assumed the word nest was the proper way to refer to a group of vampires, kinda like a murder of crows or a waddle of penguins as to the first usage I cant help you
The first time I encountered the term was in the movie The Lost Boys (1987).
13,238
What constitutes a vampire "nest"? Is it just the home of several vampires, or does it have to actually be "nest" like (i.e. dirty, dark, stinky, unpleasant)? For instance, I've never seen the Cullen's house referred to as a nest, since they're sort of civilized. But in the first season of True Blood there were three vampires living in a house and it was referred to as a nest. Is there a distinction? Or just the preference of the author writing the vampires? Is Jean Claude's building in the Anita Blake series considered a nest? Also, what is the first mention of a 'vampire nest' in fiction?
2012/03/16
[ "https://scifi.stackexchange.com/questions/13238", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/3102/" ]
I think it is similar to a wasps' nest -- not something cozy but rather like what animals would build. For example, in the Fright Night remake (and maybe in the original, I don't recall) the head vampire simple stores his brood in the basement -- it is a practical place for them, out of the light but they have no comforts nor do they need them -- presumably the head vampire just throws victims to them occasionally and then they emerge from holes in the wall or floor.
The first time I encountered the term was in the movie The Lost Boys (1987).
42,865,955
I would like to have a pop up message appear every time a cell contains specific text. Everytime the word "Red Level" is in any of this cells (I22,I23,I34,I35,I36), I would like a MsgBox to appear. I am using a data validation list in all those cells mentioned above, to make sure the word "Red Level" is always the same. I wrote some code and it worked but only when I had 1 cell in my range. When I tried to add the other cell numbers to my code, it will still only work for the first cell and not for the rest. Below is the code that worked for one cell: ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Worksheets("A12").Range("I22").Value = "Red Level" Then MsgBox ("Please call maintenance immediately to refill reservoir") End If End Sub ``` I thought I could just add the rest of the cells to the range on my code, but that did not work. This is what I did but did not work (The MsgBox will only appear when the word "Red Level is on I22 and not in the other cells): ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Sheets("A12").Range("I22,I23,I34,I35,I36").Value = "Red Level" Then MsgBox ("Please call maintenance immediately to refill reservoir") End If End Sub ```
2017/03/17
[ "https://Stackoverflow.com/questions/42865955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6707084/" ]
For this, you can do it two ways (at least). If you want to stay with `If`, you need lots of `Or`: ``` If Sheets("A12").Range("I22").Value = "Red Level" or Sheets("A12").Range("I23").Value = "Red Level" or ... Then ``` But as you can see, it'll be a really long line, which isn't the most straightforward to read. Here's an alternative: ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.EnableEvents = False Dim addr() As Variant Dim hasPrompted As Boolean hasPrompted = False addr = Array("$I$22", "$I$23", "$I$34", "$I$35", "$I$36") Dim i As Long For i = LBound(addr) To UBound(addr) If Range(addr(i)).Value = "Red Level" And Not hasPrompted Then MsgBox ("Please call maintenance immediately to refill reservoir") hasPrompted = True End If Next i Application.EnableEvents = True End Sub ``` Note the second one will only fire one time, even if all cells have "Red Level", or just one cell has it. If you want to alert the user which cells have it, you can add that in, just let me know.
The DATA tab has a wizard for data validation, The first tab allows you to define a condition. The third tab of this wizard is for a message popup. You don't need to write code for this, S it is already built in to excel. <http://www.excel-easy.com/basics/data-validation.html>
42,865,955
I would like to have a pop up message appear every time a cell contains specific text. Everytime the word "Red Level" is in any of this cells (I22,I23,I34,I35,I36), I would like a MsgBox to appear. I am using a data validation list in all those cells mentioned above, to make sure the word "Red Level" is always the same. I wrote some code and it worked but only when I had 1 cell in my range. When I tried to add the other cell numbers to my code, it will still only work for the first cell and not for the rest. Below is the code that worked for one cell: ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Worksheets("A12").Range("I22").Value = "Red Level" Then MsgBox ("Please call maintenance immediately to refill reservoir") End If End Sub ``` I thought I could just add the rest of the cells to the range on my code, but that did not work. This is what I did but did not work (The MsgBox will only appear when the word "Red Level is on I22 and not in the other cells): ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Sheets("A12").Range("I22,I23,I34,I35,I36").Value = "Red Level" Then MsgBox ("Please call maintenance immediately to refill reservoir") End If End Sub ```
2017/03/17
[ "https://Stackoverflow.com/questions/42865955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6707084/" ]
For this, you can do it two ways (at least). If you want to stay with `If`, you need lots of `Or`: ``` If Sheets("A12").Range("I22").Value = "Red Level" or Sheets("A12").Range("I23").Value = "Red Level" or ... Then ``` But as you can see, it'll be a really long line, which isn't the most straightforward to read. Here's an alternative: ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) Application.EnableEvents = False Dim addr() As Variant Dim hasPrompted As Boolean hasPrompted = False addr = Array("$I$22", "$I$23", "$I$34", "$I$35", "$I$36") Dim i As Long For i = LBound(addr) To UBound(addr) If Range(addr(i)).Value = "Red Level" And Not hasPrompted Then MsgBox ("Please call maintenance immediately to refill reservoir") hasPrompted = True End If Next i Application.EnableEvents = True End Sub ``` Note the second one will only fire one time, even if all cells have "Red Level", or just one cell has it. If you want to alert the user which cells have it, you can add that in, just let me know.
why not using find on the wanted cells range? ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Not Worksheets("A12").Range("I22,I23,I34:I36").Find(what:="Red Level", LookIn:=xlValues, lookat:=xlWhole) Is Nothing Then MsgBox "Please call maintenance immediately to refill reservoir" End Sub ``` and, as @Jeeped already said, if the worksheet you're monitoring event of is named after "A12" then you can omit the `Worksheets("A12").` part
42,865,955
I would like to have a pop up message appear every time a cell contains specific text. Everytime the word "Red Level" is in any of this cells (I22,I23,I34,I35,I36), I would like a MsgBox to appear. I am using a data validation list in all those cells mentioned above, to make sure the word "Red Level" is always the same. I wrote some code and it worked but only when I had 1 cell in my range. When I tried to add the other cell numbers to my code, it will still only work for the first cell and not for the rest. Below is the code that worked for one cell: ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Worksheets("A12").Range("I22").Value = "Red Level" Then MsgBox ("Please call maintenance immediately to refill reservoir") End If End Sub ``` I thought I could just add the rest of the cells to the range on my code, but that did not work. This is what I did but did not work (The MsgBox will only appear when the word "Red Level is on I22 and not in the other cells): ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Sheets("A12").Range("I22,I23,I34,I35,I36").Value = "Red Level" Then MsgBox ("Please call maintenance immediately to refill reservoir") End If End Sub ```
2017/03/17
[ "https://Stackoverflow.com/questions/42865955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6707084/" ]
You could use the worksheet's MATCH but it will not work on discontiguous cells so two checks must be made. ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) if not iserror(application.match("red level", Range("I22:I23"), 0)) or _ not iserror(application.match("red level", Range("I34:I36"), 0)) then 'Red Level is is at least one of the discontiguous cells MsgBox ("Please call maintenance immediately to refill reservoir") end if End Sub ``` It's unclear what actually drives 'Red Level' to appear in range("I22:I23, I34:I36"). This may be better as a Worksheet\_Change. As is, the user cannot navigate through the worksheet if one or more of the cells remains 'Red Level'. On a related note: is this within the A12 worksheet's code sheet? If so (as a private sub within the worksheet's code sheet), defining the parent worksheet with `Worksheets("A12")` is unnecessary. My code has removed the parent worksheet reference.
The DATA tab has a wizard for data validation, The first tab allows you to define a condition. The third tab of this wizard is for a message popup. You don't need to write code for this, S it is already built in to excel. <http://www.excel-easy.com/basics/data-validation.html>
42,865,955
I would like to have a pop up message appear every time a cell contains specific text. Everytime the word "Red Level" is in any of this cells (I22,I23,I34,I35,I36), I would like a MsgBox to appear. I am using a data validation list in all those cells mentioned above, to make sure the word "Red Level" is always the same. I wrote some code and it worked but only when I had 1 cell in my range. When I tried to add the other cell numbers to my code, it will still only work for the first cell and not for the rest. Below is the code that worked for one cell: ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Worksheets("A12").Range("I22").Value = "Red Level" Then MsgBox ("Please call maintenance immediately to refill reservoir") End If End Sub ``` I thought I could just add the rest of the cells to the range on my code, but that did not work. This is what I did but did not work (The MsgBox will only appear when the word "Red Level is on I22 and not in the other cells): ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Sheets("A12").Range("I22,I23,I34,I35,I36").Value = "Red Level" Then MsgBox ("Please call maintenance immediately to refill reservoir") End If End Sub ```
2017/03/17
[ "https://Stackoverflow.com/questions/42865955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6707084/" ]
You could use the worksheet's MATCH but it will not work on discontiguous cells so two checks must be made. ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) if not iserror(application.match("red level", Range("I22:I23"), 0)) or _ not iserror(application.match("red level", Range("I34:I36"), 0)) then 'Red Level is is at least one of the discontiguous cells MsgBox ("Please call maintenance immediately to refill reservoir") end if End Sub ``` It's unclear what actually drives 'Red Level' to appear in range("I22:I23, I34:I36"). This may be better as a Worksheet\_Change. As is, the user cannot navigate through the worksheet if one or more of the cells remains 'Red Level'. On a related note: is this within the A12 worksheet's code sheet? If so (as a private sub within the worksheet's code sheet), defining the parent worksheet with `Worksheets("A12")` is unnecessary. My code has removed the parent worksheet reference.
why not using find on the wanted cells range? ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Not Worksheets("A12").Range("I22,I23,I34:I36").Find(what:="Red Level", LookIn:=xlValues, lookat:=xlWhole) Is Nothing Then MsgBox "Please call maintenance immediately to refill reservoir" End Sub ``` and, as @Jeeped already said, if the worksheet you're monitoring event of is named after "A12" then you can omit the `Worksheets("A12").` part
69,547,905
I'm trying to deploy an app on heroku but i can't if i use dotenv. This code doesn't work: ```js mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true }, () => { console.log("Connected to db successfully"); }); ``` But this does: ```js mongoose.connect("mongodb+srv://test:[email protected]/ecommerce?retryWrites=true&w=majority", { useNewUrlParser: true }, () => { console.log("Connected to db successfully"); }); ``` When i try to use dotenv heroku throws this error: ``` MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string. ```
2021/10/12
[ "https://Stackoverflow.com/questions/69547905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14716818/" ]
I had to go to heroku dashboard> settings> config vars and then add the key as MONGO\_URI and the mongo url value that mongodb gave me
You need to make sure of two things 1. go to heroku dashboard> settings> config vars and then add the key as MONGO\_URI and the mongo url value that mongodb gave me... this info is in the .env file of your project. you might have with another name like DATA\_BASE\_MONGO just make sure to use that name and key in the config vars. 2. Heroku dynamically assigns your app a port, so you can't set the port to a fixed number. Heroku adds the port to the env, so you can pull it from there. Switch your listen to this: **.listen(process.env.PORT || 5000)**, probably yo have it like .listen(5000), just make sure to change it. And thats`s it you will have your app running.
6,043,381
I have the following query (slightly amended for clarity): ``` CREATE PROCEDURE Kctc.CaseTasks_GetCaseTasks @CaseNumber int ... other parameters ,@ChangedBefore datetime ,@ChangedAfter datetime AS SELECT Kctc.CaseTasks.CaseTaskId ...blah blah blah FROM Kctc.CaseTasks ... some joins here WHERE ... some normal where clauses AND ( (@ChangedAfter IS NULL AND @ChangedBefore IS NULL) OR EXISTS (SELECT * FROM Kctc.FieldChanges WHERE Kctc.FieldChanges.RecordId = Kctc.CaseTasks.CaseTaskId AND Kctc.FieldChanges.TableName = 'CaseTasks' AND Kctc.FieldChanges.DateOfChange BETWEEN ISNULL(@ChangedAfter, '2000/01/01') AND ISNULL(@ChangedBefore, '2050/01/01')) ) ``` This query times out whenever the user specifies values for `@ChangedBefore` or `@ChangedAfter`, therefore invoking the subquery. The subquery checks for the existence of a record in the table called `FieldChanges` (which effectively records changes to every field in the `CaseTasks` table). Querying `FieldChanges` isn't very efficient because it involves filtering on the text field `TableName` which isn't indexed. And I know that subqueries are inherently inefficient. So my question in general is, is there a way to redesign the query so that it performs better? I can't think of a way to express the subquery as a join while still returning just one `CaseTask` row when there are multiple associated `FieldChanges` (i.e. preserving the EXISTS semantic). I haven't yet indexed the `TableName` field of the `FieldChanges` table because I'm hesitant about indexing text fields. So what should I do?
2011/05/18
[ "https://Stackoverflow.com/questions/6043381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/164923/" ]
As a first cut you might try putting an index on the table Kctc.FieldChanges on the RecordId, TableName, and DateOfChange fields (one single index with all three fields) and see if that helps. Share and enjoy.
This is **not going to be a "good" solution**, but it might be better than what's happening right now: ``` SELECT Kctc.CaseTasks.CaseTaskId ...blah blah blah FROM Kctc.CaseTasks ... some joins here LEFT JOIN ( SELECT RecordID FROM Kctc.FieldChanges WHERE Kctc.FieldChanges.TableName = 'CaseTasks' AND Kctc.FieldChanges.DateOfChange BETWEEN ISNULL(@ChangedAfter, '2000/01/01') AND ISNULL(@ChangedBefore, '2050/01/01') GROUP BY RecordID ) AS MatchingChanges ON Kctc.CaseTasks.RecordId = MatchingChanges.RecordId WHERE ... some normal where clauses AND (MatchingChanges.RecordID Is Not Null OR ((@ChangedAfter IS NULL AND @ChangedBefore IS NULL)) ``` Depends on exactly what the query plan is - if it was performing the subquery repeatedly, this formulation might help.
6,043,381
I have the following query (slightly amended for clarity): ``` CREATE PROCEDURE Kctc.CaseTasks_GetCaseTasks @CaseNumber int ... other parameters ,@ChangedBefore datetime ,@ChangedAfter datetime AS SELECT Kctc.CaseTasks.CaseTaskId ...blah blah blah FROM Kctc.CaseTasks ... some joins here WHERE ... some normal where clauses AND ( (@ChangedAfter IS NULL AND @ChangedBefore IS NULL) OR EXISTS (SELECT * FROM Kctc.FieldChanges WHERE Kctc.FieldChanges.RecordId = Kctc.CaseTasks.CaseTaskId AND Kctc.FieldChanges.TableName = 'CaseTasks' AND Kctc.FieldChanges.DateOfChange BETWEEN ISNULL(@ChangedAfter, '2000/01/01') AND ISNULL(@ChangedBefore, '2050/01/01')) ) ``` This query times out whenever the user specifies values for `@ChangedBefore` or `@ChangedAfter`, therefore invoking the subquery. The subquery checks for the existence of a record in the table called `FieldChanges` (which effectively records changes to every field in the `CaseTasks` table). Querying `FieldChanges` isn't very efficient because it involves filtering on the text field `TableName` which isn't indexed. And I know that subqueries are inherently inefficient. So my question in general is, is there a way to redesign the query so that it performs better? I can't think of a way to express the subquery as a join while still returning just one `CaseTask` row when there are multiple associated `FieldChanges` (i.e. preserving the EXISTS semantic). I haven't yet indexed the `TableName` field of the `FieldChanges` table because I'm hesitant about indexing text fields. So what should I do?
2011/05/18
[ "https://Stackoverflow.com/questions/6043381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/164923/" ]
My first instinct is to limit the result set ``` SELECT * FROM Kctc.FieldChanges WHERE Kctc.FieldChanges.RecordId = Kctc.CaseTasks.CaseTaskId AND Kctc.FieldChanges.TableName = 'CaseTasks' AND Kctc.FieldChanges.DateOfChange BETWEEN ISNULL(@ChangedAfter, '2000/01/01') AND ISNULL(@ChangedBefore, '2050/01/01' ``` changed to ``` SELECT TOP 1 Kctc.FieldChanges.RecordId FROM Kctc.FieldChanges WHERE Kctc.FieldChanges.RecordId = Kctc.CaseTasks.CaseTaskId AND Kctc.FieldChanges.TableName = 'CaseTasks' AND Kctc.FieldChanges.DateOfChange BETWEEN ISNULL(@ChangedAfter, '2000/01/01') AND ISNULL(@ChangedBefore, '2050/01/01' ``` then look at the index on the fields in the where clause EDIT: Regarding the TOP 1 - likely not giving that much of a benefit, but should not hurt, and might help avoid a table scan. Using a single field instead of \* should only return that column (I assume it is NOT a NULL value column here) Additional thoughts: Declare and Set a local value instead of the ISNULL thing which gets processed multiple times: ``` DECLARE @checkmyafter datetime; -- assumption on my part here on the type SET @checkmyafter = ISNULL(@ChangedAfter, '2000/01/01'); ``` do same with before, then use ``` ... SELECT TOP 1 Kctc.FieldChanges.RecordId FROM Kctc.FieldChanges WHERE Kctc.FieldChanges.RecordId = Kctc.CaseTasks.CaseTaskId AND Kctc.FieldChanges.TableName = 'CaseTasks' AND Kctc.FieldChanges.DateOfChange BETWEEN @checkmybefore AND @checkmyafter ... ``` ONE MORE THING: Check the sequence of the WHERE xxx AND - use the MOST LIKELY candidate to isolate FIRST in the sequence, whichever condition that is, so it can get out faster. If that is the RecordId, then find, if the TableName is better, use that first instead. If one column also has an index already consider that one all else being equal.
This is **not going to be a "good" solution**, but it might be better than what's happening right now: ``` SELECT Kctc.CaseTasks.CaseTaskId ...blah blah blah FROM Kctc.CaseTasks ... some joins here LEFT JOIN ( SELECT RecordID FROM Kctc.FieldChanges WHERE Kctc.FieldChanges.TableName = 'CaseTasks' AND Kctc.FieldChanges.DateOfChange BETWEEN ISNULL(@ChangedAfter, '2000/01/01') AND ISNULL(@ChangedBefore, '2050/01/01') GROUP BY RecordID ) AS MatchingChanges ON Kctc.CaseTasks.RecordId = MatchingChanges.RecordId WHERE ... some normal where clauses AND (MatchingChanges.RecordID Is Not Null OR ((@ChangedAfter IS NULL AND @ChangedBefore IS NULL)) ``` Depends on exactly what the query plan is - if it was performing the subquery repeatedly, this formulation might help.
6,043,381
I have the following query (slightly amended for clarity): ``` CREATE PROCEDURE Kctc.CaseTasks_GetCaseTasks @CaseNumber int ... other parameters ,@ChangedBefore datetime ,@ChangedAfter datetime AS SELECT Kctc.CaseTasks.CaseTaskId ...blah blah blah FROM Kctc.CaseTasks ... some joins here WHERE ... some normal where clauses AND ( (@ChangedAfter IS NULL AND @ChangedBefore IS NULL) OR EXISTS (SELECT * FROM Kctc.FieldChanges WHERE Kctc.FieldChanges.RecordId = Kctc.CaseTasks.CaseTaskId AND Kctc.FieldChanges.TableName = 'CaseTasks' AND Kctc.FieldChanges.DateOfChange BETWEEN ISNULL(@ChangedAfter, '2000/01/01') AND ISNULL(@ChangedBefore, '2050/01/01')) ) ``` This query times out whenever the user specifies values for `@ChangedBefore` or `@ChangedAfter`, therefore invoking the subquery. The subquery checks for the existence of a record in the table called `FieldChanges` (which effectively records changes to every field in the `CaseTasks` table). Querying `FieldChanges` isn't very efficient because it involves filtering on the text field `TableName` which isn't indexed. And I know that subqueries are inherently inefficient. So my question in general is, is there a way to redesign the query so that it performs better? I can't think of a way to express the subquery as a join while still returning just one `CaseTask` row when there are multiple associated `FieldChanges` (i.e. preserving the EXISTS semantic). I haven't yet indexed the `TableName` field of the `FieldChanges` table because I'm hesitant about indexing text fields. So what should I do?
2011/05/18
[ "https://Stackoverflow.com/questions/6043381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/164923/" ]
Adding `SET ARITHABORT ON` to the stored procedure got it to execute in less than 1 second. I have no idea what it means. Presumably 'stop arsing about'.
This is **not going to be a "good" solution**, but it might be better than what's happening right now: ``` SELECT Kctc.CaseTasks.CaseTaskId ...blah blah blah FROM Kctc.CaseTasks ... some joins here LEFT JOIN ( SELECT RecordID FROM Kctc.FieldChanges WHERE Kctc.FieldChanges.TableName = 'CaseTasks' AND Kctc.FieldChanges.DateOfChange BETWEEN ISNULL(@ChangedAfter, '2000/01/01') AND ISNULL(@ChangedBefore, '2050/01/01') GROUP BY RecordID ) AS MatchingChanges ON Kctc.CaseTasks.RecordId = MatchingChanges.RecordId WHERE ... some normal where clauses AND (MatchingChanges.RecordID Is Not Null OR ((@ChangedAfter IS NULL AND @ChangedBefore IS NULL)) ``` Depends on exactly what the query plan is - if it was performing the subquery repeatedly, this formulation might help.
67,588,803
I have a list of lists in Python that essentially represent a table. I know I should have used a pandas dataframe to accomplish this, but hindsight is 20/20. I digress...below is an example list of what I'm talking about. The overarching list variable is comprised of these nested lists: ``` ['Store number', 2, 3, 4, 1, 5] ['Variable 1', 82, 99, 44, 32, 65] ['String 1', 'cat', 'dog', 'lizard', 'alligator', 'crocodile'] ``` In the current state, each index of each nested list corresponds to the same row in the table. So for store number 2, variable 1 is 82 and string 1 is cat. Say I want to sort each list to where these relationships are maintained, but we sort by ascending store number. The final lists would look like: ``` ['Store number', 1, 2, 3, 4, 5] ['Variable 1', 32, 82, 99, 44, 65] ['String 1', 'alligator', 'cat', 'dog', 'lizard', 'crocodile'] ``` How could I accomplish this using my current data structures?
2021/05/18
[ "https://Stackoverflow.com/questions/67588803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15154835/" ]
You can sort a list of indexes from a `range`, based on the values in one of your lists. Then you can use the indexes reorder the original three lists: ``` store = ['Store number', 2, 3, 4, 1, 5] var1 = ['Variable 1', 82, 99, 44, 32, 65] str1 = ['String 1', 'cat', 'dog', 'lizard', 'alligator', 'crocodile'] sort_indexes = sorted(range(1, len(store)), key=lambda i:store[i]) store[1:] = [store[i] for i in sort_indexes] var1[1:] = [var1[i] for i in sort_indexes] str1[1:] = [str1[i] for i in sort_indexes] ``` Your data structure would be a lot nicer to work with if the header for each column wasn't contained in the same list. But that awkwardness doesn't actually effect this code much, since we're not directly sorting the lists anyway, we're sorting indexes instead, and there's not really any problem doing that starting at index `1` instead of `0`. If you move the headers out of the data, you'd just be able to skip the slice assignment at the end of this code (just use the list comprehension values directly).
If you must use your current data structure, here is a function that will do what you want. Note there are probably much more clever approaches, but this will work. given: ``` lolists = [['Store number', 2, 3, 4, 1, 5], ['Variable 1', 82, 99, 44, 32, 65], ['String 1', 'cat', 'dog', 'lizard', 'alligator', 'crocodile'] ] def sortinnerLists(lol): kys = lol[0][1:] sortedKys = sorted(kys) rslt = [[lol[0][0]], [lol[1][0]], [lol[2][0]]] for v in sortedKys: indx = kys.index(v)+1 rslt[0].append(v) rslt[1].append(lol[1][indx]) rslt[2].append(lol[2][indx]) return rslt sortinnerLists(lolists) ``` yields: ``` [['Store number', 1, 2, 3, 4, 5], ['Variable 1', 32, 82, 99, 44, 65], ['String 1', 'alligator', 'cat', 'dog', 'lizard', 'crocodile']] ```
18,045,410
I am new to Django and am trying to have a user select from a drop-down of choices, then have their choice pass to my next view class so that the record can be edited. Right now my code passes the name of the disease but not the PK from the database. It seems like a simple problem but I'm not sure how to solve it. I get the following error: ``` Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found. ``` Code is below: **views.py** ``` def drui_index(request): diseaseForm = DiseaseForm(request.POST) if diseaseForm.is_valid(): #the problem is probably in the below line. The code isn't right. new_disease = diseaseForm.cleaned_data['disease'] url = reverse('drui', kwargs={'someApp_disease_id': new_disease.pk}) return HttpResponseRedirect(url) else: diseaseForm = DiseaseForm() return render_to_response("drui_index.html", {'diseaseForm': diseaseForm}, context_instance=RequestContext(request)) def drui(request, someApp_disease_id): disease = get_object_or_404(Disease, pk=someApp_disease_id if request.method == "POST": diseaseForm = DiseaseForm(request.POST, instance=disease) indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=disease) if diseaseForm.is_valid(): new_disease = diseaseForm.save(commit=False) if indicatorInlineFormSet.is_valid(): new_disease.save() indicatorInlineFormSet.save() return HttpResponseRedirect(reverse(valdrui)) else: diseaseForm = DiseaseForm(instance=disease) indicatorInlineFormSet = IndicatorFormSet(instance=disease) return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet, 'hide_breadcrumb': hide_breadcrumb},context_instance=RequestContext(request)) ``` **forms.py** ``` class DiseaseForm(forms.ModelForm): disease = forms.ModelChoiceField(queryset=Disease.objects.all()) class Meta: model = Disease ``` **urls.py** ``` url(r'^drui_index/$', 'someApp.views.drui_index', name='drui_index'), url(r'^drui/(?P<someApp_disease_id>\d+)/$', 'someApp.views.drui', name='drui') ``` **HTML for drui.html** ``` <form class="disease_form" action="{% url drui someApp_disease_id %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} {{ indicatorInlineFormSet.as_table }} ``` **HTML for drui\_index.html** ``` <form class="disease_form" action="{% url drui_index %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} ``` **UPDATE** Solved it by adding a .pk in my kwargs. But now I get a Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
2013/08/04
[ "https://Stackoverflow.com/questions/18045410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646813/" ]
Case 2 seems the opposite as case 3, so I don't think you can combine the `Pattern`s. For case 2, your `Pattern` could look like: ``` Pattern pattern = Pattern.compile("(\\s|^)Hello(\\s|$)", Pattern.CASE_INSENSITIVE); ``` In this case we surround the keyword by whitespace or beginning/end of input. For case 3, your `Pattern` could look like: ``` Pattern pattern = Pattern.compile("[\\$#@\\^&]Hello(\\s|$)", Pattern.CASE_INSENSITIVE); ``` In this case, we precede the keyword with any of the special characters of your choice (note the escaped reserved characters `$` and `^`), then we accept whitespace or the end of input as the character following the keyword.
Use `(?:^|\s)` ("start of text or whitespace") instead of the first `\b`, and `(?:$|\s)` ("end of text or whitespace") instead of the second `\b` in your regex.
18,045,410
I am new to Django and am trying to have a user select from a drop-down of choices, then have their choice pass to my next view class so that the record can be edited. Right now my code passes the name of the disease but not the PK from the database. It seems like a simple problem but I'm not sure how to solve it. I get the following error: ``` Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found. ``` Code is below: **views.py** ``` def drui_index(request): diseaseForm = DiseaseForm(request.POST) if diseaseForm.is_valid(): #the problem is probably in the below line. The code isn't right. new_disease = diseaseForm.cleaned_data['disease'] url = reverse('drui', kwargs={'someApp_disease_id': new_disease.pk}) return HttpResponseRedirect(url) else: diseaseForm = DiseaseForm() return render_to_response("drui_index.html", {'diseaseForm': diseaseForm}, context_instance=RequestContext(request)) def drui(request, someApp_disease_id): disease = get_object_or_404(Disease, pk=someApp_disease_id if request.method == "POST": diseaseForm = DiseaseForm(request.POST, instance=disease) indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=disease) if diseaseForm.is_valid(): new_disease = diseaseForm.save(commit=False) if indicatorInlineFormSet.is_valid(): new_disease.save() indicatorInlineFormSet.save() return HttpResponseRedirect(reverse(valdrui)) else: diseaseForm = DiseaseForm(instance=disease) indicatorInlineFormSet = IndicatorFormSet(instance=disease) return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet, 'hide_breadcrumb': hide_breadcrumb},context_instance=RequestContext(request)) ``` **forms.py** ``` class DiseaseForm(forms.ModelForm): disease = forms.ModelChoiceField(queryset=Disease.objects.all()) class Meta: model = Disease ``` **urls.py** ``` url(r'^drui_index/$', 'someApp.views.drui_index', name='drui_index'), url(r'^drui/(?P<someApp_disease_id>\d+)/$', 'someApp.views.drui', name='drui') ``` **HTML for drui.html** ``` <form class="disease_form" action="{% url drui someApp_disease_id %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} {{ indicatorInlineFormSet.as_table }} ``` **HTML for drui\_index.html** ``` <form class="disease_form" action="{% url drui_index %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} ``` **UPDATE** Solved it by adding a .pk in my kwargs. But now I get a Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
2013/08/04
[ "https://Stackoverflow.com/questions/18045410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646813/" ]
Case 2 seems the opposite as case 3, so I don't think you can combine the `Pattern`s. For case 2, your `Pattern` could look like: ``` Pattern pattern = Pattern.compile("(\\s|^)Hello(\\s|$)", Pattern.CASE_INSENSITIVE); ``` In this case we surround the keyword by whitespace or beginning/end of input. For case 3, your `Pattern` could look like: ``` Pattern pattern = Pattern.compile("[\\$#@\\^&]Hello(\\s|$)", Pattern.CASE_INSENSITIVE); ``` In this case, we precede the keyword with any of the special characters of your choice (note the escaped reserved characters `$` and `^`), then we accept whitespace or the end of input as the character following the keyword.
The problem comes from the way that "exact word" is defined. It is not just whitespace that can surround the word to make it a word. For example in most circumstances one would want an exact word match for 'Hello' to work with. "hello there", "That young man just said hello to that other young man" and "I wish people would still answer the telephone by saying ahoy rather than Hello." If you want the match to be only split on whitespace then I believe you will have to specify the whitespace condition. Assuming you also want to it to match at the end then I would propose something like this. ``` Pattern pattern = Pattern.compile("\(^\| \)" + escapeSearchString(patternString) + "\( \|$\)"); ``` and then have a couple of methods like this ``` public String escapeSearchString(String patternString) { StringBuilder stringBuilder = new StringBuilder(patternString.length() * 3); for (char c : patternString.toCharArray()) { if (isEscapableCharacter(c)) { stringBuilder.append("\\"); } stringBuilder.append(c); } } public boolean isEscapableCharacter(char c) { switch (c) { case '#': case '$': case '@': case '^': case '&': return true; default: return false; } } ``` It would probably be better to iterate over a char[] for the escapable characters and load them from a config file.
18,045,410
I am new to Django and am trying to have a user select from a drop-down of choices, then have their choice pass to my next view class so that the record can be edited. Right now my code passes the name of the disease but not the PK from the database. It seems like a simple problem but I'm not sure how to solve it. I get the following error: ``` Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found. ``` Code is below: **views.py** ``` def drui_index(request): diseaseForm = DiseaseForm(request.POST) if diseaseForm.is_valid(): #the problem is probably in the below line. The code isn't right. new_disease = diseaseForm.cleaned_data['disease'] url = reverse('drui', kwargs={'someApp_disease_id': new_disease.pk}) return HttpResponseRedirect(url) else: diseaseForm = DiseaseForm() return render_to_response("drui_index.html", {'diseaseForm': diseaseForm}, context_instance=RequestContext(request)) def drui(request, someApp_disease_id): disease = get_object_or_404(Disease, pk=someApp_disease_id if request.method == "POST": diseaseForm = DiseaseForm(request.POST, instance=disease) indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=disease) if diseaseForm.is_valid(): new_disease = diseaseForm.save(commit=False) if indicatorInlineFormSet.is_valid(): new_disease.save() indicatorInlineFormSet.save() return HttpResponseRedirect(reverse(valdrui)) else: diseaseForm = DiseaseForm(instance=disease) indicatorInlineFormSet = IndicatorFormSet(instance=disease) return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet, 'hide_breadcrumb': hide_breadcrumb},context_instance=RequestContext(request)) ``` **forms.py** ``` class DiseaseForm(forms.ModelForm): disease = forms.ModelChoiceField(queryset=Disease.objects.all()) class Meta: model = Disease ``` **urls.py** ``` url(r'^drui_index/$', 'someApp.views.drui_index', name='drui_index'), url(r'^drui/(?P<someApp_disease_id>\d+)/$', 'someApp.views.drui', name='drui') ``` **HTML for drui.html** ``` <form class="disease_form" action="{% url drui someApp_disease_id %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} {{ indicatorInlineFormSet.as_table }} ``` **HTML for drui\_index.html** ``` <form class="disease_form" action="{% url drui_index %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} ``` **UPDATE** Solved it by adding a .pk in my kwargs. But now I get a Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
2013/08/04
[ "https://Stackoverflow.com/questions/18045410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646813/" ]
Case 2 seems the opposite as case 3, so I don't think you can combine the `Pattern`s. For case 2, your `Pattern` could look like: ``` Pattern pattern = Pattern.compile("(\\s|^)Hello(\\s|$)", Pattern.CASE_INSENSITIVE); ``` In this case we surround the keyword by whitespace or beginning/end of input. For case 3, your `Pattern` could look like: ``` Pattern pattern = Pattern.compile("[\\$#@\\^&]Hello(\\s|$)", Pattern.CASE_INSENSITIVE); ``` In this case, we precede the keyword with any of the special characters of your choice (note the escaped reserved characters `$` and `^`), then we accept whitespace or the end of input as the character following the keyword.
Try maybe this way ``` String patternStr = "(?i)(?<=\\s|^)"+Pattern.quote(searchedStubstring)+"(?=\\s|$)"; ``` (?<=...) and (?=...) is positive [look behind and ahead](http://www.regular-expressions.info/lookaround.html) so it will check if before your `searchedStubstring` will have * white-space `\\s` or start of the input `^` before, and * white-space `\\s` or end of the input `&` after it. Also in case you would like to searched for special characters like `$` `+` and others you need to escape them. To do this you can use `Pattern.quote(searchedStubstring)`
18,045,410
I am new to Django and am trying to have a user select from a drop-down of choices, then have their choice pass to my next view class so that the record can be edited. Right now my code passes the name of the disease but not the PK from the database. It seems like a simple problem but I'm not sure how to solve it. I get the following error: ``` Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found. ``` Code is below: **views.py** ``` def drui_index(request): diseaseForm = DiseaseForm(request.POST) if diseaseForm.is_valid(): #the problem is probably in the below line. The code isn't right. new_disease = diseaseForm.cleaned_data['disease'] url = reverse('drui', kwargs={'someApp_disease_id': new_disease.pk}) return HttpResponseRedirect(url) else: diseaseForm = DiseaseForm() return render_to_response("drui_index.html", {'diseaseForm': diseaseForm}, context_instance=RequestContext(request)) def drui(request, someApp_disease_id): disease = get_object_or_404(Disease, pk=someApp_disease_id if request.method == "POST": diseaseForm = DiseaseForm(request.POST, instance=disease) indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=disease) if diseaseForm.is_valid(): new_disease = diseaseForm.save(commit=False) if indicatorInlineFormSet.is_valid(): new_disease.save() indicatorInlineFormSet.save() return HttpResponseRedirect(reverse(valdrui)) else: diseaseForm = DiseaseForm(instance=disease) indicatorInlineFormSet = IndicatorFormSet(instance=disease) return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet, 'hide_breadcrumb': hide_breadcrumb},context_instance=RequestContext(request)) ``` **forms.py** ``` class DiseaseForm(forms.ModelForm): disease = forms.ModelChoiceField(queryset=Disease.objects.all()) class Meta: model = Disease ``` **urls.py** ``` url(r'^drui_index/$', 'someApp.views.drui_index', name='drui_index'), url(r'^drui/(?P<someApp_disease_id>\d+)/$', 'someApp.views.drui', name='drui') ``` **HTML for drui.html** ``` <form class="disease_form" action="{% url drui someApp_disease_id %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} {{ indicatorInlineFormSet.as_table }} ``` **HTML for drui\_index.html** ``` <form class="disease_form" action="{% url drui_index %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} ``` **UPDATE** Solved it by adding a .pk in my kwargs. But now I get a Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
2013/08/04
[ "https://Stackoverflow.com/questions/18045410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646813/" ]
Case 2 seems the opposite as case 3, so I don't think you can combine the `Pattern`s. For case 2, your `Pattern` could look like: ``` Pattern pattern = Pattern.compile("(\\s|^)Hello(\\s|$)", Pattern.CASE_INSENSITIVE); ``` In this case we surround the keyword by whitespace or beginning/end of input. For case 3, your `Pattern` could look like: ``` Pattern pattern = Pattern.compile("[\\$#@\\^&]Hello(\\s|$)", Pattern.CASE_INSENSITIVE); ``` In this case, we precede the keyword with any of the special characters of your choice (note the escaped reserved characters `$` and `^`), then we accept whitespace or the end of input as the character following the keyword.
for example if your word want to have special char (for example here '#') at the begining and end of this you have to write the following: ``` Pattern p = Pattern.compile("(\\s|^|#)"+word+"(\\s|\\#|$)", Pattern.CASE_INSENSITIVE); ``` if you want exact match: ``` Pattern p = Pattern.compile("(\\s|^)"+word+"(\\s|$)", Pattern.CASE_INSENSITIVE); ``` with '|' is like OR so you can add as match special char's you want ..for example: ``` Pattern p = Pattern.compile("(\\s|^|#|:|-)"+word+"(\\s|\\#|\\,|\\.|$)", Pattern.CASE_INSENSITIVE); ``` char '^' means to detect the string at beginning of line and '$' means at end of line. see more here: [Summary of regular-expression constructs](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)
18,045,410
I am new to Django and am trying to have a user select from a drop-down of choices, then have their choice pass to my next view class so that the record can be edited. Right now my code passes the name of the disease but not the PK from the database. It seems like a simple problem but I'm not sure how to solve it. I get the following error: ``` Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found. ``` Code is below: **views.py** ``` def drui_index(request): diseaseForm = DiseaseForm(request.POST) if diseaseForm.is_valid(): #the problem is probably in the below line. The code isn't right. new_disease = diseaseForm.cleaned_data['disease'] url = reverse('drui', kwargs={'someApp_disease_id': new_disease.pk}) return HttpResponseRedirect(url) else: diseaseForm = DiseaseForm() return render_to_response("drui_index.html", {'diseaseForm': diseaseForm}, context_instance=RequestContext(request)) def drui(request, someApp_disease_id): disease = get_object_or_404(Disease, pk=someApp_disease_id if request.method == "POST": diseaseForm = DiseaseForm(request.POST, instance=disease) indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=disease) if diseaseForm.is_valid(): new_disease = diseaseForm.save(commit=False) if indicatorInlineFormSet.is_valid(): new_disease.save() indicatorInlineFormSet.save() return HttpResponseRedirect(reverse(valdrui)) else: diseaseForm = DiseaseForm(instance=disease) indicatorInlineFormSet = IndicatorFormSet(instance=disease) return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet, 'hide_breadcrumb': hide_breadcrumb},context_instance=RequestContext(request)) ``` **forms.py** ``` class DiseaseForm(forms.ModelForm): disease = forms.ModelChoiceField(queryset=Disease.objects.all()) class Meta: model = Disease ``` **urls.py** ``` url(r'^drui_index/$', 'someApp.views.drui_index', name='drui_index'), url(r'^drui/(?P<someApp_disease_id>\d+)/$', 'someApp.views.drui', name='drui') ``` **HTML for drui.html** ``` <form class="disease_form" action="{% url drui someApp_disease_id %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} {{ indicatorInlineFormSet.as_table }} ``` **HTML for drui\_index.html** ``` <form class="disease_form" action="{% url drui_index %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} ``` **UPDATE** Solved it by adding a .pk in my kwargs. But now I get a Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
2013/08/04
[ "https://Stackoverflow.com/questions/18045410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646813/" ]
Use `(?:^|\s)` ("start of text or whitespace") instead of the first `\b`, and `(?:$|\s)` ("end of text or whitespace") instead of the second `\b` in your regex.
The problem comes from the way that "exact word" is defined. It is not just whitespace that can surround the word to make it a word. For example in most circumstances one would want an exact word match for 'Hello' to work with. "hello there", "That young man just said hello to that other young man" and "I wish people would still answer the telephone by saying ahoy rather than Hello." If you want the match to be only split on whitespace then I believe you will have to specify the whitespace condition. Assuming you also want to it to match at the end then I would propose something like this. ``` Pattern pattern = Pattern.compile("\(^\| \)" + escapeSearchString(patternString) + "\( \|$\)"); ``` and then have a couple of methods like this ``` public String escapeSearchString(String patternString) { StringBuilder stringBuilder = new StringBuilder(patternString.length() * 3); for (char c : patternString.toCharArray()) { if (isEscapableCharacter(c)) { stringBuilder.append("\\"); } stringBuilder.append(c); } } public boolean isEscapableCharacter(char c) { switch (c) { case '#': case '$': case '@': case '^': case '&': return true; default: return false; } } ``` It would probably be better to iterate over a char[] for the escapable characters and load them from a config file.
18,045,410
I am new to Django and am trying to have a user select from a drop-down of choices, then have their choice pass to my next view class so that the record can be edited. Right now my code passes the name of the disease but not the PK from the database. It seems like a simple problem but I'm not sure how to solve it. I get the following error: ``` Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found. ``` Code is below: **views.py** ``` def drui_index(request): diseaseForm = DiseaseForm(request.POST) if diseaseForm.is_valid(): #the problem is probably in the below line. The code isn't right. new_disease = diseaseForm.cleaned_data['disease'] url = reverse('drui', kwargs={'someApp_disease_id': new_disease.pk}) return HttpResponseRedirect(url) else: diseaseForm = DiseaseForm() return render_to_response("drui_index.html", {'diseaseForm': diseaseForm}, context_instance=RequestContext(request)) def drui(request, someApp_disease_id): disease = get_object_or_404(Disease, pk=someApp_disease_id if request.method == "POST": diseaseForm = DiseaseForm(request.POST, instance=disease) indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=disease) if diseaseForm.is_valid(): new_disease = diseaseForm.save(commit=False) if indicatorInlineFormSet.is_valid(): new_disease.save() indicatorInlineFormSet.save() return HttpResponseRedirect(reverse(valdrui)) else: diseaseForm = DiseaseForm(instance=disease) indicatorInlineFormSet = IndicatorFormSet(instance=disease) return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet, 'hide_breadcrumb': hide_breadcrumb},context_instance=RequestContext(request)) ``` **forms.py** ``` class DiseaseForm(forms.ModelForm): disease = forms.ModelChoiceField(queryset=Disease.objects.all()) class Meta: model = Disease ``` **urls.py** ``` url(r'^drui_index/$', 'someApp.views.drui_index', name='drui_index'), url(r'^drui/(?P<someApp_disease_id>\d+)/$', 'someApp.views.drui', name='drui') ``` **HTML for drui.html** ``` <form class="disease_form" action="{% url drui someApp_disease_id %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} {{ indicatorInlineFormSet.as_table }} ``` **HTML for drui\_index.html** ``` <form class="disease_form" action="{% url drui_index %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} ``` **UPDATE** Solved it by adding a .pk in my kwargs. But now I get a Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
2013/08/04
[ "https://Stackoverflow.com/questions/18045410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646813/" ]
Use `(?:^|\s)` ("start of text or whitespace") instead of the first `\b`, and `(?:$|\s)` ("end of text or whitespace") instead of the second `\b` in your regex.
Try maybe this way ``` String patternStr = "(?i)(?<=\\s|^)"+Pattern.quote(searchedStubstring)+"(?=\\s|$)"; ``` (?<=...) and (?=...) is positive [look behind and ahead](http://www.regular-expressions.info/lookaround.html) so it will check if before your `searchedStubstring` will have * white-space `\\s` or start of the input `^` before, and * white-space `\\s` or end of the input `&` after it. Also in case you would like to searched for special characters like `$` `+` and others you need to escape them. To do this you can use `Pattern.quote(searchedStubstring)`
18,045,410
I am new to Django and am trying to have a user select from a drop-down of choices, then have their choice pass to my next view class so that the record can be edited. Right now my code passes the name of the disease but not the PK from the database. It seems like a simple problem but I'm not sure how to solve it. I get the following error: ``` Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found. ``` Code is below: **views.py** ``` def drui_index(request): diseaseForm = DiseaseForm(request.POST) if diseaseForm.is_valid(): #the problem is probably in the below line. The code isn't right. new_disease = diseaseForm.cleaned_data['disease'] url = reverse('drui', kwargs={'someApp_disease_id': new_disease.pk}) return HttpResponseRedirect(url) else: diseaseForm = DiseaseForm() return render_to_response("drui_index.html", {'diseaseForm': diseaseForm}, context_instance=RequestContext(request)) def drui(request, someApp_disease_id): disease = get_object_or_404(Disease, pk=someApp_disease_id if request.method == "POST": diseaseForm = DiseaseForm(request.POST, instance=disease) indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=disease) if diseaseForm.is_valid(): new_disease = diseaseForm.save(commit=False) if indicatorInlineFormSet.is_valid(): new_disease.save() indicatorInlineFormSet.save() return HttpResponseRedirect(reverse(valdrui)) else: diseaseForm = DiseaseForm(instance=disease) indicatorInlineFormSet = IndicatorFormSet(instance=disease) return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet, 'hide_breadcrumb': hide_breadcrumb},context_instance=RequestContext(request)) ``` **forms.py** ``` class DiseaseForm(forms.ModelForm): disease = forms.ModelChoiceField(queryset=Disease.objects.all()) class Meta: model = Disease ``` **urls.py** ``` url(r'^drui_index/$', 'someApp.views.drui_index', name='drui_index'), url(r'^drui/(?P<someApp_disease_id>\d+)/$', 'someApp.views.drui', name='drui') ``` **HTML for drui.html** ``` <form class="disease_form" action="{% url drui someApp_disease_id %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} {{ indicatorInlineFormSet.as_table }} ``` **HTML for drui\_index.html** ``` <form class="disease_form" action="{% url drui_index %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} ``` **UPDATE** Solved it by adding a .pk in my kwargs. But now I get a Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
2013/08/04
[ "https://Stackoverflow.com/questions/18045410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646813/" ]
Use `(?:^|\s)` ("start of text or whitespace") instead of the first `\b`, and `(?:$|\s)` ("end of text or whitespace") instead of the second `\b` in your regex.
for example if your word want to have special char (for example here '#') at the begining and end of this you have to write the following: ``` Pattern p = Pattern.compile("(\\s|^|#)"+word+"(\\s|\\#|$)", Pattern.CASE_INSENSITIVE); ``` if you want exact match: ``` Pattern p = Pattern.compile("(\\s|^)"+word+"(\\s|$)", Pattern.CASE_INSENSITIVE); ``` with '|' is like OR so you can add as match special char's you want ..for example: ``` Pattern p = Pattern.compile("(\\s|^|#|:|-)"+word+"(\\s|\\#|\\,|\\.|$)", Pattern.CASE_INSENSITIVE); ``` char '^' means to detect the string at beginning of line and '$' means at end of line. see more here: [Summary of regular-expression constructs](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)
18,045,410
I am new to Django and am trying to have a user select from a drop-down of choices, then have their choice pass to my next view class so that the record can be edited. Right now my code passes the name of the disease but not the PK from the database. It seems like a simple problem but I'm not sure how to solve it. I get the following error: ``` Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found. ``` Code is below: **views.py** ``` def drui_index(request): diseaseForm = DiseaseForm(request.POST) if diseaseForm.is_valid(): #the problem is probably in the below line. The code isn't right. new_disease = diseaseForm.cleaned_data['disease'] url = reverse('drui', kwargs={'someApp_disease_id': new_disease.pk}) return HttpResponseRedirect(url) else: diseaseForm = DiseaseForm() return render_to_response("drui_index.html", {'diseaseForm': diseaseForm}, context_instance=RequestContext(request)) def drui(request, someApp_disease_id): disease = get_object_or_404(Disease, pk=someApp_disease_id if request.method == "POST": diseaseForm = DiseaseForm(request.POST, instance=disease) indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=disease) if diseaseForm.is_valid(): new_disease = diseaseForm.save(commit=False) if indicatorInlineFormSet.is_valid(): new_disease.save() indicatorInlineFormSet.save() return HttpResponseRedirect(reverse(valdrui)) else: diseaseForm = DiseaseForm(instance=disease) indicatorInlineFormSet = IndicatorFormSet(instance=disease) return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet, 'hide_breadcrumb': hide_breadcrumb},context_instance=RequestContext(request)) ``` **forms.py** ``` class DiseaseForm(forms.ModelForm): disease = forms.ModelChoiceField(queryset=Disease.objects.all()) class Meta: model = Disease ``` **urls.py** ``` url(r'^drui_index/$', 'someApp.views.drui_index', name='drui_index'), url(r'^drui/(?P<someApp_disease_id>\d+)/$', 'someApp.views.drui', name='drui') ``` **HTML for drui.html** ``` <form class="disease_form" action="{% url drui someApp_disease_id %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} {{ indicatorInlineFormSet.as_table }} ``` **HTML for drui\_index.html** ``` <form class="disease_form" action="{% url drui_index %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} ``` **UPDATE** Solved it by adding a .pk in my kwargs. But now I get a Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
2013/08/04
[ "https://Stackoverflow.com/questions/18045410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646813/" ]
The problem comes from the way that "exact word" is defined. It is not just whitespace that can surround the word to make it a word. For example in most circumstances one would want an exact word match for 'Hello' to work with. "hello there", "That young man just said hello to that other young man" and "I wish people would still answer the telephone by saying ahoy rather than Hello." If you want the match to be only split on whitespace then I believe you will have to specify the whitespace condition. Assuming you also want to it to match at the end then I would propose something like this. ``` Pattern pattern = Pattern.compile("\(^\| \)" + escapeSearchString(patternString) + "\( \|$\)"); ``` and then have a couple of methods like this ``` public String escapeSearchString(String patternString) { StringBuilder stringBuilder = new StringBuilder(patternString.length() * 3); for (char c : patternString.toCharArray()) { if (isEscapableCharacter(c)) { stringBuilder.append("\\"); } stringBuilder.append(c); } } public boolean isEscapableCharacter(char c) { switch (c) { case '#': case '$': case '@': case '^': case '&': return true; default: return false; } } ``` It would probably be better to iterate over a char[] for the escapable characters and load them from a config file.
for example if your word want to have special char (for example here '#') at the begining and end of this you have to write the following: ``` Pattern p = Pattern.compile("(\\s|^|#)"+word+"(\\s|\\#|$)", Pattern.CASE_INSENSITIVE); ``` if you want exact match: ``` Pattern p = Pattern.compile("(\\s|^)"+word+"(\\s|$)", Pattern.CASE_INSENSITIVE); ``` with '|' is like OR so you can add as match special char's you want ..for example: ``` Pattern p = Pattern.compile("(\\s|^|#|:|-)"+word+"(\\s|\\#|\\,|\\.|$)", Pattern.CASE_INSENSITIVE); ``` char '^' means to detect the string at beginning of line and '$' means at end of line. see more here: [Summary of regular-expression constructs](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)
18,045,410
I am new to Django and am trying to have a user select from a drop-down of choices, then have their choice pass to my next view class so that the record can be edited. Right now my code passes the name of the disease but not the PK from the database. It seems like a simple problem but I'm not sure how to solve it. I get the following error: ``` Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found. ``` Code is below: **views.py** ``` def drui_index(request): diseaseForm = DiseaseForm(request.POST) if diseaseForm.is_valid(): #the problem is probably in the below line. The code isn't right. new_disease = diseaseForm.cleaned_data['disease'] url = reverse('drui', kwargs={'someApp_disease_id': new_disease.pk}) return HttpResponseRedirect(url) else: diseaseForm = DiseaseForm() return render_to_response("drui_index.html", {'diseaseForm': diseaseForm}, context_instance=RequestContext(request)) def drui(request, someApp_disease_id): disease = get_object_or_404(Disease, pk=someApp_disease_id if request.method == "POST": diseaseForm = DiseaseForm(request.POST, instance=disease) indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=disease) if diseaseForm.is_valid(): new_disease = diseaseForm.save(commit=False) if indicatorInlineFormSet.is_valid(): new_disease.save() indicatorInlineFormSet.save() return HttpResponseRedirect(reverse(valdrui)) else: diseaseForm = DiseaseForm(instance=disease) indicatorInlineFormSet = IndicatorFormSet(instance=disease) return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet, 'hide_breadcrumb': hide_breadcrumb},context_instance=RequestContext(request)) ``` **forms.py** ``` class DiseaseForm(forms.ModelForm): disease = forms.ModelChoiceField(queryset=Disease.objects.all()) class Meta: model = Disease ``` **urls.py** ``` url(r'^drui_index/$', 'someApp.views.drui_index', name='drui_index'), url(r'^drui/(?P<someApp_disease_id>\d+)/$', 'someApp.views.drui', name='drui') ``` **HTML for drui.html** ``` <form class="disease_form" action="{% url drui someApp_disease_id %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} {{ indicatorInlineFormSet.as_table }} ``` **HTML for drui\_index.html** ``` <form class="disease_form" action="{% url drui_index %}" method="post">{% csrf_token %} {{ diseaseForm.as_table }} ``` **UPDATE** Solved it by adding a .pk in my kwargs. But now I get a Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
2013/08/04
[ "https://Stackoverflow.com/questions/18045410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646813/" ]
Try maybe this way ``` String patternStr = "(?i)(?<=\\s|^)"+Pattern.quote(searchedStubstring)+"(?=\\s|$)"; ``` (?<=...) and (?=...) is positive [look behind and ahead](http://www.regular-expressions.info/lookaround.html) so it will check if before your `searchedStubstring` will have * white-space `\\s` or start of the input `^` before, and * white-space `\\s` or end of the input `&` after it. Also in case you would like to searched for special characters like `$` `+` and others you need to escape them. To do this you can use `Pattern.quote(searchedStubstring)`
for example if your word want to have special char (for example here '#') at the begining and end of this you have to write the following: ``` Pattern p = Pattern.compile("(\\s|^|#)"+word+"(\\s|\\#|$)", Pattern.CASE_INSENSITIVE); ``` if you want exact match: ``` Pattern p = Pattern.compile("(\\s|^)"+word+"(\\s|$)", Pattern.CASE_INSENSITIVE); ``` with '|' is like OR so you can add as match special char's you want ..for example: ``` Pattern p = Pattern.compile("(\\s|^|#|:|-)"+word+"(\\s|\\#|\\,|\\.|$)", Pattern.CASE_INSENSITIVE); ``` char '^' means to detect the string at beginning of line and '$' means at end of line. see more here: [Summary of regular-expression constructs](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)
17,376,575
I'm working on a sudoku game and I have a list of sudoku games that I can save. I currently have the following serializer classes to save the games: ``` /// <summary> /// A method to serialize the game repository /// </summary> /// <param name="filename">A string representation of the output file name</param> /// <param name="savedGameRepository">The saved game repository</param> public void SerializeRepository(string filename, SavedGameRepository savedGameRepository) { using (Stream stream = File.Open(filename, FileMode.OpenOrCreate)) { BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, savedGameRepository); } } /// <summary> /// A method to deserialize the game repository /// </summary> /// <param name="filename">A string representation of the input file name</param> /// <returns>A SavedGameRepository object</returns> public SavedGameRepository DeserializeRepository(string filename) { SavedGameRepository savedGameRepository = new SavedGameRepository(); using (Stream stream = File.Open(filename, FileMode.OpenOrCreate)) { BinaryFormatter bFormatter = new BinaryFormatter(); if (stream.Length > 0) { savedGameRepository = (SavedGameRepository)bFormatter.Deserialize(stream); } } return savedGameRepository; } ``` Of course the problem with this is that the data file still displays the text associated with the sudoku solution so the user could read and cheat. I tried to use asymmetric encryption but of course the list of game objects is too long. I used symmetric encryption and it works as long as the game is not closed. Once closed and reopened the key is gone and the encrypted data file cannot be reopened. Is it possible to persist a symmetric encryption key?
2013/06/29
[ "https://Stackoverflow.com/questions/17376575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try to save the serialized objects in a SQLite table. The database can be encrypted with a password, and it is very simple as you don't have to write any code to encrypt just add password in the connection string. Advantages: You don't have lot of scattered files, easy to code and read write to table. Disadvantage: If this file gets corrupt your entire save is lost.
Yes ofcourse you can encrypt and decrypt. I will give you a sample code. Your encrypt class will be like this ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; using System.Text; using System.IO; namespace demo.encry { public class Crypto { public Crypto() { } public String encrypto(string te, string ps, string Salt = "Kosher", string HashAlgorithm = "SHA1", int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256) { if (string.IsNullOrEmpty(te)) return ""; byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] PlainTextBytes = Encoding.UTF8.GetBytes(te); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(ps, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; byte[] CipherTextBytes = null; using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)) { using (MemoryStream MemStream = new MemoryStream()) { using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)) { CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length); CryptoStream.FlushFinalBlock(); CipherTextBytes = MemStream.ToArray(); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return Convert.ToBase64String(CipherTextBytes); } public String decrypto(string ct, string ps, string Salt = "Kosher", string HashAlgorithm = "SHA1", int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256) { if (string.IsNullOrEmpty(ct)) return ""; byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] CipherTextBytes = Convert.FromBase64String(ct); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(ps, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; byte[] PlainTextBytes = new byte[CipherTextBytes.Length]; int ByteCount = 0; using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)) { using (MemoryStream MemStream = new MemoryStream(CipherTextBytes)) { using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)) { ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount); } } } ``` so to encrypt a String do ``` Crypto cs =new Crypto(); String originaltext="hello"; String password="password123"; /encrypting String encryptedtext=cs.encrypto(originaltext, password); //decrypting String decryptedtext=cs.decrypto(encryptedtext, password); ```
17,376,575
I'm working on a sudoku game and I have a list of sudoku games that I can save. I currently have the following serializer classes to save the games: ``` /// <summary> /// A method to serialize the game repository /// </summary> /// <param name="filename">A string representation of the output file name</param> /// <param name="savedGameRepository">The saved game repository</param> public void SerializeRepository(string filename, SavedGameRepository savedGameRepository) { using (Stream stream = File.Open(filename, FileMode.OpenOrCreate)) { BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, savedGameRepository); } } /// <summary> /// A method to deserialize the game repository /// </summary> /// <param name="filename">A string representation of the input file name</param> /// <returns>A SavedGameRepository object</returns> public SavedGameRepository DeserializeRepository(string filename) { SavedGameRepository savedGameRepository = new SavedGameRepository(); using (Stream stream = File.Open(filename, FileMode.OpenOrCreate)) { BinaryFormatter bFormatter = new BinaryFormatter(); if (stream.Length > 0) { savedGameRepository = (SavedGameRepository)bFormatter.Deserialize(stream); } } return savedGameRepository; } ``` Of course the problem with this is that the data file still displays the text associated with the sudoku solution so the user could read and cheat. I tried to use asymmetric encryption but of course the list of game objects is too long. I used symmetric encryption and it works as long as the game is not closed. Once closed and reopened the key is gone and the encrypted data file cannot be reopened. Is it possible to persist a symmetric encryption key?
2013/06/29
[ "https://Stackoverflow.com/questions/17376575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Of course a symmetric key can be persisted – it's just like any other data. You could save it to a file for instance. But the user would obviously recover the key from the file in that case. This is a fundamental property of encryption. Encryption substitutes the confidentiality of an arbitrary amount of data (the plaintext) with the confidentiality of a small amount data (the key). More on this: <http://blogs.msdn.com/b/ericlippert/archive/2011/09/27/keep-it-secret-keep-it-safe.aspx> Because your game has to be able to read the file, it has to have access to all the information required to do that. At best, you are looking at some sort of obfuscation. You have to ask yourself the question: Do you really care that much about cheating?
Yes ofcourse you can encrypt and decrypt. I will give you a sample code. Your encrypt class will be like this ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; using System.Text; using System.IO; namespace demo.encry { public class Crypto { public Crypto() { } public String encrypto(string te, string ps, string Salt = "Kosher", string HashAlgorithm = "SHA1", int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256) { if (string.IsNullOrEmpty(te)) return ""; byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] PlainTextBytes = Encoding.UTF8.GetBytes(te); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(ps, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; byte[] CipherTextBytes = null; using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)) { using (MemoryStream MemStream = new MemoryStream()) { using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)) { CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length); CryptoStream.FlushFinalBlock(); CipherTextBytes = MemStream.ToArray(); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return Convert.ToBase64String(CipherTextBytes); } public String decrypto(string ct, string ps, string Salt = "Kosher", string HashAlgorithm = "SHA1", int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY", int KeySize = 256) { if (string.IsNullOrEmpty(ct)) return ""; byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt); byte[] CipherTextBytes = Convert.FromBase64String(ct); PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(ps, SaltValueBytes, HashAlgorithm, PasswordIterations); byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8); RijndaelManaged SymmetricKey = new RijndaelManaged(); SymmetricKey.Mode = CipherMode.CBC; byte[] PlainTextBytes = new byte[CipherTextBytes.Length]; int ByteCount = 0; using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)) { using (MemoryStream MemStream = new MemoryStream(CipherTextBytes)) { using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)) { ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length); MemStream.Close(); CryptoStream.Close(); } } } SymmetricKey.Clear(); return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount); } } } ``` so to encrypt a String do ``` Crypto cs =new Crypto(); String originaltext="hello"; String password="password123"; /encrypting String encryptedtext=cs.encrypto(originaltext, password); //decrypting String decryptedtext=cs.decrypto(encryptedtext, password); ```
6,299,460
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits. I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is: ``` public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); rsa.KeySize = 1024; } public static string EncryptData(string data2Encrypt) { AssignParameter(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } ``` This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying: CryptographicException was unhandled: Wrong length (OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length'). Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp? Thanks in advance, LordJesus **EDIT:** Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
2011/06/09
[ "https://Stackoverflow.com/questions/6299460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928874/" ]
The minimum key size for encrypting 128 bytes would be 1112 bits, when you are calling `Encrypt` with OAEP off. Note that setting the key size like this `rsa.KeySize = 1024` won't help, you need to actually generate they key of the right size and use them. This is what worked for me: ``` using System; using System.IO; using System.Security.Cryptography; namespace SO6299460 { class Program { static void Main() { GenerateKey(); string data2Encrypt = string.Empty.PadLeft(128,'$'); string encrypted = EncryptData(data2Encrypt); string decrypted = DecryptData(encrypted); Console.WriteLine(data2Encrypt); Console.WriteLine(encrypted); Console.WriteLine(decrypted); } private const string path = @"c:\"; public static void GenerateKey() { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1112); string publickKey = rsa.ToXmlString(false); string privateKey = rsa.ToXmlString(true); WriteStringToFile(publickKey, path + "publickey.xml"); WriteStringToFile(privateKey, path + "privatekey.xml"); } public static void WriteStringToFile(string value, string filename) { using (FileStream stream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read)) using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(value); writer.Flush(); stream.Flush(); } } public static string EncryptData(string data2Encrypt) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes,false); return Convert.ToBase64String(cipherbytes); } public static string DecryptData(string data2Decrypt) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader reader = new StreamReader(path + "privatekey.xml"); string key = reader.ReadToEnd(); rsa.FromXmlString(key); reader.Close(); byte[] plainbytes = rsa.Decrypt(Convert.FromBase64String(data2Decrypt), false); return System.Text.Encoding.UTF8.GetString(plainbytes); } } } ``` Note however, that I'm not using a crypto container, and thus, I don't need your `AssignParameter`, but if you need to use it, modifying the code should be easy enough. If you ever need to encrypt large quantities of data (much larger than 128 bytes) [this article](http://pages.infinit.net/ctech/20031101-0151.html) has sample code on how to do this.
Do you real need the custom padding? If not you could just use [RSACryptoServiceProvider.SignData Method](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.signdata.aspx)
6,299,460
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits. I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is: ``` public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); rsa.KeySize = 1024; } public static string EncryptData(string data2Encrypt) { AssignParameter(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } ``` This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying: CryptographicException was unhandled: Wrong length (OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length'). Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp? Thanks in advance, LordJesus **EDIT:** Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
2011/06/09
[ "https://Stackoverflow.com/questions/6299460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928874/" ]
If you want to *sign* you do not want to *encrypt*. Signatures and encryption are distinct algorithms. It does not help that there is a well-known signature algorithm called RSA, and a well-known asymmetric encryption algorithm also called RSA, and that the signature algorithm was first presented (and still is in many places) as "you encrypt with the private key". This is just plain confusing. In RSA encryption, the data to encrypt (with the public key) must be padded with what [PKCS#1](http://www.rsa.com/rsalabs/node.asp?id=2125) (the RSA standard) describes as "Type 2 padding", and the result (which has the same length than the modulus) is then processed through the modular exponentiation which is at the core of RSA (at the core, but RSA is not *only* a modular exponentiation; the padding is very important for security). When signing, the data to sign must be hashed, then the hash value is embedded in a structure which describes the hash function which was just used, and the encoded structure is itself padded with a "Type 1 padding" -- not the same padding than the padding for encryption, and that's important, too. Either way, a normal RSA engine will perform the type 1 or type 2 padding itself, and most RSA *signature* engines will also handle themselves the structure which identifies the used hash function. A RSA signature engine such as `RSACryptoServiceProvider` can work either with `SignHash()`, which expects the hash value (the 32 bytes obtained from SHA-256, *without* any kind of encapsulating structure or type 1 padding -- `RSACryptoServiceProvider` handles that itself), or `SignData()`, which expects the data to be signed (the engine then does the hash computation too). To sum up, if you do any kind of padding yourself, then you are doing it wrong. If you used `Encrypt()` to compute a signature, then you are doing it wrong, too.
Apparently, according to this question — [how to use RSA to encrypt files (huge data) in C#](https://stackoverflow.com/questions/1199058/how-to-use-rsa-to-encrypt-files-huge-data-in-c) — RSA can only encrypt data shorter than its key length. Bizarre. The MSDN docs for[`RSACryptoServiceProvider.Encrypt()](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.encrypt.aspx) say that a CryptographicException may be thrown if *the length of the rgb parameter is greater than the maximum allowed length.* Well. That seems odd, especially since there doesn't seem to be much in the way of documentation regarding said maximum. A little further digging, under **Remarks** has this: > > The following table describes the padding supported by different versions > of Microsoft Windows and the maximum length of rgb allowed by the different > combinations of operating systems and padding. > > > * If you are running XP or later and you're using OAEP padding, then the limit is stated to be > > Modulus size -2 -2\*hLen, where hLen is the size of the hash > > > No idea what the "size of the hash" might be, since the docs, AFAICS, don't mention "hash" anywhere except in regards to digital signatures. * If you are running Windows 2000 or later with the "high encryption pack" installed (again, no idea how you find that out), then the limit is stated to be > > Modulus size - 11. (11 bytes is the minimum padding possible.) > > > * Otherwise (Windows 98, Millenium or Windows 2000 or later without the aforementioned "high encryption pack" then you get "Direct Encryption and OAEP padding not supported", where the limitation is > > The maximum size allowed for a symmetric key. > > > Say...wait a second... RSA is an asymmetric algorithm, right? Worthless documentation. Sheesh.
6,299,460
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits. I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is: ``` public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); rsa.KeySize = 1024; } public static string EncryptData(string data2Encrypt) { AssignParameter(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } ``` This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying: CryptographicException was unhandled: Wrong length (OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length'). Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp? Thanks in advance, LordJesus **EDIT:** Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
2011/06/09
[ "https://Stackoverflow.com/questions/6299460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928874/" ]
If you want to *sign* you do not want to *encrypt*. Signatures and encryption are distinct algorithms. It does not help that there is a well-known signature algorithm called RSA, and a well-known asymmetric encryption algorithm also called RSA, and that the signature algorithm was first presented (and still is in many places) as "you encrypt with the private key". This is just plain confusing. In RSA encryption, the data to encrypt (with the public key) must be padded with what [PKCS#1](http://www.rsa.com/rsalabs/node.asp?id=2125) (the RSA standard) describes as "Type 2 padding", and the result (which has the same length than the modulus) is then processed through the modular exponentiation which is at the core of RSA (at the core, but RSA is not *only* a modular exponentiation; the padding is very important for security). When signing, the data to sign must be hashed, then the hash value is embedded in a structure which describes the hash function which was just used, and the encoded structure is itself padded with a "Type 1 padding" -- not the same padding than the padding for encryption, and that's important, too. Either way, a normal RSA engine will perform the type 1 or type 2 padding itself, and most RSA *signature* engines will also handle themselves the structure which identifies the used hash function. A RSA signature engine such as `RSACryptoServiceProvider` can work either with `SignHash()`, which expects the hash value (the 32 bytes obtained from SHA-256, *without* any kind of encapsulating structure or type 1 padding -- `RSACryptoServiceProvider` handles that itself), or `SignData()`, which expects the data to be signed (the engine then does the hash computation too). To sum up, if you do any kind of padding yourself, then you are doing it wrong. If you used `Encrypt()` to compute a signature, then you are doing it wrong, too.
See <http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.encrypt.aspx>. The exception thrown is probably "The length of the rgb parameter is greater than the maximum allowed length."
6,299,460
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits. I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is: ``` public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); rsa.KeySize = 1024; } public static string EncryptData(string data2Encrypt) { AssignParameter(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } ``` This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying: CryptographicException was unhandled: Wrong length (OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length'). Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp? Thanks in advance, LordJesus **EDIT:** Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
2011/06/09
[ "https://Stackoverflow.com/questions/6299460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928874/" ]
If you want to *sign* you do not want to *encrypt*. Signatures and encryption are distinct algorithms. It does not help that there is a well-known signature algorithm called RSA, and a well-known asymmetric encryption algorithm also called RSA, and that the signature algorithm was first presented (and still is in many places) as "you encrypt with the private key". This is just plain confusing. In RSA encryption, the data to encrypt (with the public key) must be padded with what [PKCS#1](http://www.rsa.com/rsalabs/node.asp?id=2125) (the RSA standard) describes as "Type 2 padding", and the result (which has the same length than the modulus) is then processed through the modular exponentiation which is at the core of RSA (at the core, but RSA is not *only* a modular exponentiation; the padding is very important for security). When signing, the data to sign must be hashed, then the hash value is embedded in a structure which describes the hash function which was just used, and the encoded structure is itself padded with a "Type 1 padding" -- not the same padding than the padding for encryption, and that's important, too. Either way, a normal RSA engine will perform the type 1 or type 2 padding itself, and most RSA *signature* engines will also handle themselves the structure which identifies the used hash function. A RSA signature engine such as `RSACryptoServiceProvider` can work either with `SignHash()`, which expects the hash value (the 32 bytes obtained from SHA-256, *without* any kind of encapsulating structure or type 1 padding -- `RSACryptoServiceProvider` handles that itself), or `SignData()`, which expects the data to be signed (the engine then does the hash computation too). To sum up, if you do any kind of padding yourself, then you are doing it wrong. If you used `Encrypt()` to compute a signature, then you are doing it wrong, too.
Usually RSA encryption has padding, and since your encrypted data size goes to the key size, there is no space for padding. Try to use longer key or less data size to encrypt.
6,299,460
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits. I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is: ``` public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); rsa.KeySize = 1024; } public static string EncryptData(string data2Encrypt) { AssignParameter(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } ``` This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying: CryptographicException was unhandled: Wrong length (OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length'). Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp? Thanks in advance, LordJesus **EDIT:** Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
2011/06/09
[ "https://Stackoverflow.com/questions/6299460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928874/" ]
The minimum key size for encrypting 128 bytes would be 1112 bits, when you are calling `Encrypt` with OAEP off. Note that setting the key size like this `rsa.KeySize = 1024` won't help, you need to actually generate they key of the right size and use them. This is what worked for me: ``` using System; using System.IO; using System.Security.Cryptography; namespace SO6299460 { class Program { static void Main() { GenerateKey(); string data2Encrypt = string.Empty.PadLeft(128,'$'); string encrypted = EncryptData(data2Encrypt); string decrypted = DecryptData(encrypted); Console.WriteLine(data2Encrypt); Console.WriteLine(encrypted); Console.WriteLine(decrypted); } private const string path = @"c:\"; public static void GenerateKey() { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1112); string publickKey = rsa.ToXmlString(false); string privateKey = rsa.ToXmlString(true); WriteStringToFile(publickKey, path + "publickey.xml"); WriteStringToFile(privateKey, path + "privatekey.xml"); } public static void WriteStringToFile(string value, string filename) { using (FileStream stream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read)) using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(value); writer.Flush(); stream.Flush(); } } public static string EncryptData(string data2Encrypt) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes,false); return Convert.ToBase64String(cipherbytes); } public static string DecryptData(string data2Decrypt) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader reader = new StreamReader(path + "privatekey.xml"); string key = reader.ReadToEnd(); rsa.FromXmlString(key); reader.Close(); byte[] plainbytes = rsa.Decrypt(Convert.FromBase64String(data2Decrypt), false); return System.Text.Encoding.UTF8.GetString(plainbytes); } } } ``` Note however, that I'm not using a crypto container, and thus, I don't need your `AssignParameter`, but if you need to use it, modifying the code should be easy enough. If you ever need to encrypt large quantities of data (much larger than 128 bytes) [this article](http://pages.infinit.net/ctech/20031101-0151.html) has sample code on how to do this.
Usually RSA encryption has padding, and since your encrypted data size goes to the key size, there is no space for padding. Try to use longer key or less data size to encrypt.
6,299,460
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits. I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is: ``` public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); rsa.KeySize = 1024; } public static string EncryptData(string data2Encrypt) { AssignParameter(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } ``` This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying: CryptographicException was unhandled: Wrong length (OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length'). Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp? Thanks in advance, LordJesus **EDIT:** Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
2011/06/09
[ "https://Stackoverflow.com/questions/6299460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928874/" ]
Apparently, according to this question — [how to use RSA to encrypt files (huge data) in C#](https://stackoverflow.com/questions/1199058/how-to-use-rsa-to-encrypt-files-huge-data-in-c) — RSA can only encrypt data shorter than its key length. Bizarre. The MSDN docs for[`RSACryptoServiceProvider.Encrypt()](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.encrypt.aspx) say that a CryptographicException may be thrown if *the length of the rgb parameter is greater than the maximum allowed length.* Well. That seems odd, especially since there doesn't seem to be much in the way of documentation regarding said maximum. A little further digging, under **Remarks** has this: > > The following table describes the padding supported by different versions > of Microsoft Windows and the maximum length of rgb allowed by the different > combinations of operating systems and padding. > > > * If you are running XP or later and you're using OAEP padding, then the limit is stated to be > > Modulus size -2 -2\*hLen, where hLen is the size of the hash > > > No idea what the "size of the hash" might be, since the docs, AFAICS, don't mention "hash" anywhere except in regards to digital signatures. * If you are running Windows 2000 or later with the "high encryption pack" installed (again, no idea how you find that out), then the limit is stated to be > > Modulus size - 11. (11 bytes is the minimum padding possible.) > > > * Otherwise (Windows 98, Millenium or Windows 2000 or later without the aforementioned "high encryption pack" then you get "Direct Encryption and OAEP padding not supported", where the limitation is > > The maximum size allowed for a symmetric key. > > > Say...wait a second... RSA is an asymmetric algorithm, right? Worthless documentation. Sheesh.
See <http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.encrypt.aspx>. The exception thrown is probably "The length of the rgb parameter is greater than the maximum allowed length."
6,299,460
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits. I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is: ``` public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); rsa.KeySize = 1024; } public static string EncryptData(string data2Encrypt) { AssignParameter(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } ``` This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying: CryptographicException was unhandled: Wrong length (OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length'). Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp? Thanks in advance, LordJesus **EDIT:** Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
2011/06/09
[ "https://Stackoverflow.com/questions/6299460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928874/" ]
If you want to *sign* you do not want to *encrypt*. Signatures and encryption are distinct algorithms. It does not help that there is a well-known signature algorithm called RSA, and a well-known asymmetric encryption algorithm also called RSA, and that the signature algorithm was first presented (and still is in many places) as "you encrypt with the private key". This is just plain confusing. In RSA encryption, the data to encrypt (with the public key) must be padded with what [PKCS#1](http://www.rsa.com/rsalabs/node.asp?id=2125) (the RSA standard) describes as "Type 2 padding", and the result (which has the same length than the modulus) is then processed through the modular exponentiation which is at the core of RSA (at the core, but RSA is not *only* a modular exponentiation; the padding is very important for security). When signing, the data to sign must be hashed, then the hash value is embedded in a structure which describes the hash function which was just used, and the encoded structure is itself padded with a "Type 1 padding" -- not the same padding than the padding for encryption, and that's important, too. Either way, a normal RSA engine will perform the type 1 or type 2 padding itself, and most RSA *signature* engines will also handle themselves the structure which identifies the used hash function. A RSA signature engine such as `RSACryptoServiceProvider` can work either with `SignHash()`, which expects the hash value (the 32 bytes obtained from SHA-256, *without* any kind of encapsulating structure or type 1 padding -- `RSACryptoServiceProvider` handles that itself), or `SignData()`, which expects the data to be signed (the engine then does the hash computation too). To sum up, if you do any kind of padding yourself, then you are doing it wrong. If you used `Encrypt()` to compute a signature, then you are doing it wrong, too.
Do you real need the custom padding? If not you could just use [RSACryptoServiceProvider.SignData Method](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.signdata.aspx)
6,299,460
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits. I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is: ``` public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); rsa.KeySize = 1024; } public static string EncryptData(string data2Encrypt) { AssignParameter(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } ``` This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying: CryptographicException was unhandled: Wrong length (OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length'). Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp? Thanks in advance, LordJesus **EDIT:** Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
2011/06/09
[ "https://Stackoverflow.com/questions/6299460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928874/" ]
The minimum key size for encrypting 128 bytes would be 1112 bits, when you are calling `Encrypt` with OAEP off. Note that setting the key size like this `rsa.KeySize = 1024` won't help, you need to actually generate they key of the right size and use them. This is what worked for me: ``` using System; using System.IO; using System.Security.Cryptography; namespace SO6299460 { class Program { static void Main() { GenerateKey(); string data2Encrypt = string.Empty.PadLeft(128,'$'); string encrypted = EncryptData(data2Encrypt); string decrypted = DecryptData(encrypted); Console.WriteLine(data2Encrypt); Console.WriteLine(encrypted); Console.WriteLine(decrypted); } private const string path = @"c:\"; public static void GenerateKey() { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1112); string publickKey = rsa.ToXmlString(false); string privateKey = rsa.ToXmlString(true); WriteStringToFile(publickKey, path + "publickey.xml"); WriteStringToFile(privateKey, path + "privatekey.xml"); } public static void WriteStringToFile(string value, string filename) { using (FileStream stream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read)) using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(value); writer.Flush(); stream.Flush(); } } public static string EncryptData(string data2Encrypt) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes,false); return Convert.ToBase64String(cipherbytes); } public static string DecryptData(string data2Decrypt) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader reader = new StreamReader(path + "privatekey.xml"); string key = reader.ReadToEnd(); rsa.FromXmlString(key); reader.Close(); byte[] plainbytes = rsa.Decrypt(Convert.FromBase64String(data2Decrypt), false); return System.Text.Encoding.UTF8.GetString(plainbytes); } } } ``` Note however, that I'm not using a crypto container, and thus, I don't need your `AssignParameter`, but if you need to use it, modifying the code should be easy enough. If you ever need to encrypt large quantities of data (much larger than 128 bytes) [this article](http://pages.infinit.net/ctech/20031101-0151.html) has sample code on how to do this.
Apparently, according to this question — [how to use RSA to encrypt files (huge data) in C#](https://stackoverflow.com/questions/1199058/how-to-use-rsa-to-encrypt-files-huge-data-in-c) — RSA can only encrypt data shorter than its key length. Bizarre. The MSDN docs for[`RSACryptoServiceProvider.Encrypt()](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.encrypt.aspx) say that a CryptographicException may be thrown if *the length of the rgb parameter is greater than the maximum allowed length.* Well. That seems odd, especially since there doesn't seem to be much in the way of documentation regarding said maximum. A little further digging, under **Remarks** has this: > > The following table describes the padding supported by different versions > of Microsoft Windows and the maximum length of rgb allowed by the different > combinations of operating systems and padding. > > > * If you are running XP or later and you're using OAEP padding, then the limit is stated to be > > Modulus size -2 -2\*hLen, where hLen is the size of the hash > > > No idea what the "size of the hash" might be, since the docs, AFAICS, don't mention "hash" anywhere except in regards to digital signatures. * If you are running Windows 2000 or later with the "high encryption pack" installed (again, no idea how you find that out), then the limit is stated to be > > Modulus size - 11. (11 bytes is the minimum padding possible.) > > > * Otherwise (Windows 98, Millenium or Windows 2000 or later without the aforementioned "high encryption pack" then you get "Direct Encryption and OAEP padding not supported", where the limitation is > > The maximum size allowed for a symmetric key. > > > Say...wait a second... RSA is an asymmetric algorithm, right? Worthless documentation. Sheesh.
6,299,460
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits. I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is: ``` public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); rsa.KeySize = 1024; } public static string EncryptData(string data2Encrypt) { AssignParameter(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } ``` This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying: CryptographicException was unhandled: Wrong length (OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length'). Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp? Thanks in advance, LordJesus **EDIT:** Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
2011/06/09
[ "https://Stackoverflow.com/questions/6299460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928874/" ]
Apparently, according to this question — [how to use RSA to encrypt files (huge data) in C#](https://stackoverflow.com/questions/1199058/how-to-use-rsa-to-encrypt-files-huge-data-in-c) — RSA can only encrypt data shorter than its key length. Bizarre. The MSDN docs for[`RSACryptoServiceProvider.Encrypt()](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.encrypt.aspx) say that a CryptographicException may be thrown if *the length of the rgb parameter is greater than the maximum allowed length.* Well. That seems odd, especially since there doesn't seem to be much in the way of documentation regarding said maximum. A little further digging, under **Remarks** has this: > > The following table describes the padding supported by different versions > of Microsoft Windows and the maximum length of rgb allowed by the different > combinations of operating systems and padding. > > > * If you are running XP or later and you're using OAEP padding, then the limit is stated to be > > Modulus size -2 -2\*hLen, where hLen is the size of the hash > > > No idea what the "size of the hash" might be, since the docs, AFAICS, don't mention "hash" anywhere except in regards to digital signatures. * If you are running Windows 2000 or later with the "high encryption pack" installed (again, no idea how you find that out), then the limit is stated to be > > Modulus size - 11. (11 bytes is the minimum padding possible.) > > > * Otherwise (Windows 98, Millenium or Windows 2000 or later without the aforementioned "high encryption pack" then you get "Direct Encryption and OAEP padding not supported", where the limitation is > > The maximum size allowed for a symmetric key. > > > Say...wait a second... RSA is an asymmetric algorithm, right? Worthless documentation. Sheesh.
Do you real need the custom padding? If not you could just use [RSACryptoServiceProvider.SignData Method](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.signdata.aspx)
6,299,460
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits. I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is: ``` public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); rsa.KeySize = 1024; } public static string EncryptData(string data2Encrypt) { AssignParameter(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes); } ``` This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying: CryptographicException was unhandled: Wrong length (OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length'). Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp? Thanks in advance, LordJesus **EDIT:** Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
2011/06/09
[ "https://Stackoverflow.com/questions/6299460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928874/" ]
The minimum key size for encrypting 128 bytes would be 1112 bits, when you are calling `Encrypt` with OAEP off. Note that setting the key size like this `rsa.KeySize = 1024` won't help, you need to actually generate they key of the right size and use them. This is what worked for me: ``` using System; using System.IO; using System.Security.Cryptography; namespace SO6299460 { class Program { static void Main() { GenerateKey(); string data2Encrypt = string.Empty.PadLeft(128,'$'); string encrypted = EncryptData(data2Encrypt); string decrypted = DecryptData(encrypted); Console.WriteLine(data2Encrypt); Console.WriteLine(encrypted); Console.WriteLine(decrypted); } private const string path = @"c:\"; public static void GenerateKey() { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1112); string publickKey = rsa.ToXmlString(false); string privateKey = rsa.ToXmlString(true); WriteStringToFile(publickKey, path + "publickey.xml"); WriteStringToFile(privateKey, path + "privatekey.xml"); } public static void WriteStringToFile(string value, string filename) { using (FileStream stream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read)) using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(value); writer.Flush(); stream.Flush(); } } public static string EncryptData(string data2Encrypt) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader reader = new StreamReader(path + "publickey.xml"); string publicOnlyKeyXML = reader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXML); reader.Close(); //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt); byte[] cipherbytes = rsa.Encrypt(plainbytes,false); return Convert.ToBase64String(cipherbytes); } public static string DecryptData(string data2Decrypt) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader reader = new StreamReader(path + "privatekey.xml"); string key = reader.ReadToEnd(); rsa.FromXmlString(key); reader.Close(); byte[] plainbytes = rsa.Decrypt(Convert.FromBase64String(data2Decrypt), false); return System.Text.Encoding.UTF8.GetString(plainbytes); } } } ``` Note however, that I'm not using a crypto container, and thus, I don't need your `AssignParameter`, but if you need to use it, modifying the code should be easy enough. If you ever need to encrypt large quantities of data (much larger than 128 bytes) [this article](http://pages.infinit.net/ctech/20031101-0151.html) has sample code on how to do this.
See <http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.encrypt.aspx>. The exception thrown is probably "The length of the rgb parameter is greater than the maximum allowed length."
41,339,035
I do have a select box, like so: ``` <select id="fatherhoodDocument" name="fatherhoodDocument" style="width:250px;" data-bvalidator="myCyrillicDigitsAndSpaceValidator,required" data-bvalidator-modifier="myCapsModifier"> <option value="[$i18n.getString( "select" )]">[$i18n.getString( "select" )]</option> <option value="test1">test1</option> <option value="test2">test</option> <option value="test3">test3</option> </select> ``` And I have 2 hidden inputs, which should be activated and shown if one of the options above have been chosen: ``` <input type="text" id="marriageregdate" name="marriageregdate" value="" style="width:80px; display:none;" data-bvalidator="required" data-fordraft="required"/> <input type="text" id="filliationregdate" name="filliationregdate" value="" style="width:80px; display:none;" data-bvalidator="required" data-fordraft="required"/> ``` This is the `JavaScript` code which does change the properties, if some of the options have been clicked: ``` $('#fatherhoodDocument').on('change',function(){ var selection = $(this).val(); switch(selection){ case "test1": $("#marriageregdate").show(); $( "#marriageregdate" ).prop( "disabled", false ); $("#filliationregdate").hide(); $( "#filliationregdate" ).prop( "disabled", true ); break; case "test2": $("#filliationregdate").show(); $( "#filliationregdate" ).prop( "disabled", false ); $("#marriageregdate").hide(); $( "#marriageregdate" ).prop( "disabled", true ); break; default: $("#marriageregdate").hide(); $("#filliationregdate").hide(); } }); ``` It works just fine, untill the page has not been refreshed. Once the page is refresehed (clicked f5, or browser icon) the inputs go back to their original state, i.e hidden. But the value of the `select box` remains the same as it was chosen before. So, my question is how to save the `code` changes too, after the page have been refreshed?
2016/12/27
[ "https://Stackoverflow.com/questions/41339035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/588519/" ]
Well, on page load/refresh, `$('#fatherhoodDocument')` hasn't changed yet so the change handler isn't called. What you could do is assign the change handler to a variable and call that on document ready **and** on `$('#fatherhoodDocument')` change. ``` $(function () { var ddFatherhoodDocument = $('#fatherhoodDocument'); var toggleTextboxes = function () { var selection = ddFatherhoodDocument.val(); switch(selection) { case "test1": $("#marriageregdate").show(); $( "#marriageregdate" ).prop( "disabled", false ); $("#filliationregdate").hide(); $( "#filliationregdate" ).prop( "disabled", true ); break; case "test2": $("#filliationregdate").show(); $( "#filliationregdate" ).prop( "disabled", false ); $("#marriageregdate").hide(); $( "#marriageregdate" ).prop( "disabled", true ); break; default: $("#marriageregdate").hide(); $("#filliationregdate").hide(); } } ddFatherhoodDocument.on('change', toggleTextboxes); toggleTextboxes(); }); ```
I am not why your SELECT remains unchanged on page refresh. However if you want to keep very first option selected after page refresh just try to add "selected" attribute. check [this](http://www.w3schools.com/tags/att_option_selected.asp). ```html <select id="fatherhoodDocument" name="fatherhoodDocument" style="width:250px;" data-bvalidator="myCyrillicDigitsAndSpaceValidator,required" data-bvalidator-modifier="myCapsModifier"> <option value="[$i18n.getString( "select" )]" selected>[$i18n.getString( "select" )]</option> <option value="test1">test1</option> <option value="test2">test</option> <option value="test3">test3</option> </select> ```
41,339,035
I do have a select box, like so: ``` <select id="fatherhoodDocument" name="fatherhoodDocument" style="width:250px;" data-bvalidator="myCyrillicDigitsAndSpaceValidator,required" data-bvalidator-modifier="myCapsModifier"> <option value="[$i18n.getString( "select" )]">[$i18n.getString( "select" )]</option> <option value="test1">test1</option> <option value="test2">test</option> <option value="test3">test3</option> </select> ``` And I have 2 hidden inputs, which should be activated and shown if one of the options above have been chosen: ``` <input type="text" id="marriageregdate" name="marriageregdate" value="" style="width:80px; display:none;" data-bvalidator="required" data-fordraft="required"/> <input type="text" id="filliationregdate" name="filliationregdate" value="" style="width:80px; display:none;" data-bvalidator="required" data-fordraft="required"/> ``` This is the `JavaScript` code which does change the properties, if some of the options have been clicked: ``` $('#fatherhoodDocument').on('change',function(){ var selection = $(this).val(); switch(selection){ case "test1": $("#marriageregdate").show(); $( "#marriageregdate" ).prop( "disabled", false ); $("#filliationregdate").hide(); $( "#filliationregdate" ).prop( "disabled", true ); break; case "test2": $("#filliationregdate").show(); $( "#filliationregdate" ).prop( "disabled", false ); $("#marriageregdate").hide(); $( "#marriageregdate" ).prop( "disabled", true ); break; default: $("#marriageregdate").hide(); $("#filliationregdate").hide(); } }); ``` It works just fine, untill the page has not been refreshed. Once the page is refresehed (clicked f5, or browser icon) the inputs go back to their original state, i.e hidden. But the value of the `select box` remains the same as it was chosen before. So, my question is how to save the `code` changes too, after the page have been refreshed?
2016/12/27
[ "https://Stackoverflow.com/questions/41339035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/588519/" ]
You could do something like as shown below,you can define the function under a different function name and call it on ready of the document as well as on change of the dropdown ,in the on ready function the changeData function will not be called unless the dropdown has something selected in it other than the default selection ```js $('#fatherhoodDocument').on('change',changeData); $(document).ready(function() { console.log($("#fatherhoodDocument")[0].selectedIndex); if($('#fatherhoodDocument')[0].selectedIndex!=0){ changeData(); } }); function changeData(){ var selection = $('#fatherhoodDocument').val(); switch(selection){ case "test1": $("#marriageregdate").show(); $( "#marriageregdate" ).prop( "disabled", false ); $("#filliationregdate").hide(); $( "#filliationregdate" ).prop( "disabled", true ); break; case "test2": $("#filliationregdate").show(); $( "#filliationregdate" ).prop( "disabled", false); $("#marriageregdate").hide(); $( "#marriageregdate" ).prop( "disabled", true ); break; default: $("#marriageregdate").hide(); $("#filliationregdate").hide(); } } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="fatherhoodDocument" name="fatherhoodDocument" style="width:250px;" data-bvalidator="myCyrillicDigitsAndSpaceValidator,required" data-bvalidator-modifier="myCapsModifier"> <option value="[$i18n.getString( "select" )]">[$i18n.getString( "select" )]</option> <option value="test1">test1</option> <option value="test2">test</option> <option value="test3">test3</option> </select> <input type="text" id="marriageregdate" name="marriageregdate" value="" style="width:80px; display:none;" data-bvalidator="required" data-fordraft="required"/> <input type="text" id="filliationregdate" name="filliationregdate" value="" style="width:80px; display:none;" data-bvalidator="required" data-fordraft="required"/> ```
I am not why your SELECT remains unchanged on page refresh. However if you want to keep very first option selected after page refresh just try to add "selected" attribute. check [this](http://www.w3schools.com/tags/att_option_selected.asp). ```html <select id="fatherhoodDocument" name="fatherhoodDocument" style="width:250px;" data-bvalidator="myCyrillicDigitsAndSpaceValidator,required" data-bvalidator-modifier="myCapsModifier"> <option value="[$i18n.getString( "select" )]" selected>[$i18n.getString( "select" )]</option> <option value="test1">test1</option> <option value="test2">test</option> <option value="test3">test3</option> </select> ```
14,404,801
``` html{ background: url(/assets/flower.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } ``` How can I make this code randomly choose from a selected number of pictures as background. I am using Rails 3, so have that in mind, if that will simplify the process of making this work. THANKS! :D
2013/01/18
[ "https://Stackoverflow.com/questions/14404801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1990339/" ]
In your view file where you would like to display the background image, add this line ``` <style type="text/css"> html { background: url(<%= randomized_background_image %>) no-repeat center center fixed; } </style> ``` Now in your application\_helper ``` def randomized_background_image images = ["assets/foo.jpg", "assets/random.jpg", "assets/super_random"] images[rand(images.size)] end ```
The easiest way is to create an actions with redirect to a random image the browser will follow the redirect. app/controller/background\_controller.rb ``` class BackgroundController < ApplicationController def image redirect_to "/assets/images/background_#{rand(10)}.jpg" end end ``` This will randomly redirect to a background image between `background_0.jpg` and `background_9.jpg` config/routes.rb ``` Something::Application.routes.draw do … get '/random_background.jpg', to: 'background#image' … end ``` css ``` html{ background: url(/random_background.jpg) no-repeat center center fixed; } ``` --- Some more advanced would be to do something like this in a Middleware, so such a request won't need so whole rails stack. app/middleware/random\_background\_middleware.rb ``` class RandomBackgroundMiddleware def initialize(app, count = 10) @app = app @count = count end def call(env) if env["PATH_INFO"] == "/random_background.jpg" [302, {"Location" => "/assets/images/background_#{rand(@count)}.jpg")}, ''] else @app.call(env) end end end ``` `config/application.rb` ``` config.middleware.insert_before 0, "RandomBackgroundMiddlware" ``` `insert_before 0` is used to place it at the top of the Middleware-Chain --- Or even better would be something like this in your webserver config. But I don't how or if this can be done.
14,404,801
``` html{ background: url(/assets/flower.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } ``` How can I make this code randomly choose from a selected number of pictures as background. I am using Rails 3, so have that in mind, if that will simplify the process of making this work. THANKS! :D
2013/01/18
[ "https://Stackoverflow.com/questions/14404801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1990339/" ]
The easiest way is to create an actions with redirect to a random image the browser will follow the redirect. app/controller/background\_controller.rb ``` class BackgroundController < ApplicationController def image redirect_to "/assets/images/background_#{rand(10)}.jpg" end end ``` This will randomly redirect to a background image between `background_0.jpg` and `background_9.jpg` config/routes.rb ``` Something::Application.routes.draw do … get '/random_background.jpg', to: 'background#image' … end ``` css ``` html{ background: url(/random_background.jpg) no-repeat center center fixed; } ``` --- Some more advanced would be to do something like this in a Middleware, so such a request won't need so whole rails stack. app/middleware/random\_background\_middleware.rb ``` class RandomBackgroundMiddleware def initialize(app, count = 10) @app = app @count = count end def call(env) if env["PATH_INFO"] == "/random_background.jpg" [302, {"Location" => "/assets/images/background_#{rand(@count)}.jpg")}, ''] else @app.call(env) end end end ``` `config/application.rb` ``` config.middleware.insert_before 0, "RandomBackgroundMiddlware" ``` `insert_before 0` is used to place it at the top of the Middleware-Chain --- Or even better would be something like this in your webserver config. But I don't how or if this can be done.
I did this by creating a random class name in the view like this: ``` <div class="homepage-banner-<%= rand(1..10) %>"> ``` Then I just added multiple images to my css like this: ``` .homepage-banner-1 background-image: image-url('homepage/homepage-feature-1.jpg') .homepage-banner-2 background-image: image-url('homepage/homepage-feature-2.jpg') .homepage-banner-3 background-image: image-url('homepage/homepage-feature-3.jpg') etc. ``` Not sure if that's the best way, but it's very simple.
14,404,801
``` html{ background: url(/assets/flower.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } ``` How can I make this code randomly choose from a selected number of pictures as background. I am using Rails 3, so have that in mind, if that will simplify the process of making this work. THANKS! :D
2013/01/18
[ "https://Stackoverflow.com/questions/14404801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1990339/" ]
In your view file where you would like to display the background image, add this line ``` <style type="text/css"> html { background: url(<%= randomized_background_image %>) no-repeat center center fixed; } </style> ``` Now in your application\_helper ``` def randomized_background_image images = ["assets/foo.jpg", "assets/random.jpg", "assets/super_random"] images[rand(images.size)] end ```
I did this by creating a random class name in the view like this: ``` <div class="homepage-banner-<%= rand(1..10) %>"> ``` Then I just added multiple images to my css like this: ``` .homepage-banner-1 background-image: image-url('homepage/homepage-feature-1.jpg') .homepage-banner-2 background-image: image-url('homepage/homepage-feature-2.jpg') .homepage-banner-3 background-image: image-url('homepage/homepage-feature-3.jpg') etc. ``` Not sure if that's the best way, but it's very simple.
27,095
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details: > > When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them, > and for my clothing they cast lots.” (John 19:23-24) > > > John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top." "From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit. Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
2017/02/20
[ "https://hermeneutics.stackexchange.com/questions/27095", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8450/" ]
John gives a more detailed description of this aspect of the crucifixion than either Mark or Mathew: > > And they crucify Him, and divide His garments among *themselves*, casting a lot for them *to decide* who should take what. (Mark 15:24 DLNT) > > > And having crucified Him, they divided His garments among *themselves*, casting a lot. > > (Matthew 27:35 DLNT) > > > Then the soldiers, when they crucified Jesus, took His garments and made four parts— a part *for* each soldier— and the tunic. Now the tunic was seamless, woven from the top through *the* whole. So they said to one another, “Let us not tear it, but let us cast-lots for it *to decide* whose it will be”— in order that the Scripture [in Ps 22:18] might be fulfilled, the *one* saying, “They divided My garments among themselves, and they cast a lot for My clothing”. So indeed, the soldiers did these *things*. (John 19:23-24 DLNT) > > > Writing after both Mark and Matthew, John completes the record of how the clothing of Jesus was divided. This account is purposeful to include three pieces of information: 1. The Old Testament passage fulfilled 2. The number of pieces of clothing (five) 3. Identifying the piece of clothing which was not torn (a tunic - χιτὼν) As noted by User34445 John makes the point that both aspects of Psalm 22:18 were fulfilled: the clothing was divided **and** lots were cast for the garments. In addition, there is a difference between the Masoretic Text (MT) and that John which cites: > > Psalm 22:18: > > They divide my clothes among themselves **casting lots** for my garments. (JPS Translation) > > They divided My garments among themselves, and they **cast a lot** for My clothing. (DLNT) > > > The Hebrew is plural (lots). John states a single lot was cast. This difference shows John has the Septuagint version of Psalm 22 in mind: > > John 19:23: > > διεμερίσαντο τὰ ἱμάτιά μου ἑαυτοῖς καὶ ἐπὶ τὸν ἱματισμόν μου ἔβαλον κλῆρον (NA28) > > > Psalm 22:18: > > διεμερίσαντο τὰ ἱμάτιά μου ἑαυτοῖς καὶ ἐπὶ τὸν ἱματισμόν μου ἔβαλον κλῆρον (LXX) > > > John's citation is verbatim. The singular casting of a lot does not materially affect the fulfillment of the Psalm. It shows John is pointing the reader to the Greek text of the OT. The article of clothing which was preserved in one piece is specifically a tunic [[χιτών]](https://www.blueletterbible.org/lang/lexicon/lexicon.cfm?Strongs=G5509&t=KJV) which is found in some significant places. Two in particular: * This was the piece of clothing the LORD made for the first man and woman when they left the Garden of Eden (Genesis 3:21). + Just as the first man received a tunic from the LORD God; one of the Roman soldiers received a tunic from the Lord Jesus. * The garment for the High Priest (Exodus 28:4). + Jesus is the true High Priest (e.g. Hebrews 10:21) The emphasis on not tearing the garment invites a comparison to the clothing of the High Priest which is not supposed to be torn: > > The priest who is chief among his brothers, on whose head the anointing oil is poured and who has been consecrated to wear the garments, shall not let the hair of his head hang loose nor tear his clothes. (Leviticus 21:10 ESV) 1 > > > In particular, there is a connection to the High Priest is found on the Day of Atonement: > > He shall put on the holy linen coat and shall have the linen undergarment on his body, and he shall tie the linen sash around his waist, and wear the linen turban; these are the holy garments. He shall bathe his body in water and then put them on. (Leviticus 16:4 ESV) > > > καὶ **χιτῶνα** λινοῦν ἡγιασμένον ἐνδύσεται καὶ περισκελὲς λινοῦν ἔσται ἐπὶ τοῦ χρωτὸς αὐτοῦ καὶ ζώνῃ λινῇ ζώσεται καὶ κίδαριν λινῆν περιθήσεται ἱμάτια ἅγιά ἐστιν καὶ λούσεται ὕδατι πᾶν τὸ σῶμα αὐτοῦ καὶ ἐνδύσεται αὐτά (LXX) > > > The tunic is removed and left in the Holy Place: > > “Then Aaron shall come into the tent of meeting and shall take off the linen garments that he put on when he went into the Holy Place and shall leave them there. (Leviticus 16:23 ESV) > > > Therefore Mark and Matthew record the tearing of the Temple veil opening the entrance to the Most Holy Place and John presents Jesus as the High Priest, who is and makes the sacrifice and leaves His tunic outside the Most Holy Place. --- 1. The crown of thorns fulfills this requirement
I believe that the tunic that was not torn represents the Apostolic gift (John 19:23-24). We have the 5 fold ministry, where the Apostolic gift embraces all the other 4 (Ephesians 4:11-13). The purple tunic represents the entire operation. We should embrace all the other gifts so that the Apostolic foundation can work effectively. (Ephessians 2:20)
27,095
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details: > > When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them, > and for my clothing they cast lots.” (John 19:23-24) > > > John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top." "From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit. Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
2017/02/20
[ "https://hermeneutics.stackexchange.com/questions/27095", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8450/" ]
I believe that the tunic that was not torn represents the Apostolic gift (John 19:23-24). We have the 5 fold ministry, where the Apostolic gift embraces all the other 4 (Ephesians 4:11-13). The purple tunic represents the entire operation. We should embrace all the other gifts so that the Apostolic foundation can work effectively. (Ephessians 2:20)
Christ came in the fullness of time close to the 4,000 year mark after Adam. The fourth day is when the material universe (cosmos) came to be and light was divided from darkness. He took on the sin of the world and His garment was symbolically divided into four pieces (for the four corners of the world). The four gospels are given as witness to what Jesus did. And He will only return when the whole gospel is preached to the whole world. I believe that’s what the divided four pieces represent. The inner garment that was seamless probably represented His character as others have said but the hidden component, the Living Word, His divine person could not be divided. His body human - broken for the World, His divinity robed within experiencing everything firsthand.
27,095
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details: > > When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them, > and for my clothing they cast lots.” (John 19:23-24) > > > John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top." "From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit. Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
2017/02/20
[ "https://hermeneutics.stackexchange.com/questions/27095", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8450/" ]
'**The tunic was seamless, woven in one piece from top to bottom**'. That's what "*sewn from the top*" means. It's a special type of weaving - something akin to seamless knitting (on circular needles) except through weaving. Weaving a seamless garment was a special skill, out of the ordinary and exceedingly rare - so quite valuable. This detail implies the garment was specially woven for Yehshua, perhaps even the product of a mother's hand, or possibly a close follower - like Mary Magdalene. > > Notice the prophecy in **Psalm 22:18** - ***They divide my clothes among them and cast lots for my garment***. > This prophesy contains two details: > > > * They divide my clothes among them; and > * {they} cast lots for my garment. > > > Why divide **AND** cast lots? > > > **ANSWER**: The detail contained in **Matthew 27:3** provides the answer to the riddle of **Psalm 22:18**. The clothes that could be divided were divided, yet one was seamless *sewn from the top* and quite valuable so sought after. Lots were drawn for the tunic because of its value. > > >
What does it signify to tear Christ's robe into 4 pieces? Explainations given do not give the meaning ? Its the question am asking
27,095
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details: > > When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them, > and for my clothing they cast lots.” (John 19:23-24) > > > John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top." "From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit. Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
2017/02/20
[ "https://hermeneutics.stackexchange.com/questions/27095", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8450/" ]
John gives a more detailed description of this aspect of the crucifixion than either Mark or Mathew: > > And they crucify Him, and divide His garments among *themselves*, casting a lot for them *to decide* who should take what. (Mark 15:24 DLNT) > > > And having crucified Him, they divided His garments among *themselves*, casting a lot. > > (Matthew 27:35 DLNT) > > > Then the soldiers, when they crucified Jesus, took His garments and made four parts— a part *for* each soldier— and the tunic. Now the tunic was seamless, woven from the top through *the* whole. So they said to one another, “Let us not tear it, but let us cast-lots for it *to decide* whose it will be”— in order that the Scripture [in Ps 22:18] might be fulfilled, the *one* saying, “They divided My garments among themselves, and they cast a lot for My clothing”. So indeed, the soldiers did these *things*. (John 19:23-24 DLNT) > > > Writing after both Mark and Matthew, John completes the record of how the clothing of Jesus was divided. This account is purposeful to include three pieces of information: 1. The Old Testament passage fulfilled 2. The number of pieces of clothing (five) 3. Identifying the piece of clothing which was not torn (a tunic - χιτὼν) As noted by User34445 John makes the point that both aspects of Psalm 22:18 were fulfilled: the clothing was divided **and** lots were cast for the garments. In addition, there is a difference between the Masoretic Text (MT) and that John which cites: > > Psalm 22:18: > > They divide my clothes among themselves **casting lots** for my garments. (JPS Translation) > > They divided My garments among themselves, and they **cast a lot** for My clothing. (DLNT) > > > The Hebrew is plural (lots). John states a single lot was cast. This difference shows John has the Septuagint version of Psalm 22 in mind: > > John 19:23: > > διεμερίσαντο τὰ ἱμάτιά μου ἑαυτοῖς καὶ ἐπὶ τὸν ἱματισμόν μου ἔβαλον κλῆρον (NA28) > > > Psalm 22:18: > > διεμερίσαντο τὰ ἱμάτιά μου ἑαυτοῖς καὶ ἐπὶ τὸν ἱματισμόν μου ἔβαλον κλῆρον (LXX) > > > John's citation is verbatim. The singular casting of a lot does not materially affect the fulfillment of the Psalm. It shows John is pointing the reader to the Greek text of the OT. The article of clothing which was preserved in one piece is specifically a tunic [[χιτών]](https://www.blueletterbible.org/lang/lexicon/lexicon.cfm?Strongs=G5509&t=KJV) which is found in some significant places. Two in particular: * This was the piece of clothing the LORD made for the first man and woman when they left the Garden of Eden (Genesis 3:21). + Just as the first man received a tunic from the LORD God; one of the Roman soldiers received a tunic from the Lord Jesus. * The garment for the High Priest (Exodus 28:4). + Jesus is the true High Priest (e.g. Hebrews 10:21) The emphasis on not tearing the garment invites a comparison to the clothing of the High Priest which is not supposed to be torn: > > The priest who is chief among his brothers, on whose head the anointing oil is poured and who has been consecrated to wear the garments, shall not let the hair of his head hang loose nor tear his clothes. (Leviticus 21:10 ESV) 1 > > > In particular, there is a connection to the High Priest is found on the Day of Atonement: > > He shall put on the holy linen coat and shall have the linen undergarment on his body, and he shall tie the linen sash around his waist, and wear the linen turban; these are the holy garments. He shall bathe his body in water and then put them on. (Leviticus 16:4 ESV) > > > καὶ **χιτῶνα** λινοῦν ἡγιασμένον ἐνδύσεται καὶ περισκελὲς λινοῦν ἔσται ἐπὶ τοῦ χρωτὸς αὐτοῦ καὶ ζώνῃ λινῇ ζώσεται καὶ κίδαριν λινῆν περιθήσεται ἱμάτια ἅγιά ἐστιν καὶ λούσεται ὕδατι πᾶν τὸ σῶμα αὐτοῦ καὶ ἐνδύσεται αὐτά (LXX) > > > The tunic is removed and left in the Holy Place: > > “Then Aaron shall come into the tent of meeting and shall take off the linen garments that he put on when he went into the Holy Place and shall leave them there. (Leviticus 16:23 ESV) > > > Therefore Mark and Matthew record the tearing of the Temple veil opening the entrance to the Most Holy Place and John presents Jesus as the High Priest, who is and makes the sacrifice and leaves His tunic outside the Most Holy Place. --- 1. The crown of thorns fulfills this requirement
The garment had no seams , representing there is no hole or crack in which to enter Heaven or be saved but only through Jesus Christ and his sacrifice and grace . When Jesus entered the throne to His Father He was given the garment of holiness and praise and we will also . Casting lots or trying to buy your way into salvation or enter through any other way besides the blood of Jesus will not save you ! Only through accepting His sacrifice and cleansing blood can we be saved
27,095
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details: > > When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them, > and for my clothing they cast lots.” (John 19:23-24) > > > John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top." "From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit. Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
2017/02/20
[ "https://hermeneutics.stackexchange.com/questions/27095", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8450/" ]
What does it signify to tear Christ's robe into 4 pieces? Explainations given do not give the meaning ? Its the question am asking
Christ came in the fullness of time close to the 4,000 year mark after Adam. The fourth day is when the material universe (cosmos) came to be and light was divided from darkness. He took on the sin of the world and His garment was symbolically divided into four pieces (for the four corners of the world). The four gospels are given as witness to what Jesus did. And He will only return when the whole gospel is preached to the whole world. I believe that’s what the divided four pieces represent. The inner garment that was seamless probably represented His character as others have said but the hidden component, the Living Word, His divine person could not be divided. His body human - broken for the World, His divinity robed within experiencing everything firsthand.
27,095
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details: > > When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them, > and for my clothing they cast lots.” (John 19:23-24) > > > John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top." "From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit. Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
2017/02/20
[ "https://hermeneutics.stackexchange.com/questions/27095", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8450/" ]
'**The tunic was seamless, woven in one piece from top to bottom**'. That's what "*sewn from the top*" means. It's a special type of weaving - something akin to seamless knitting (on circular needles) except through weaving. Weaving a seamless garment was a special skill, out of the ordinary and exceedingly rare - so quite valuable. This detail implies the garment was specially woven for Yehshua, perhaps even the product of a mother's hand, or possibly a close follower - like Mary Magdalene. > > Notice the prophecy in **Psalm 22:18** - ***They divide my clothes among them and cast lots for my garment***. > This prophesy contains two details: > > > * They divide my clothes among them; and > * {they} cast lots for my garment. > > > Why divide **AND** cast lots? > > > **ANSWER**: The detail contained in **Matthew 27:3** provides the answer to the riddle of **Psalm 22:18**. The clothes that could be divided were divided, yet one was seamless *sewn from the top* and quite valuable so sought after. Lots were drawn for the tunic because of its value. > > >
Christ came in the fullness of time close to the 4,000 year mark after Adam. The fourth day is when the material universe (cosmos) came to be and light was divided from darkness. He took on the sin of the world and His garment was symbolically divided into four pieces (for the four corners of the world). The four gospels are given as witness to what Jesus did. And He will only return when the whole gospel is preached to the whole world. I believe that’s what the divided four pieces represent. The inner garment that was seamless probably represented His character as others have said but the hidden component, the Living Word, His divine person could not be divided. His body human - broken for the World, His divinity robed within experiencing everything firsthand.
27,095
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details: > > When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them, > and for my clothing they cast lots.” (John 19:23-24) > > > John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top." "From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit. Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
2017/02/20
[ "https://hermeneutics.stackexchange.com/questions/27095", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8450/" ]
John gives a more detailed description of this aspect of the crucifixion than either Mark or Mathew: > > And they crucify Him, and divide His garments among *themselves*, casting a lot for them *to decide* who should take what. (Mark 15:24 DLNT) > > > And having crucified Him, they divided His garments among *themselves*, casting a lot. > > (Matthew 27:35 DLNT) > > > Then the soldiers, when they crucified Jesus, took His garments and made four parts— a part *for* each soldier— and the tunic. Now the tunic was seamless, woven from the top through *the* whole. So they said to one another, “Let us not tear it, but let us cast-lots for it *to decide* whose it will be”— in order that the Scripture [in Ps 22:18] might be fulfilled, the *one* saying, “They divided My garments among themselves, and they cast a lot for My clothing”. So indeed, the soldiers did these *things*. (John 19:23-24 DLNT) > > > Writing after both Mark and Matthew, John completes the record of how the clothing of Jesus was divided. This account is purposeful to include three pieces of information: 1. The Old Testament passage fulfilled 2. The number of pieces of clothing (five) 3. Identifying the piece of clothing which was not torn (a tunic - χιτὼν) As noted by User34445 John makes the point that both aspects of Psalm 22:18 were fulfilled: the clothing was divided **and** lots were cast for the garments. In addition, there is a difference between the Masoretic Text (MT) and that John which cites: > > Psalm 22:18: > > They divide my clothes among themselves **casting lots** for my garments. (JPS Translation) > > They divided My garments among themselves, and they **cast a lot** for My clothing. (DLNT) > > > The Hebrew is plural (lots). John states a single lot was cast. This difference shows John has the Septuagint version of Psalm 22 in mind: > > John 19:23: > > διεμερίσαντο τὰ ἱμάτιά μου ἑαυτοῖς καὶ ἐπὶ τὸν ἱματισμόν μου ἔβαλον κλῆρον (NA28) > > > Psalm 22:18: > > διεμερίσαντο τὰ ἱμάτιά μου ἑαυτοῖς καὶ ἐπὶ τὸν ἱματισμόν μου ἔβαλον κλῆρον (LXX) > > > John's citation is verbatim. The singular casting of a lot does not materially affect the fulfillment of the Psalm. It shows John is pointing the reader to the Greek text of the OT. The article of clothing which was preserved in one piece is specifically a tunic [[χιτών]](https://www.blueletterbible.org/lang/lexicon/lexicon.cfm?Strongs=G5509&t=KJV) which is found in some significant places. Two in particular: * This was the piece of clothing the LORD made for the first man and woman when they left the Garden of Eden (Genesis 3:21). + Just as the first man received a tunic from the LORD God; one of the Roman soldiers received a tunic from the Lord Jesus. * The garment for the High Priest (Exodus 28:4). + Jesus is the true High Priest (e.g. Hebrews 10:21) The emphasis on not tearing the garment invites a comparison to the clothing of the High Priest which is not supposed to be torn: > > The priest who is chief among his brothers, on whose head the anointing oil is poured and who has been consecrated to wear the garments, shall not let the hair of his head hang loose nor tear his clothes. (Leviticus 21:10 ESV) 1 > > > In particular, there is a connection to the High Priest is found on the Day of Atonement: > > He shall put on the holy linen coat and shall have the linen undergarment on his body, and he shall tie the linen sash around his waist, and wear the linen turban; these are the holy garments. He shall bathe his body in water and then put them on. (Leviticus 16:4 ESV) > > > καὶ **χιτῶνα** λινοῦν ἡγιασμένον ἐνδύσεται καὶ περισκελὲς λινοῦν ἔσται ἐπὶ τοῦ χρωτὸς αὐτοῦ καὶ ζώνῃ λινῇ ζώσεται καὶ κίδαριν λινῆν περιθήσεται ἱμάτια ἅγιά ἐστιν καὶ λούσεται ὕδατι πᾶν τὸ σῶμα αὐτοῦ καὶ ἐνδύσεται αὐτά (LXX) > > > The tunic is removed and left in the Holy Place: > > “Then Aaron shall come into the tent of meeting and shall take off the linen garments that he put on when he went into the Holy Place and shall leave them there. (Leviticus 16:23 ESV) > > > Therefore Mark and Matthew record the tearing of the Temple veil opening the entrance to the Most Holy Place and John presents Jesus as the High Priest, who is and makes the sacrifice and leaves His tunic outside the Most Holy Place. --- 1. The crown of thorns fulfills this requirement
Christ came in the fullness of time close to the 4,000 year mark after Adam. The fourth day is when the material universe (cosmos) came to be and light was divided from darkness. He took on the sin of the world and His garment was symbolically divided into four pieces (for the four corners of the world). The four gospels are given as witness to what Jesus did. And He will only return when the whole gospel is preached to the whole world. I believe that’s what the divided four pieces represent. The inner garment that was seamless probably represented His character as others have said but the hidden component, the Living Word, His divine person could not be divided. His body human - broken for the World, His divinity robed within experiencing everything firsthand.
27,095
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details: > > When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them, > and for my clothing they cast lots.” (John 19:23-24) > > > John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top." "From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit. Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
2017/02/20
[ "https://hermeneutics.stackexchange.com/questions/27095", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8450/" ]
John gives a more detailed description of this aspect of the crucifixion than either Mark or Mathew: > > And they crucify Him, and divide His garments among *themselves*, casting a lot for them *to decide* who should take what. (Mark 15:24 DLNT) > > > And having crucified Him, they divided His garments among *themselves*, casting a lot. > > (Matthew 27:35 DLNT) > > > Then the soldiers, when they crucified Jesus, took His garments and made four parts— a part *for* each soldier— and the tunic. Now the tunic was seamless, woven from the top through *the* whole. So they said to one another, “Let us not tear it, but let us cast-lots for it *to decide* whose it will be”— in order that the Scripture [in Ps 22:18] might be fulfilled, the *one* saying, “They divided My garments among themselves, and they cast a lot for My clothing”. So indeed, the soldiers did these *things*. (John 19:23-24 DLNT) > > > Writing after both Mark and Matthew, John completes the record of how the clothing of Jesus was divided. This account is purposeful to include three pieces of information: 1. The Old Testament passage fulfilled 2. The number of pieces of clothing (five) 3. Identifying the piece of clothing which was not torn (a tunic - χιτὼν) As noted by User34445 John makes the point that both aspects of Psalm 22:18 were fulfilled: the clothing was divided **and** lots were cast for the garments. In addition, there is a difference between the Masoretic Text (MT) and that John which cites: > > Psalm 22:18: > > They divide my clothes among themselves **casting lots** for my garments. (JPS Translation) > > They divided My garments among themselves, and they **cast a lot** for My clothing. (DLNT) > > > The Hebrew is plural (lots). John states a single lot was cast. This difference shows John has the Septuagint version of Psalm 22 in mind: > > John 19:23: > > διεμερίσαντο τὰ ἱμάτιά μου ἑαυτοῖς καὶ ἐπὶ τὸν ἱματισμόν μου ἔβαλον κλῆρον (NA28) > > > Psalm 22:18: > > διεμερίσαντο τὰ ἱμάτιά μου ἑαυτοῖς καὶ ἐπὶ τὸν ἱματισμόν μου ἔβαλον κλῆρον (LXX) > > > John's citation is verbatim. The singular casting of a lot does not materially affect the fulfillment of the Psalm. It shows John is pointing the reader to the Greek text of the OT. The article of clothing which was preserved in one piece is specifically a tunic [[χιτών]](https://www.blueletterbible.org/lang/lexicon/lexicon.cfm?Strongs=G5509&t=KJV) which is found in some significant places. Two in particular: * This was the piece of clothing the LORD made for the first man and woman when they left the Garden of Eden (Genesis 3:21). + Just as the first man received a tunic from the LORD God; one of the Roman soldiers received a tunic from the Lord Jesus. * The garment for the High Priest (Exodus 28:4). + Jesus is the true High Priest (e.g. Hebrews 10:21) The emphasis on not tearing the garment invites a comparison to the clothing of the High Priest which is not supposed to be torn: > > The priest who is chief among his brothers, on whose head the anointing oil is poured and who has been consecrated to wear the garments, shall not let the hair of his head hang loose nor tear his clothes. (Leviticus 21:10 ESV) 1 > > > In particular, there is a connection to the High Priest is found on the Day of Atonement: > > He shall put on the holy linen coat and shall have the linen undergarment on his body, and he shall tie the linen sash around his waist, and wear the linen turban; these are the holy garments. He shall bathe his body in water and then put them on. (Leviticus 16:4 ESV) > > > καὶ **χιτῶνα** λινοῦν ἡγιασμένον ἐνδύσεται καὶ περισκελὲς λινοῦν ἔσται ἐπὶ τοῦ χρωτὸς αὐτοῦ καὶ ζώνῃ λινῇ ζώσεται καὶ κίδαριν λινῆν περιθήσεται ἱμάτια ἅγιά ἐστιν καὶ λούσεται ὕδατι πᾶν τὸ σῶμα αὐτοῦ καὶ ἐνδύσεται αὐτά (LXX) > > > The tunic is removed and left in the Holy Place: > > “Then Aaron shall come into the tent of meeting and shall take off the linen garments that he put on when he went into the Holy Place and shall leave them there. (Leviticus 16:23 ESV) > > > Therefore Mark and Matthew record the tearing of the Temple veil opening the entrance to the Most Holy Place and John presents Jesus as the High Priest, who is and makes the sacrifice and leaves His tunic outside the Most Holy Place. --- 1. The crown of thorns fulfills this requirement
'**The tunic was seamless, woven in one piece from top to bottom**'. That's what "*sewn from the top*" means. It's a special type of weaving - something akin to seamless knitting (on circular needles) except through weaving. Weaving a seamless garment was a special skill, out of the ordinary and exceedingly rare - so quite valuable. This detail implies the garment was specially woven for Yehshua, perhaps even the product of a mother's hand, or possibly a close follower - like Mary Magdalene. > > Notice the prophecy in **Psalm 22:18** - ***They divide my clothes among them and cast lots for my garment***. > This prophesy contains two details: > > > * They divide my clothes among them; and > * {they} cast lots for my garment. > > > Why divide **AND** cast lots? > > > **ANSWER**: The detail contained in **Matthew 27:3** provides the answer to the riddle of **Psalm 22:18**. The clothes that could be divided were divided, yet one was seamless *sewn from the top* and quite valuable so sought after. Lots were drawn for the tunic because of its value. > > >
27,095
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details: > > When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them, > and for my clothing they cast lots.” (John 19:23-24) > > > John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top." "From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit. Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
2017/02/20
[ "https://hermeneutics.stackexchange.com/questions/27095", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8450/" ]
The clothing of Christ is symbolic of the Christian churches. The doctrine, ritual, liturgy etc. these are the outer coverings of God. They point us toward God. They are distinct from God in some ways yet are owned by Christ. The tunic represents the Holy apostolic church that will remain intact until the end of days. And the torn robe represents the various schisms and resulting denominations which all harbour various truths (yet not wholly intact). And so we can follow the path of truth toward the one true church of which to unite in worship of the risen Christ. We can subjectively and objectively find his tunic intact even today. The casting of lots means that it is God that chooses what truths he gives to what man. It is not man who chooses which truth he takes for himself. which points us back to the garden of eden where conversely it was man who chose the fruit of death. Christ crucified on the cross has become the tree of life. The temple veil being torn apart from the top signifies an act of God ending the old covenant. Mainly because Christ is the sacrificial lamb that takes on all the sins of the world, so that sacrifices at the temple are no longer needed.
Christ came in the fullness of time close to the 4,000 year mark after Adam. The fourth day is when the material universe (cosmos) came to be and light was divided from darkness. He took on the sin of the world and His garment was symbolically divided into four pieces (for the four corners of the world). The four gospels are given as witness to what Jesus did. And He will only return when the whole gospel is preached to the whole world. I believe that’s what the divided four pieces represent. The inner garment that was seamless probably represented His character as others have said but the hidden component, the Living Word, His divine person could not be divided. His body human - broken for the World, His divinity robed within experiencing everything firsthand.
27,095
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details: > > When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them, > and for my clothing they cast lots.” (John 19:23-24) > > > John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top." "From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit. Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
2017/02/20
[ "https://hermeneutics.stackexchange.com/questions/27095", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8450/" ]
The garment had no seams , representing there is no hole or crack in which to enter Heaven or be saved but only through Jesus Christ and his sacrifice and grace . When Jesus entered the throne to His Father He was given the garment of holiness and praise and we will also . Casting lots or trying to buy your way into salvation or enter through any other way besides the blood of Jesus will not save you ! Only through accepting His sacrifice and cleansing blood can we be saved
Christ came in the fullness of time close to the 4,000 year mark after Adam. The fourth day is when the material universe (cosmos) came to be and light was divided from darkness. He took on the sin of the world and His garment was symbolically divided into four pieces (for the four corners of the world). The four gospels are given as witness to what Jesus did. And He will only return when the whole gospel is preached to the whole world. I believe that’s what the divided four pieces represent. The inner garment that was seamless probably represented His character as others have said but the hidden component, the Living Word, His divine person could not be divided. His body human - broken for the World, His divinity robed within experiencing everything firsthand.
33,650,063
I need to combine two Bytes into one int value. I receive from my camera a 16bit Image were two successive bytes have the intensity value of one pixel. My goal is to combine these two bytes into one "int" vale. I manage to do this using the following code: ``` for (int i = 0; i < VectorLength * 2; i = i + 2) { NewImageVector[ImagePointer] = ((int)(buffer.Array[i + 1]) << 8) | ((int)(buffer.Array[i])); ImagePointer++; } ``` My image is 1280\*960 so VectorLength==1228800 and the incomming buffer size is 2\*1228800=2457600 elements... Is there any way that I can speed this up? Maybe there is another way so I don't need to use a for-loop. Thank you
2015/11/11
[ "https://Stackoverflow.com/questions/33650063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210481/" ]
You could use the equivalent to the union of c. Im not sure if faster, but more elegant: ``` [StructLayout(LayoutKind.Explicit)] struct byte_array { [FieldOffset(0)] public byte byte1; [FieldOffset(1)] public byte byte2; [FieldOffset(0)] public short int0; } ``` use it like this: ``` byte_array ba = new byte_array(); //insert the two bytes ba.byte1 = (byte)(buffer.Array[i]); ba.byte2 = (byte)(buffer.Array[i + 1]); //get the integer NewImageVector[ImagePointer] = ba.int1; ``` You can fill your two bytes and use the int. To find the faster way take the StopWatch-Class and compare the two ways like this: ``` Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); //The code stopWatch.Stop(); MessageBox.Show(stopWatch.ElapsedTicks.ToString()); //Or milliseconds ,... ```
You can achieve a small performance increase by using unsafe pointers to iterate the arrays. The following code assumes that `source` is the input byte array (`buffer.Array` in your case). It also assumes that `source` has an even number of elements. In production code you would obviously have to check these things. ``` int[] output = new int[source.Length / 2]; fixed (byte* pSource = source) fixed (int* pDestination = output) { byte* sourceIterator = pSource; int* destIterator = pDestination; for (int i = 0; i < output.Length; i++) { (*destIterator) = ((*sourceIterator) | (*(sourceIterator + 1) << 8)); destIterator++; sourceIterator += 2; } } return output; ```
33,650,063
I need to combine two Bytes into one int value. I receive from my camera a 16bit Image were two successive bytes have the intensity value of one pixel. My goal is to combine these two bytes into one "int" vale. I manage to do this using the following code: ``` for (int i = 0; i < VectorLength * 2; i = i + 2) { NewImageVector[ImagePointer] = ((int)(buffer.Array[i + 1]) << 8) | ((int)(buffer.Array[i])); ImagePointer++; } ``` My image is 1280\*960 so VectorLength==1228800 and the incomming buffer size is 2\*1228800=2457600 elements... Is there any way that I can speed this up? Maybe there is another way so I don't need to use a for-loop. Thank you
2015/11/11
[ "https://Stackoverflow.com/questions/33650063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210481/" ]
Assuming you can (re-)define `NewImageVector` as a `short[]`, and every two consecutive bytes in `Buffer` should be transformed into a `short` (which basically what you're doing now, only you cast to an `int` afterwards), you can use [Buffer.BlockCopy](https://msdn.microsoft.com/en-us/library/system.buffer.blockcopy(v=vs.110).aspx) to do it for you. As the documentation tells, you `Buffer.BlockCopy` copies bytes from one array to another, so in order to copy your bytes in buffer you need to do the following: ``` Buffer.BlockCopy(Buffer, 0, NewImageVector, 0, [NumberOfExpectedShorts] * 2) ``` This tells `BlockCopy` that you want to start copying bytes from `Buffer`, starting at index 0, to `NewImageVector` starting at index 0, and you want to copy `[NumberOfExpectedShorts] * 2` bytes (since every short is two bytes long). No loops, but it does depend on the ability of using a `short[]` array instead of an `int[]` array (and indeed, on using an array to begin with). Note that this also requires the bytes in `Buffer` to be in `little-endian` order (i.e. `Buffer[index]` contains the low byte, `buffer[index + 1]` the high byte).
You could use the equivalent to the union of c. Im not sure if faster, but more elegant: ``` [StructLayout(LayoutKind.Explicit)] struct byte_array { [FieldOffset(0)] public byte byte1; [FieldOffset(1)] public byte byte2; [FieldOffset(0)] public short int0; } ``` use it like this: ``` byte_array ba = new byte_array(); //insert the two bytes ba.byte1 = (byte)(buffer.Array[i]); ba.byte2 = (byte)(buffer.Array[i + 1]); //get the integer NewImageVector[ImagePointer] = ba.int1; ``` You can fill your two bytes and use the int. To find the faster way take the StopWatch-Class and compare the two ways like this: ``` Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); //The code stopWatch.Stop(); MessageBox.Show(stopWatch.ElapsedTicks.ToString()); //Or milliseconds ,... ```
33,650,063
I need to combine two Bytes into one int value. I receive from my camera a 16bit Image were two successive bytes have the intensity value of one pixel. My goal is to combine these two bytes into one "int" vale. I manage to do this using the following code: ``` for (int i = 0; i < VectorLength * 2; i = i + 2) { NewImageVector[ImagePointer] = ((int)(buffer.Array[i + 1]) << 8) | ((int)(buffer.Array[i])); ImagePointer++; } ``` My image is 1280\*960 so VectorLength==1228800 and the incomming buffer size is 2\*1228800=2457600 elements... Is there any way that I can speed this up? Maybe there is another way so I don't need to use a for-loop. Thank you
2015/11/11
[ "https://Stackoverflow.com/questions/33650063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210481/" ]
Assuming you can (re-)define `NewImageVector` as a `short[]`, and every two consecutive bytes in `Buffer` should be transformed into a `short` (which basically what you're doing now, only you cast to an `int` afterwards), you can use [Buffer.BlockCopy](https://msdn.microsoft.com/en-us/library/system.buffer.blockcopy(v=vs.110).aspx) to do it for you. As the documentation tells, you `Buffer.BlockCopy` copies bytes from one array to another, so in order to copy your bytes in buffer you need to do the following: ``` Buffer.BlockCopy(Buffer, 0, NewImageVector, 0, [NumberOfExpectedShorts] * 2) ``` This tells `BlockCopy` that you want to start copying bytes from `Buffer`, starting at index 0, to `NewImageVector` starting at index 0, and you want to copy `[NumberOfExpectedShorts] * 2` bytes (since every short is two bytes long). No loops, but it does depend on the ability of using a `short[]` array instead of an `int[]` array (and indeed, on using an array to begin with). Note that this also requires the bytes in `Buffer` to be in `little-endian` order (i.e. `Buffer[index]` contains the low byte, `buffer[index + 1]` the high byte).
You can achieve a small performance increase by using unsafe pointers to iterate the arrays. The following code assumes that `source` is the input byte array (`buffer.Array` in your case). It also assumes that `source` has an even number of elements. In production code you would obviously have to check these things. ``` int[] output = new int[source.Length / 2]; fixed (byte* pSource = source) fixed (int* pDestination = output) { byte* sourceIterator = pSource; int* destIterator = pDestination; for (int i = 0; i < output.Length; i++) { (*destIterator) = ((*sourceIterator) | (*(sourceIterator + 1) << 8)); destIterator++; sourceIterator += 2; } } return output; ```
431,943
So I find myself needing to apply global Moran's I across ~20 variables (as in ~20 instances of univariate autocorrelation for each variable, not attempted multivariate spatial autocorrelation). I'm using R and the sf + spdep packages. Where `data_lisa` is a sf object structured: ``` id | var_a | var_b | ... | var_n | geometry ``` ...and `lw` the spatial weights list created with: ``` lw <- nb2listw(neighbours = poly2nb(data_lisa, queen = TRUE), style = "W", zero.policy = TRUE) ``` Using spdep, I can apply global Moran's I for a single variable as: ``` moran.mc(data_lisa$var_a, listw = lw, nsim = 999, zero.policy = TRUE) ``` ...and receive all the expected results. So I'm looking for help in how to programmatically apply this function across all of my variables. The result of `moran.mc` is a list object which I suspect is where I'm encountering the greatest issues, as I don't have much experience interacting with lists. Ideally the output would look something like this. | variable | moran\_stat | pval | | --- | --- | --- | | var\_a | 0.064 | 0.042 | | var\_b | 0.322 | 0.001 | | var\_c | 0.183 | 0.001 | How can I do this?
2022/05/24
[ "https://gis.stackexchange.com/questions/431943", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/206106/" ]
Make a vector of your variable names either by subsetting the column names or programmatically, eg: ``` vars = names(data_lisa)[2:5] vars = paste0("var_",letters[1:4]) ``` For an example, I'm using the `COL.OLD` data you get from `?moran.mc` and this set of variables: ``` vars = c("AREA_PL","PERIMETER","CRIME","POLYID") ``` then repeat using `lapply` over the variable names, and give the returned list the names of the vars: ``` > mcs = lapply(vars, function(v){moran.mc(COL.OLD[[v]], listw=colw, nsim=10)}) > names(mcs) = vars ``` Then extract the statistic and p-value, making a data frame with the correct names: ``` > stats = data.frame( lapply(names(mcs), function(nm){ m=mcs[[nm]] setNames( list( stat=m$statistic, p=m$p.value ), paste0(nm,c("_s","_p")) ) } ) ) ``` Which produces: ``` > stats AREA_PL_s AREA_PL_p PERIMETER_s PERIMETER_p CRIME_s CRIME_p statistic 0.1404648 0.09090909 0.1741305 0.09090909 0.5109513 0.09090909 POLYID_s POLYID_p statistic 0.8701314 0.09090909 ``` I don't get how you want the output to be a table, since you only get one statistic per column, and not by `id` as implied in your sample table output. This is a global statistic. Note this only uses base R packages (plus `spdep`) so should work in any R installation.
As a possible alternative to the approach suggested by Spacedman I propose one based on `{dplyr}` and iterating via a for cycle over a vector of names of your variables of interest. As I don't have access to your `data_lisa` object I am using the well known & much loved North Carolina shapefile that ships with the `{sf}` package. What this piece of code does is that it calculates the Moran's statistic for each variable in the `variables` vector, and appends the value to the `results` tibble. I find it easier to work with denormalized (long) data, but if you prefer wide ones there is `{tidyr}` to the rescue. ``` library(sf) library(dplyr) library(spdep) # a shapefile shape <- st_read(system.file("shape/nc.shp", package="sf")) # list weight object lw <- nb2listw(neighbours = poly2nb(shape, queen = TRUE), style = "W", zero.policy = TRUE) # variable names to be investigated variables <- c("BIR74", "SID74", "NWBIR74") # initate empty resultset result <- tibble(NULL) # now let's iterate!! :) for (i in variables) { # calculate the moran's object (as list) res <- moran.mc(pull(shape, !!i), listw = lw, nsim = 999, zero.policy = TRUE) # use the res object to create a new row in results dataset result <- result %>% bind_rows(tibble(variable = i, statistic = res$statistic, pvalue = res$p.value)) } # check result result # A tibble: 3 × 3 variable statistic pvalue <chr> <dbl> <dbl> 1 BIR74 0.139 0.015 2 SID74 0.148 0.018 3 NWBIR74 0.180 0.004 ```
27,415,471
We are developing an app in Appcelerator Titanium and using PushWoosh to send notifications. We have tried with no success to send a notification that opens an specific page in the app. Think of an Inbox, where the user gets its messages, when a message is received, a notification shows up notifying the user on the new message, the user clicks it and opens the app on either the inbox or the message itself. The app includes other pages/features besides the Inbox, so far we can open the app after clicking but not the inbox or the message page. We have looked everywhere for information and we would appreciate it if you can point us to the right direction.
2014/12/11
[ "https://Stackoverflow.com/questions/27415471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2072962/" ]
``` ^(?!0?0\.00$)\d{1,2}\.\d{2}$ ``` You can simply use this.See demo. <https://regex101.com/r/qB0jV1/10>
I think you don't want to allow `0.00` or `00.00` ``` ^(?!00?\.00$)\d{1,2}(?:\.\d{2})?$ ``` OR ``` ^(?!00?\.00$)\d{1,2}(?:\.\d{1,2})?$ ``` [DEMO](https://regex101.com/r/qB0jV1/11) Negative lookahead at the start `(?!00?\.00$)` asserts that the number going to match wouldn't be `00.00` or `0.00`
27,415,471
We are developing an app in Appcelerator Titanium and using PushWoosh to send notifications. We have tried with no success to send a notification that opens an specific page in the app. Think of an Inbox, where the user gets its messages, when a message is received, a notification shows up notifying the user on the new message, the user clicks it and opens the app on either the inbox or the message itself. The app includes other pages/features besides the Inbox, so far we can open the app after clicking but not the inbox or the message page. We have looked everywhere for information and we would appreciate it if you can point us to the right direction.
2014/12/11
[ "https://Stackoverflow.com/questions/27415471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2072962/" ]
``` ^(?!0?0\.00$)\d{1,2}\.\d{2}$ ``` You can simply use this.See demo. <https://regex101.com/r/qB0jV1/10>
So why do you have to beat your self up with a complex regex. Why not a number comparison? ``` function validNum (num) { num = parserFloat(num); return num > 0 && num < 100; } ``` Want only two decimal places ? ``` function validNum (num) { num = parseFloat((num + "").replace(/^(.*\.\d\d)\d*$/, '$1')); return num > 0 && num < 100; } ``` [Test Here](http://jsfiddle.net/uxocgbqa/1/) ``` .5: true ..5 : false .005 : false 0.05 : true 99.99 : true 00.01 : true 00.00 : false 0.00 : false 00.0 : false 100.00 : false ```
27,415,471
We are developing an app in Appcelerator Titanium and using PushWoosh to send notifications. We have tried with no success to send a notification that opens an specific page in the app. Think of an Inbox, where the user gets its messages, when a message is received, a notification shows up notifying the user on the new message, the user clicks it and opens the app on either the inbox or the message itself. The app includes other pages/features besides the Inbox, so far we can open the app after clicking but not the inbox or the message page. We have looked everywhere for information and we would appreciate it if you can point us to the right direction.
2014/12/11
[ "https://Stackoverflow.com/questions/27415471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2072962/" ]
So why do you have to beat your self up with a complex regex. Why not a number comparison? ``` function validNum (num) { num = parserFloat(num); return num > 0 && num < 100; } ``` Want only two decimal places ? ``` function validNum (num) { num = parseFloat((num + "").replace(/^(.*\.\d\d)\d*$/, '$1')); return num > 0 && num < 100; } ``` [Test Here](http://jsfiddle.net/uxocgbqa/1/) ``` .5: true ..5 : false .005 : false 0.05 : true 99.99 : true 00.01 : true 00.00 : false 0.00 : false 00.0 : false 100.00 : false ```
I think you don't want to allow `0.00` or `00.00` ``` ^(?!00?\.00$)\d{1,2}(?:\.\d{2})?$ ``` OR ``` ^(?!00?\.00$)\d{1,2}(?:\.\d{1,2})?$ ``` [DEMO](https://regex101.com/r/qB0jV1/11) Negative lookahead at the start `(?!00?\.00$)` asserts that the number going to match wouldn't be `00.00` or `0.00`
53,896,970
I am getting coordinates with FusedLocationProviderClient in my application on a button click to store into a database. The issue is that when I reboot the phone or the emulator the `.getLastLocation()` is null and I have to click another time the button i order for this to work. Is there a way to force to get a current position if the value of `location from .lastKnownPosition()` is null? ``` // Google fused location client for GPS position private FusedLocationProviderClient flpc; // Vars to store GPS info public Double latitude, longitude; public Float accuracy; // Google Fused Client for location public void getLocation() { // FusedLocationProviderClient flpc = LocationServices.getFusedLocationProviderClient(context); if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ...... return; } // Get the latest position from device Task<Location> task = flpc.getLastLocation(); task.addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if(location!=null) { latitude = location.getLatitude(); longitude = location.getLongitude(); accuracy = location.getAccuracy(); } } }); } ``` In my button handler I call `getLocation()` and use latitude, longitude and accuracy to store to the database. Any help appreciated!
2018/12/22
[ "https://Stackoverflow.com/questions/53896970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975588/" ]
When getLastLocation() is null, you need to make a LocationRequest ``` private LocationRequest locationRequest; private LocationCallback locationCallback; ... locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(20 * 1000); locationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { if (locationResult == null) { return; } for (Location location : locationResult.getLocations()) { if (location != null) { wayLatitude = location.getLatitude(); wayLongitude = location.getLongitude(); txtLocation.setText(String.format(Locale.US, "%s -- %s", wayLatitude, wayLongitude)); } } } }; mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper()) ``` If you don't need continuous updates, you can remove the request once you've received it. ``` mFusedLocationClient.removeLocationUpdates(locationCallback); ``` More info here: <https://medium.com/@droidbyme/get-current-location-using-fusedlocationproviderclient-in-android-cb7ebf5ab88e>
When the phone is rebooted the cached last location is lost so if you didnt open up an app that uses GPS like google maps or something then there will be no last location. There never has to be a location returned to you, you should always assume it could be null. If you want to get location, you just need to use LocationCallback as @tenprint said in this thread. Refer this links [Android get location is null after phone reboot](https://stackoverflow.com/questions/28173322/android-get-location-is-null-after-phone-reboot)
6,275,356
I have an editable checkbox in my jQGrid with the values `editoptions: { value: "Yes:No" }` But whatever the value is i am getting back on controller string value "Yes:No", not single value "Yes" of "No", so i am getting it like that: When it is checked i am getting this: ``` form["MyCheckBox"] = "Yes:No". ``` When it is not checked i am getting this: ``` form["MyCheckBox"] = "No". ``` How can i do to make it work? Or is there any way to get bool values(true/false) instead of string values ? Need help
2011/06/08
[ "https://Stackoverflow.com/questions/6275356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735490/" ]
Try this: ``` editoptions: { value:"True:False" }, editable:true, edittype:'checkbox', formatter: "checkbox", formatoptions: {disabled : false} ```
It seems to me you describe the bug which is already fixed in the last version of jqGrid from GitHub. I recommend you to download the version from [here](https://github.com/tonytomov/jqGrid). See [here](http://www.trirand.com/jqgridwiki/doku.php?id=wiki%3ahow_to_install#development_installation) for the description of the order of the including of the jqGrid moduls.
8,673,684
I can't use boost::spirit in my environment. But I would like to use STL and boost as much as possible to build my own expression evaluator. Is there such an alternative to boost::spirit?
2011/12/29
[ "https://Stackoverflow.com/questions/8673684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/749973/" ]
The following code includes unit tests and a complete parser I wrote in an about 90 minute session at ACCU 200x (8 or 9). If you need more, it might be easy enough to extend. You can make it do doubles by defining `Parse::value_type`, or extracting it into a separate header file and make it a template class. Or you can take the test cases and try yourself. (it uses CUTE from <http://cute-test.com>) ``` #include "cute.h" #include "ide_listener.h" #include "cute_runner.h" #include <cctype> #include <map> namespace { class Parser { typedef int value_type; typedef std::vector<value_type> valuestack; typedef std::vector<char> opstack; typedef std::map<std::string,value_type> memory; public: memory variables; private: void evaluateSingleOperator(char op,value_type &result,value_type operand) { switch(op) { case '+': result += operand; break; case '-': result -= operand; break; case '*': result *= operand; break; case '/': result /= operand; break; default: throw("invalid operand"); } } void evaluateStacks(valuestack &values, opstack &ops) { while(ops.size() && values.size()>1) { char op = ops.back(); ops.pop_back(); value_type operand = values.back(); values.pop_back(); evaluateSingleOperator(op,values.back(),operand); } } bool higherPrecedenceOrLeftAssociative(char last, char current) { return (last == current)||(last == '*' || last == '/') ; } bool shouldEvaluate(char op,opstack const &ops) { return ops.size() > 0 && higherPrecedenceOrLeftAssociative(ops.back(),op); } std::string parseVariableName(std::istream &is) { std::string variable; char nextchar=0; while ((is >> nextchar) && isalpha(nextchar)) { variable += nextchar; } if (variable.size() == 0) throw std::string("internal parse error"); is.unget(); return variable; } int peekWithSkipWhiteSpace(std::istream &is) { int nextchar = EOF; while(isspace(nextchar = is.peek())) is.get(); return nextchar; } value_type getOperand(std::istream &is) { int nextchar = peekWithSkipWhiteSpace(is); if (nextchar == EOF) throw std::string("syntax error operand expected"); if (isdigit(nextchar)){ value_type operand=0; if (!(is >> operand)) throw std::string("syntax error getting number") ; return operand; } else if ('(' == nextchar) { is.get(); return parse(is); } else if (isalpha(nextchar)) { std::string variable= parseVariableName(is); if( parseAssignmentOperator(is)) { variables[variable] = parse(is); } else { if (!variables.count(variable)) throw std::string("undefined variable: ")+variable; } return variables[variable]; } throw std::string("syntax error"); } bool parseAssignmentOperator(std::istream &is) { int nextchar = peekWithSkipWhiteSpace(is); if ('=' != nextchar) { return false; } is.get(); return true; } public: value_type parse(std::istream &is) { is >> std::skipws; valuestack values; opstack ops; values.push_back(getOperand(is)); char op=')'; while((is >>op) && op != ')') { if (shouldEvaluate(op, ops)) { evaluateStacks(values, ops); } values.push_back(getOperand(is)); ops.push_back(op); } evaluateStacks(values,ops); return values.back(); } value_type eval(std::string s) { std::istringstream is(s); return parse(is); } }; int eval(std::string s) { return Parser().eval(s); } void shouldThrowEmptyExpression() { eval(""); } void shouldThrowSyntaxError() { eval("()"); } void testSimpleNumber() { ASSERT_EQUAL(5,eval("5")); } void testSimpleAdd() { ASSERT_EQUAL(10,eval("5 +5")); } void testMultiAdd() { ASSERT_EQUAL(10,eval("1 + 2 + 3+4")); } void testSimpleSubtract() { ASSERT_EQUAL(5,eval("6-1")); } void testTenPlus12Minus100() { ASSERT_EQUAL(-78,eval("10+12-100")); } void testMultiply() { ASSERT_EQUAL(50,eval("10*5")); } void testDivision() { ASSERT_EQUAL(7,eval("21/3")); } void testAddThenMultiply() { ASSERT_EQUAL(21,eval("1+4 *5")); } void testAddThenMultiplyAdd() { ASSERT_EQUAL(16,eval("1+4*5 -5")); } void testAddSubSub() { ASSERT_EQUAL(-4,eval("1+2-3-4")); } void testSimpleParenthesis() { ASSERT_EQUAL(1,eval("(1)")); } void testSimpleOperandParenthesis() { ASSERT_EQUAL(2,eval("1+(1)")); } void testParenthesis() { ASSERT_EQUAL(5,eval("2*(1+4)-5")); } void testNestedParenthesis() { ASSERT_EQUAL(16,eval("2*(1+(4*3)-5)")); } void testDeeplyNestedParenthesis() { ASSERT_EQUAL(8,eval("((2*((1+(4*3)-5)))/2)")); } void testSimpleAssignment() { Parser p; ASSERT_EQUAL(1, p.eval("a=1*(2-1)")); ASSERT_EQUAL(8, p.eval("a+7")); ASSERT_EQUAL(1, p.eval("2-a")); } void testLongerVariables() { Parser p; ASSERT_EQUAL(1, p.eval("aLongVariableName=1*(2-1)")); ASSERT_EQUAL(42, p.eval("AnotherVariable=7*(4+2)")); ASSERT_EQUAL(1, p.eval("2-(aLongVariableName*AnotherVariable)/42")); } void shouldThrowUndefined() { eval("2 * undefinedVariable"); } void runSuite(){ cute::suite s; //TODO add your test here s.push_back(CUTE_EXPECT(CUTE(shouldThrowEmptyExpression),std::string)); s.push_back(CUTE_EXPECT(CUTE(shouldThrowSyntaxError),std::string)); s.push_back(CUTE(testSimpleNumber)); s.push_back(CUTE(testSimpleAdd)); s.push_back(CUTE(testMultiAdd)); s.push_back(CUTE(testSimpleSubtract)); s.push_back(CUTE(testTenPlus12Minus100)); s.push_back(CUTE(testMultiply)); s.push_back(CUTE(testDivision)); s.push_back(CUTE(testAddThenMultiply)); s.push_back(CUTE(testAddSubSub)); s.push_back(CUTE(testAddThenMultiplyAdd)); s.push_back(CUTE(testSimpleParenthesis)); s.push_back(CUTE(testSimpleOperandParenthesis)); s.push_back(CUTE(testParenthesis)); s.push_back(CUTE(testNestedParenthesis)); s.push_back(CUTE(testDeeplyNestedParenthesis)); s.push_back(CUTE(testSimpleAssignment)); s.push_back(CUTE(testLongerVariables)); s.push_back(CUTE_EXPECT(CUTE(shouldThrowUndefined),std::string)); cute::ide_listener lis; cute::makeRunner(lis)(s, "The Suite"); } } int main(){ runSuite(); } ```
YACC++ is a very good tool for parser generator for c++ applications. ANTLR is also agood option howver that does not have good documentation for its usage in C/C++.
35,306
**tl;dr** Faculty don't think teaching is as important as their other responsibilities; how do we change that? **Long version** I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result. How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research? *Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
2015/01/06
[ "https://academia.stackexchange.com/questions/35306", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27290/" ]
Putting in place a better system for evaluating teaching than today's student evaluation forms would be a good start. Getting serious about the assessment of student learning outcomes (rather than simply assigning grades) would also be extremely helpful.
You don't hire people who don't take teaching seriously, and if you do happen to hire them accidentally, you deny them tenure and kick them out. More generally, you reward those who take teaching seriously and/or punish those who don't. This means you give the former time (by reducing the number of classes they have to teach), money (by paying them more, giving them department funds for research, whatever), and/or other perks (nice office, free parking pass, first dibs on teaching the particular classes they'd most like to teach, whatever), and you don't give those things to the latter.
35,306
**tl;dr** Faculty don't think teaching is as important as their other responsibilities; how do we change that? **Long version** I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result. How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research? *Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
2015/01/06
[ "https://academia.stackexchange.com/questions/35306", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27290/" ]
Putting in place a better system for evaluating teaching than today's student evaluation forms would be a good start. Getting serious about the assessment of student learning outcomes (rather than simply assigning grades) would also be extremely helpful.
The fundamental problem is that research and teaching are two *entirely* different skills. Imagine you're hiring a chef who is also expected to spend a third of his or her time waiting tables; the simple fact of reality is that specially talented individuals will rarely excel at both of these tasks. You can't *convince* a professor to be a better teacher than they are - most simply do not have the personality type, passion, inclination, or even inherent capacity to be excellent teachers. They haven't trained those skills nor have they required them to get to their current position in life. It isn't what they were hired for, it isn't what they are good at, and it isn't what they have spent their lives wanting and learning to do. Professors are hired to perform and manage research activities and are only incidentally required to also perform *custodial* teaching duties. They would likely also do a terrible job if you required them to pitch in cooking lunch in the cafeteria twice a week. At least in my part of the world, secondary school teachers are not even allowed to apply for a job without an appropriate degree in education. This is to say that, in addition to having the required qualifications in the subject that they are teaching they are also required to be qualified *teachers*. I see higher education eventually following a similar model - as teaching becomes more important, professorship *must* eventually branch into two or three largely separate streams. With specialization being so critical in almost every other professional activity it is almost unbelievable that professorship is such a haphazard occupation. While the training and demonstrated excellence for the position is almost entirely based on research and scientific acumen, professors are nevertheless required to also perform at least two entirely different functions - teaching and management. Surely some PhDs would love to only teach while others would love to devote entirely to research. Likewise, how many late-career professors could continue to produce invaluable research if not burdened by the need to both teach and project-manage a large research group; the very skill they excel at is squandered while their time is occupied performing things they are often neither good at nor that they enjoy. If you want good teachers, hire teachers to teach. If you want good researchers, hire researchers to research. If you want well managed research groups, hire managers to manage them. If you want chaos and headaches, pick some clever boffins and get them to juggle it all at once. Occasionally you will get lucky and find professors who are excellent researchers, excellent teachers, and excellent managers but, in my experience, these are very rare creatures indeed. Higher education would do well to reconsider its organizational hierarchy, I think.
35,306
**tl;dr** Faculty don't think teaching is as important as their other responsibilities; how do we change that? **Long version** I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result. How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research? *Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
2015/01/06
[ "https://academia.stackexchange.com/questions/35306", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27290/" ]
Putting in place a better system for evaluating teaching than today's student evaluation forms would be a good start. Getting serious about the assessment of student learning outcomes (rather than simply assigning grades) would also be extremely helpful.
**Step 0:** Talk to/with existing faculty. How do they view their teaching skill, it's relative importance, motivation to do better, what do they think would improve their own teaching and/or the teaching of others? I would hope the actual people on the ground know a thing or two more than some random fool on the internet (such as myself). **Step 0b:** Probably prioritize what people actually think at your institution over what I'll say below. Further, educated people are generally incredibly resistant to having random diktats imposed on them (and professors who are renowned for valuing their positions autonomy all the more so), so you'll need people to buy into things and embrace things. That takes some great implementation skill, diplomacy, and care - good advice followed poorly is rarely a boon. But with that said... **Step 1:** Clearly, effectively communicate what is valued in the department/institution - to existing faculty, students, prospective faculty, and the world at large. **Step 2:** Actually value those things - don't just pay them lip-service. Are meaningful teaching awards given? Are special posts/chairs given for teaching excellence, with funding and reduced other-than-teaching workloads optionally reduced? Can a person be a great teacher and a not-so-good researcher and expect to be respected and have job security comparable to a star researcher who can barely teach at all? Research/grants are often tied to equipment, labs, funding for students/assistants/projects - must teaching be solely it's own reward at your institution? **Step 3:** Measure what's important. Is a respected teaching-quality rating system in place to poll students before/during/after courses, program entrance/graduation, etc? How do you know who is doing a great job and who's doing a bad one? Do people even know if they are doing a good job? Does everyone else know who's doing great things? Is student success/learning solely the responsibility of individual faculty to determine and measure - as though assessment were somehow trivial and easy to do - and thus one class/semester/teacher cannot be meaningfully compared or evaluated? Tight feedback loops are necessary for flow experiences and improvement - tighten the loop. **Step 4:** Provide mechanisms for improvement. Feedback from students, constructive advice/encouragement/criticism from senior faculty - especially previously identified great teachers, funding for workshops/conferences specifically about education/pedagogy/teaching, bringing in outside faculty/speakers to speak and hold workshops, etc. Teaching is a skill, just like researching - it must be learned. As some people have very little teaching experience (sometimes having won fellowships that exempted them from teaching), it is generally unwise to just cross your fingers and pray people figure it out on their own. **Step 5:** At the end of a semester/year, appraise the situation. What is going well, and what isn't? Make a plan to do better next year, implement the plan, and follow up again next semester/year. Do it again. And again. And again. There are no real shortcuts, just consistent hard work performed by many, repeatedly, over a stretch of time. **Step 6:** Align decisions at ever greater (and lesser) levels to match what is truly valued. Student selection, graduate program admittance, postdoc positions, faculty hiring, tenure decisions - if teaching isn't important to the department/institution, it is strange to expect it to be treated as though it were actually important none the less. This doesn't necessarily have to mean everyone must be amazing teachers or else - just that it must be a factor that really does matter and holds value. **Warning:** *Anything that hints of punishment, job insecurity, lack of respect, or unpleasantness will lead to both intentional and unintentional gaming/sabotage/resistance to any process of improvement or assessment. Trust is valuable, hard to build, and incredibly easy to lose.* In the end, some people are naturally motivated and take it upon themselves to be better and better teachers. For those people you likely need only give them what they need and don't step on them or get in their way. But social systems are powerful, and can rob people of their desire and motivation just as they can encourage the better angels of our nature and inspire us. It must then be decided what system you have now, and what are you willing to and able to do about it?
35,306
**tl;dr** Faculty don't think teaching is as important as their other responsibilities; how do we change that? **Long version** I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result. How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research? *Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
2015/01/06
[ "https://academia.stackexchange.com/questions/35306", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27290/" ]
**Step 0:** Talk to/with existing faculty. How do they view their teaching skill, it's relative importance, motivation to do better, what do they think would improve their own teaching and/or the teaching of others? I would hope the actual people on the ground know a thing or two more than some random fool on the internet (such as myself). **Step 0b:** Probably prioritize what people actually think at your institution over what I'll say below. Further, educated people are generally incredibly resistant to having random diktats imposed on them (and professors who are renowned for valuing their positions autonomy all the more so), so you'll need people to buy into things and embrace things. That takes some great implementation skill, diplomacy, and care - good advice followed poorly is rarely a boon. But with that said... **Step 1:** Clearly, effectively communicate what is valued in the department/institution - to existing faculty, students, prospective faculty, and the world at large. **Step 2:** Actually value those things - don't just pay them lip-service. Are meaningful teaching awards given? Are special posts/chairs given for teaching excellence, with funding and reduced other-than-teaching workloads optionally reduced? Can a person be a great teacher and a not-so-good researcher and expect to be respected and have job security comparable to a star researcher who can barely teach at all? Research/grants are often tied to equipment, labs, funding for students/assistants/projects - must teaching be solely it's own reward at your institution? **Step 3:** Measure what's important. Is a respected teaching-quality rating system in place to poll students before/during/after courses, program entrance/graduation, etc? How do you know who is doing a great job and who's doing a bad one? Do people even know if they are doing a good job? Does everyone else know who's doing great things? Is student success/learning solely the responsibility of individual faculty to determine and measure - as though assessment were somehow trivial and easy to do - and thus one class/semester/teacher cannot be meaningfully compared or evaluated? Tight feedback loops are necessary for flow experiences and improvement - tighten the loop. **Step 4:** Provide mechanisms for improvement. Feedback from students, constructive advice/encouragement/criticism from senior faculty - especially previously identified great teachers, funding for workshops/conferences specifically about education/pedagogy/teaching, bringing in outside faculty/speakers to speak and hold workshops, etc. Teaching is a skill, just like researching - it must be learned. As some people have very little teaching experience (sometimes having won fellowships that exempted them from teaching), it is generally unwise to just cross your fingers and pray people figure it out on their own. **Step 5:** At the end of a semester/year, appraise the situation. What is going well, and what isn't? Make a plan to do better next year, implement the plan, and follow up again next semester/year. Do it again. And again. And again. There are no real shortcuts, just consistent hard work performed by many, repeatedly, over a stretch of time. **Step 6:** Align decisions at ever greater (and lesser) levels to match what is truly valued. Student selection, graduate program admittance, postdoc positions, faculty hiring, tenure decisions - if teaching isn't important to the department/institution, it is strange to expect it to be treated as though it were actually important none the less. This doesn't necessarily have to mean everyone must be amazing teachers or else - just that it must be a factor that really does matter and holds value. **Warning:** *Anything that hints of punishment, job insecurity, lack of respect, or unpleasantness will lead to both intentional and unintentional gaming/sabotage/resistance to any process of improvement or assessment. Trust is valuable, hard to build, and incredibly easy to lose.* In the end, some people are naturally motivated and take it upon themselves to be better and better teachers. For those people you likely need only give them what they need and don't step on them or get in their way. But social systems are powerful, and can rob people of their desire and motivation just as they can encourage the better angels of our nature and inspire us. It must then be decided what system you have now, and what are you willing to and able to do about it?
Much mention has been made of Reward for good teaching, but I would like to suggest an old fashioned and out-of-date idea: Punishment. If someone fails to deliver on their contracted responsibilities to the agreed quality and standards, then they need to face the consequences of their actions and decisions, resulting if necessary in formal disciplinary proceedings. It is not like their students are going to get another chance, so why should the teachers? However, this means taking responsibility for setting those standards and auditing progress to ensure that they are met, which is something most facilities seem reluctant to do.
35,306
**tl;dr** Faculty don't think teaching is as important as their other responsibilities; how do we change that? **Long version** I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result. How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research? *Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
2015/01/06
[ "https://academia.stackexchange.com/questions/35306", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27290/" ]
Putting in place a better system for evaluating teaching than today's student evaluation forms would be a good start. Getting serious about the assessment of student learning outcomes (rather than simply assigning grades) would also be extremely helpful.
Much mention has been made of Reward for good teaching, but I would like to suggest an old fashioned and out-of-date idea: Punishment. If someone fails to deliver on their contracted responsibilities to the agreed quality and standards, then they need to face the consequences of their actions and decisions, resulting if necessary in formal disciplinary proceedings. It is not like their students are going to get another chance, so why should the teachers? However, this means taking responsibility for setting those standards and auditing progress to ensure that they are met, which is something most facilities seem reluctant to do.
35,306
**tl;dr** Faculty don't think teaching is as important as their other responsibilities; how do we change that? **Long version** I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result. How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research? *Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
2015/01/06
[ "https://academia.stackexchange.com/questions/35306", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27290/" ]
The fundamental problem is that research and teaching are two *entirely* different skills. Imagine you're hiring a chef who is also expected to spend a third of his or her time waiting tables; the simple fact of reality is that specially talented individuals will rarely excel at both of these tasks. You can't *convince* a professor to be a better teacher than they are - most simply do not have the personality type, passion, inclination, or even inherent capacity to be excellent teachers. They haven't trained those skills nor have they required them to get to their current position in life. It isn't what they were hired for, it isn't what they are good at, and it isn't what they have spent their lives wanting and learning to do. Professors are hired to perform and manage research activities and are only incidentally required to also perform *custodial* teaching duties. They would likely also do a terrible job if you required them to pitch in cooking lunch in the cafeteria twice a week. At least in my part of the world, secondary school teachers are not even allowed to apply for a job without an appropriate degree in education. This is to say that, in addition to having the required qualifications in the subject that they are teaching they are also required to be qualified *teachers*. I see higher education eventually following a similar model - as teaching becomes more important, professorship *must* eventually branch into two or three largely separate streams. With specialization being so critical in almost every other professional activity it is almost unbelievable that professorship is such a haphazard occupation. While the training and demonstrated excellence for the position is almost entirely based on research and scientific acumen, professors are nevertheless required to also perform at least two entirely different functions - teaching and management. Surely some PhDs would love to only teach while others would love to devote entirely to research. Likewise, how many late-career professors could continue to produce invaluable research if not burdened by the need to both teach and project-manage a large research group; the very skill they excel at is squandered while their time is occupied performing things they are often neither good at nor that they enjoy. If you want good teachers, hire teachers to teach. If you want good researchers, hire researchers to research. If you want well managed research groups, hire managers to manage them. If you want chaos and headaches, pick some clever boffins and get them to juggle it all at once. Occasionally you will get lucky and find professors who are excellent researchers, excellent teachers, and excellent managers but, in my experience, these are very rare creatures indeed. Higher education would do well to reconsider its organizational hierarchy, I think.
Much mention has been made of Reward for good teaching, but I would like to suggest an old fashioned and out-of-date idea: Punishment. If someone fails to deliver on their contracted responsibilities to the agreed quality and standards, then they need to face the consequences of their actions and decisions, resulting if necessary in formal disciplinary proceedings. It is not like their students are going to get another chance, so why should the teachers? However, this means taking responsibility for setting those standards and auditing progress to ensure that they are met, which is something most facilities seem reluctant to do.
35,306
**tl;dr** Faculty don't think teaching is as important as their other responsibilities; how do we change that? **Long version** I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result. How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research? *Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
2015/01/06
[ "https://academia.stackexchange.com/questions/35306", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27290/" ]
The fundamental problem is that research and teaching are two *entirely* different skills. Imagine you're hiring a chef who is also expected to spend a third of his or her time waiting tables; the simple fact of reality is that specially talented individuals will rarely excel at both of these tasks. You can't *convince* a professor to be a better teacher than they are - most simply do not have the personality type, passion, inclination, or even inherent capacity to be excellent teachers. They haven't trained those skills nor have they required them to get to their current position in life. It isn't what they were hired for, it isn't what they are good at, and it isn't what they have spent their lives wanting and learning to do. Professors are hired to perform and manage research activities and are only incidentally required to also perform *custodial* teaching duties. They would likely also do a terrible job if you required them to pitch in cooking lunch in the cafeteria twice a week. At least in my part of the world, secondary school teachers are not even allowed to apply for a job without an appropriate degree in education. This is to say that, in addition to having the required qualifications in the subject that they are teaching they are also required to be qualified *teachers*. I see higher education eventually following a similar model - as teaching becomes more important, professorship *must* eventually branch into two or three largely separate streams. With specialization being so critical in almost every other professional activity it is almost unbelievable that professorship is such a haphazard occupation. While the training and demonstrated excellence for the position is almost entirely based on research and scientific acumen, professors are nevertheless required to also perform at least two entirely different functions - teaching and management. Surely some PhDs would love to only teach while others would love to devote entirely to research. Likewise, how many late-career professors could continue to produce invaluable research if not burdened by the need to both teach and project-manage a large research group; the very skill they excel at is squandered while their time is occupied performing things they are often neither good at nor that they enjoy. If you want good teachers, hire teachers to teach. If you want good researchers, hire researchers to research. If you want well managed research groups, hire managers to manage them. If you want chaos and headaches, pick some clever boffins and get them to juggle it all at once. Occasionally you will get lucky and find professors who are excellent researchers, excellent teachers, and excellent managers but, in my experience, these are very rare creatures indeed. Higher education would do well to reconsider its organizational hierarchy, I think.
In a nutshell: **Competition** between departments for students and funding can be one of the important reasons to cause departments to care about the quality of teaching. I give the following anecdote to illustrate the above principle. In my undergrad institution, which is outside the US and is fairly large (~30 K undergrads), the introductory math classes taken by engineering students were taught by professors in the math department. I had heard from people in the math department that some in the engineering department wanted to teach the classes themselves, so as to gain more funding and be able to hire more headcount (faculty). Because the math department did not want to lose this funding and headcount to the engineering department they sent their best teaching professors to teach the intro math courses. This allowed the math department to defend their position and say, "We're doing a good job teaching this course, as evidenced by good teaching evaluations, so why should you rock the boat?"
35,306
**tl;dr** Faculty don't think teaching is as important as their other responsibilities; how do we change that? **Long version** I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result. How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research? *Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
2015/01/06
[ "https://academia.stackexchange.com/questions/35306", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27290/" ]
Putting in place a better system for evaluating teaching than today's student evaluation forms would be a good start. Getting serious about the assessment of student learning outcomes (rather than simply assigning grades) would also be extremely helpful.
In a nutshell: **Competition** between departments for students and funding can be one of the important reasons to cause departments to care about the quality of teaching. I give the following anecdote to illustrate the above principle. In my undergrad institution, which is outside the US and is fairly large (~30 K undergrads), the introductory math classes taken by engineering students were taught by professors in the math department. I had heard from people in the math department that some in the engineering department wanted to teach the classes themselves, so as to gain more funding and be able to hire more headcount (faculty). Because the math department did not want to lose this funding and headcount to the engineering department they sent their best teaching professors to teach the intro math courses. This allowed the math department to defend their position and say, "We're doing a good job teaching this course, as evidenced by good teaching evaluations, so why should you rock the boat?"
35,306
**tl;dr** Faculty don't think teaching is as important as their other responsibilities; how do we change that? **Long version** I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result. How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research? *Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
2015/01/06
[ "https://academia.stackexchange.com/questions/35306", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27290/" ]
You don't hire people who don't take teaching seriously, and if you do happen to hire them accidentally, you deny them tenure and kick them out. More generally, you reward those who take teaching seriously and/or punish those who don't. This means you give the former time (by reducing the number of classes they have to teach), money (by paying them more, giving them department funds for research, whatever), and/or other perks (nice office, free parking pass, first dibs on teaching the particular classes they'd most like to teach, whatever), and you don't give those things to the latter.
Much mention has been made of Reward for good teaching, but I would like to suggest an old fashioned and out-of-date idea: Punishment. If someone fails to deliver on their contracted responsibilities to the agreed quality and standards, then they need to face the consequences of their actions and decisions, resulting if necessary in formal disciplinary proceedings. It is not like their students are going to get another chance, so why should the teachers? However, this means taking responsibility for setting those standards and auditing progress to ensure that they are met, which is something most facilities seem reluctant to do.
35,306
**tl;dr** Faculty don't think teaching is as important as their other responsibilities; how do we change that? **Long version** I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result. How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research? *Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
2015/01/06
[ "https://academia.stackexchange.com/questions/35306", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/27290/" ]
In a nutshell: **Competition** between departments for students and funding can be one of the important reasons to cause departments to care about the quality of teaching. I give the following anecdote to illustrate the above principle. In my undergrad institution, which is outside the US and is fairly large (~30 K undergrads), the introductory math classes taken by engineering students were taught by professors in the math department. I had heard from people in the math department that some in the engineering department wanted to teach the classes themselves, so as to gain more funding and be able to hire more headcount (faculty). Because the math department did not want to lose this funding and headcount to the engineering department they sent their best teaching professors to teach the intro math courses. This allowed the math department to defend their position and say, "We're doing a good job teaching this course, as evidenced by good teaching evaluations, so why should you rock the boat?"
Much mention has been made of Reward for good teaching, but I would like to suggest an old fashioned and out-of-date idea: Punishment. If someone fails to deliver on their contracted responsibilities to the agreed quality and standards, then they need to face the consequences of their actions and decisions, resulting if necessary in formal disciplinary proceedings. It is not like their students are going to get another chance, so why should the teachers? However, this means taking responsibility for setting those standards and auditing progress to ensure that they are met, which is something most facilities seem reluctant to do.
11,944,542
I want to know whether Perl is installed by default on all Unix-based operating systems. Since I want to write server-side programs, I need to choose between Perl and C.
2012/08/14
[ "https://Stackoverflow.com/questions/11944542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595858/" ]
I'm not sure whether Perl is standard on all Unix server installs. I'm not even sure what that means - a server is a piece of hardware, it doesn't have to come with *any* specific software (not even an OS). I don't think this should be the deciding factor anyway. You can always compile Perl, or distribute Perl with your program. The factors in choosing a language for your project are: 1) Which languages map well to the domain? Using C for a text processing program would be a mistake, this is where Perl and Python shine (perhaps Ruby also?). Using Perl for your hard real time embedded application would probably be a mistake. 2) What experience do the people on the team have? 3) What skills would you (or your company) like to develop? It might be okay to use a new language if this is something that will give you or your company an edge in the long run. The best example of this would be Ericsson switching to Erlang.
Most linux distros DO include it by default. However, we got a stack of AIX machines a few months back running AIX 7.1 and none of them have perl installed. The very, very broad answer is no, you cannot assume that every Linux or Unix system you buy will have Perl installed on it.
70,334,538
I was trying to implement (in C#8.0) a class with a generic type parameter (constraint to a delegate) having an event parameter with the same generic type. The intended purpose is to have some custom event handling (Subscribe & Unsubscribe functions) while still allowing any kind of delegate associated with it. ``` public class AEvent<T> where T : Delegate { private event T eventData; public AEvent() { } } ``` Starting out with the code above, the IDE gives me this error: > > 'eventData': event must be of a delegate type > > > Can someone explain briefly why can't I implement this? Or if there's any alternative way of achieving this?
2021/12/13
[ "https://Stackoverflow.com/questions/70334538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15331253/" ]
The C# specification *explicitly* states this is not allowed *(my bold)* [**Events**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#events) > > The type of an event declaration **must** be a *delegate\_type* .... > > > [**Delegates**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/delegates) > > The only way to declare a delegate type is via a *delegate\_declaration*. A delegate type is a class type that **is derived from** `System.Delegate`. *...snip...* **Note that `System.Delegate` is not itself a delegate type**; it is a class type from which all delegate types are derived. > > > As mentioned by others, it doesn't make a huge amount of sense to do this anyway. Whatever you do, and however you generify this, you have no way of specifying the *arity* (how many parameters to pass), so you would not be able to call it. Your best bet is to use `Action<T>` or `EventHandler<TEventArgs>`, that way you at least know the number of parameters, and can use generics for the rest.
How will you rise the event? You don't know if the delegate requires arguments and how many and of which type. I would use classes `AEvent`, `AEvent<T>`, `AEvent<T1,T2>` etc. and declare the events using `Action`, `Action<T>` and `Action<T1,T2>` respecitvely. ```cs public class AEvent { private event Action eventData; } public class AEvent<T> { private event Action<T> eventData; } public class AEvent<T1, T2> { private event Action<T1, T2> eventData; } ... ```
37,906
I viscerally hate low calorie sugar replacements - all of them, including Splenda (sucralose), except in one application. In my iced coffee I like sugar-free hazelnut syrup. The brand that I've been using is sweetened with Splenda (and sneakily, acesulfame potassium). It would be great except that it's very expensive. I spend $70/month just for that syrup. I have 50 grams of sucralose (that's enough to sweeten my coffee for years) which is the sweetener in Splenda. I also have hazelnut extract. I've made a "syrup" with water, sucralose and hazelnut extract and it turned out OK, but the coffee drink really lacks something without the syrupy quality of the commercial stuff. The ingredients on the label for the commercial syrup: Purified water, natural and artificial flavors, citric acid, acesulfame potassium, sodium benzoate and potassium sorbate (to preserve freshness), xanthan gum, sucralose (SPLENDA Brand), caramel color. I know that acesulfame potassium is a sweetener, Splenda generally contains maltodextrin and sucralose, but that doesn't seem to be the case here. There doesn't seem to be any maltodextrin in the product. Unless I'm missing something, that means that the commercial product gets its viscosity from an infinitesimal amount of xanthan gum. Could that be right? Of course I can get xanthan gum. Say I'm making 2 cups of syrup at a time, I add 1/8 tsp sucralose and two teaspoons of extract to 2 cups of boiling water (off heat). Now what?
2013/10/26
[ "https://cooking.stackexchange.com/questions/37906", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/20183/" ]
I don't have a good suggestion for what to use, but at least I can give you some info on xanthan. Yes, syrup can take viscosity from an infinitesmal amount of xanthan gum. If you add 0.5% to 1% of the fluid's weight in xanthan, you get a pudding consistency. For a syrup-like viscosity, you need much less. But xanthan is not a sugar, and does not make a syrupy consistency. It makes stuff gooey, not sticky. This may be enough for you, if all you need is some thickness, but the texture won't be the same as normal sugar syrup. I haven't tried commercial sugar-free syrup, so I can't make a comparison there. Xanthan has also the unfortunate tendency to reduce aroma, although it may not be a problem in the little amounts needed for syrup-like thickness.
Make it with xylitol as you would with sugar: 1 cup xylitol, 1/2 cup of water. I use tapioca starch to thicken it; the amount of tapioca depends on the quality.
23,043,005
*I have tried everything suggested here: [Status bar won't disappear](https://stackoverflow.com/questions/17763719/status-bar-wont-disappear) to no avail.* My iPhone version of my app has no status bar shown, but on my iPad, **which runs the scaled up version of my iPhone version,** there is a status bar that won't go away! If it makes a difference, my app uses the devices camera for a majority of the app. If you need more info/code, don't hesitate to ask! My app is iOS 7 only, and I use Xcode 5. Also, I would like the status bar gone in the whole app. **Do not suggest UIViewControllerBasedStatusBar in the plist-- it does not work.** --- **Related Articles** <https://stackoverflow.com/a/18740897/294884> <https://stackoverflow.com/a/21034908/294884> <https://stackoverflow.com/a/20307841/294884>
2014/04/13
[ "https://Stackoverflow.com/questions/23043005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3088956/" ]
For 2016 onwards all you do is: =============================== Add these two items to your plist: ================================== ``` <key>UIStatusBarHidden</key> <true/> <key>UIViewControllerBasedStatusBarAppearance</key> <false/> ``` 1. It is that simple ==================== 2. There is no other method. ============================ (Note - there's a (pointless) "hide status bar" checkbox in "general settings" "deployment info" section. This simply reads the plist file, it's a completely pointless checkbox.) --- Historic answers... =================== I've removed the historic answers as they are completely useless. (If any historians need to read it, click "edit history".)
Have you already, on your **info.plist** file, added two new attributes if not present? Please try setting "**Status bar is initially hidden**" to "`YES`" and also set "`UIViewControllerBasedStatusBarAppearance`" to "`NO`". This will hide status bar for your app.
33,370,883
I've read in various places that I can use Windows batch file `for` to grab the output of a command and put it in a variable, like this: ``` FOR /F %%G IN ('foo-command') DO SET FOO=%%G ``` Great. So my `foo-command` is actually `C:\Program Files\Foo\foo.bat`, and this is stored in the `FOO_BAT` variable. And it takes a parameter `bar` with value `blah blah='foobar' blah`. So I try that: ``` FOR /F %%G IN ('%FOO_BAT% -bar "blah blah='foobar' blah"') DO SET FOO=%%G ``` I get a lovely `'C:\Program' is not recognized...`. Nothing I can do can get around the space in the command. If you want to reproduce this, create a simple `C:\Program Files\Foo\foo.bat` file containing just the following, and then run the line above in a batch file. ``` echo FooBar ``` **How can I capture the output of a command (which takes parameters) as a Windows batch variable, if the command has spaces in its path?** * Yes, I've tried putting quotes around `%FOO_EXE%`. * Yes, I've tried putting everything in a separate variable and using that single variable in the `FOR`. * Please try this *with the parameters I supplied* before telling me it works. The presence of the parameters changes everything.
2015/10/27
[ "https://Stackoverflow.com/questions/33370883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/421049/" ]
``` FOR /F "delims=" %%G IN ('CALL "C:\path with spaces\foo.bat" "blah blah='foobar' blah"') do set foo=%%G ``` Give this a try. And yes I tested it. Foo.bat does nothing more then just echo %1.
Whenever you are trying to process output directly from a `FOR` loop, I would recommend including the `usebackq` parameter. This allows you to include quotes in your command (as is often needed) to specify full file paths or individual parameters which have spaces in them. For example: ``` REM Using the DIR command with FOR switches, extract the short name. REM The path specified below can be fed by a variable. FOR /F "usebackq tokens=*" %%G IN (`DIR "C:\Program Files\Foo\foo-command.exe" /B /S`) DO SET FooPathShortName=%%~sG ECHO Short Name is: %FooPathShortName% REM No quotes are needed to run the short name. FOR /F "usebackq" %%G IN (`%FooPathShortName% -bar "blah blah='foobar' blah"`) DO SET Foo=%%G ``` In the above, I am using the `DIR` command to output the full path of the target executable into a format which the `FOR` function can parse as a file. From this I am determining the short name of the file which does not require spaces to execute in the second `FOR` command.
212,823
Do we use cache memory in microcontrollers, if not, why not? If yes, what is its application in embedded systems or it is enough just to have RAM?
2016/01/22
[ "https://electronics.stackexchange.com/questions/212823", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/81163/" ]
Cache memory adds a level of latency unpredictability that may be unwanted. A lot (most?) of microcontrollers are used in a realtime setting where you have to budget for worst-case timing. It does not matter if your code is fast *on average*, if there is a chance that it won't meet the deadline in *worst case*. Worst case would be that your code or data is not in the cache, and since you have to budget for it anyway, the cache just adds extra cost and complexity. Some microcontrollers I have worked with has a small embedded SRAM that can be used as a "manual cache". You put stuff there that must have a low latency, be it code or data. Now, the term "microcontroller" is becoming more and more bloated. Is the 8-core ARM processor in your phone a microcontroller? If so, then yes, of course it should have a cache.
Having a level 1 cache is a trade-off between speed and cost. For speed, the bigger you make memory, the the longer the path to the data gets. That means that it'll take longer and longer (in terms of latency) the more memory you add. At some point performance degrades due this latency, which is the point when adding a level 1 cache makes sense. Cost is also a consideration, in that high-speed memory is more expensive than other types of memory. Finally, an additional benefit is that caches can make the micro-controller oblivious to the *kind* of memory it is read from. Micro-controllers have typically had small memories, and therefore they often have no level 1 cache. In a sense their whole memory could be considered a level 1 cache! However, many micro-controllers today are very capable and start crossing over into the micro-processor territory, with bigger memories and therefore also level-1 (and level-2) caches. Having caches adds a rather significant toll on the programming side, since real-time behavior on cache-misses can be hard to predict. Sometimes, this doesn't matter and/or can be worked around, but in the cases where it does there are a few options: * Use smaller micro controllers for specific sub-tasks in a larger system. * Use a chip that has embedded physical real-time units. The first solution is quite attractive, as micro-controllers are cheap and capable. However, communication between the controllers and the main (CPU) unit could become an issue. This is why chips with embedded real-time capabilities can be a better solution. As with all engineering, there are pros and cons for every solution. Pick the right tool for the job!
212,823
Do we use cache memory in microcontrollers, if not, why not? If yes, what is its application in embedded systems or it is enough just to have RAM?
2016/01/22
[ "https://electronics.stackexchange.com/questions/212823", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/81163/" ]
Cache memory adds a level of latency unpredictability that may be unwanted. A lot (most?) of microcontrollers are used in a realtime setting where you have to budget for worst-case timing. It does not matter if your code is fast *on average*, if there is a chance that it won't meet the deadline in *worst case*. Worst case would be that your code or data is not in the cache, and since you have to budget for it anyway, the cache just adds extra cost and complexity. Some microcontrollers I have worked with has a small embedded SRAM that can be used as a "manual cache". You put stuff there that must have a low latency, be it code or data. Now, the term "microcontroller" is becoming more and more bloated. Is the 8-core ARM processor in your phone a microcontroller? If so, then yes, of course it should have a cache.
Above a certain speed, fast memory costs more per byte than slow memory (below that speed, making memory slower won't make it any cheaper). If a system has a large amount of memory, having most of it be slow but then including a cache of fast memory and the logic to run it will be cheaper than making all of the memory fast. If the system doesn't run very fast, however, memory which can keep up with the system won't cost more than slower memory, so there's no reason not to have all the memory be fast enough to keep up with the system. If the system is fast but doesn't have much memory, the cost savings from making the bulk of the memory slow won't be sufficient to justify the cost of adding a cache. Many microcontrollers have a flash interface which can fetch multiple bytes at once into a buffer; while this might be viewed as a sort of cache, in many cases it won't be an addressable memory, since each bit of the buffer will only be able to take data from a single source [a bit line from the flash array].
212,823
Do we use cache memory in microcontrollers, if not, why not? If yes, what is its application in embedded systems or it is enough just to have RAM?
2016/01/22
[ "https://electronics.stackexchange.com/questions/212823", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/81163/" ]
Above a certain speed, fast memory costs more per byte than slow memory (below that speed, making memory slower won't make it any cheaper). If a system has a large amount of memory, having most of it be slow but then including a cache of fast memory and the logic to run it will be cheaper than making all of the memory fast. If the system doesn't run very fast, however, memory which can keep up with the system won't cost more than slower memory, so there's no reason not to have all the memory be fast enough to keep up with the system. If the system is fast but doesn't have much memory, the cost savings from making the bulk of the memory slow won't be sufficient to justify the cost of adding a cache. Many microcontrollers have a flash interface which can fetch multiple bytes at once into a buffer; while this might be viewed as a sort of cache, in many cases it won't be an addressable memory, since each bit of the buffer will only be able to take data from a single source [a bit line from the flash array].
Having a level 1 cache is a trade-off between speed and cost. For speed, the bigger you make memory, the the longer the path to the data gets. That means that it'll take longer and longer (in terms of latency) the more memory you add. At some point performance degrades due this latency, which is the point when adding a level 1 cache makes sense. Cost is also a consideration, in that high-speed memory is more expensive than other types of memory. Finally, an additional benefit is that caches can make the micro-controller oblivious to the *kind* of memory it is read from. Micro-controllers have typically had small memories, and therefore they often have no level 1 cache. In a sense their whole memory could be considered a level 1 cache! However, many micro-controllers today are very capable and start crossing over into the micro-processor territory, with bigger memories and therefore also level-1 (and level-2) caches. Having caches adds a rather significant toll on the programming side, since real-time behavior on cache-misses can be hard to predict. Sometimes, this doesn't matter and/or can be worked around, but in the cases where it does there are a few options: * Use smaller micro controllers for specific sub-tasks in a larger system. * Use a chip that has embedded physical real-time units. The first solution is quite attractive, as micro-controllers are cheap and capable. However, communication between the controllers and the main (CPU) unit could become an issue. This is why chips with embedded real-time capabilities can be a better solution. As with all engineering, there are pros and cons for every solution. Pick the right tool for the job!
6,128
Hello I have a website that I would like to keep online no matter what for that purpose I don't mind buying multiple webhosting packages. Its a small website in terms of size but not in terms of client access and employee email accounts. I would like to achieve the following: 1) Add the DNS records of these multiple providers to one domain name, so if the on providers servers go down it can automatically use the next appropriate server. 2) Emails can be replicated across all three servers, I don't mind purchasing webhosting accounts with the same contol panel if I have to achieve the same.
2010/12/01
[ "https://webmasters.stackexchange.com/questions/6128", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/1044/" ]
Assuming your site content is fairly static (not a shopping cart or similar) you can do this using your DNS server entries on the domain. You would purchase hosting from several providers (I'll use `acme.com` and `example.com` as the providers). Each provider should provide a list of the DNS servers to use while registering your domain. It may look something like this: 1. NS1.ACME.COM 2. NS2.ACME.COM 3. NS1.EXAMPLE.COM 4. NS2.EXAMPLE.COM You enter all 4 of these DNS servers in when you register your domain (or in the editing of your domain properties). As a result, if `acme.com`'s DNS servers go down, then `example.com`'s servers will take over. You would have to set up 2 accounts (one for each hosting company) for your email users, however. But this should be fairly transparent once it is set up. This is a DNS-level solution for your problem, but I think your problem is more complex than simple DNS tricks will solve for you.
As to email, look at moving them to Google Apps and Gmail. Very high uptime, always accessible via POP/IMAP, free, and large amount of storage. <http://www.google.com/apps/intl/en/group/index.html> All you have to do is point the DNS to Google server's (the set up process walks you through it).
26,256,447
I have successfuly searched my DB table for what i want and passed it into a DataTable (dt). The idea is that i want (after the search) to redirect someone to the result page he likes. So if he Searches for example "Michael" , i'd like to show him , the name Michael as a link , and if he presses it redirect him to his page, which is made by ~/Default.aspx?Email="+ id (id also results after the search and is casted to string). My Code: ``` protected void Button1_Click1(object sender, EventArgs e) { DataTable PassRecord = new DataTable(); String str = "select First_Name,Surname,id from ID where (First_Name like '%'+ @search +'%' ) OR (Surname like '%'+ @search +'%') OR (Email_Account like '%'+ @search +'%')"; SqlCommand Srch = new SqlCommand(str, con); Srch.Parameters.Add("@search", SqlDbType.NVarChar).Value = TextBox1.Text; con.Open(); Srch.ExecuteNonQuery(); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = Srch; DataTable dt = new DataTable(); DataSet ds = new DataSet(); da.Fill(dt); foreach (DataRow dr in dt.Rows) { var field = dr["First_Name"].ToString(); Response.Write(field); Response.Write("<br/>"); } ``` As u understand i want to create a link redirecting to the users profile after the search. Any help is appreciated, Thanks in Advance !!! Michael.
2014/10/08
[ "https://Stackoverflow.com/questions/26256447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4070124/" ]
The [sourceforge version](http://phpqrcode.sourceforge.net/docs/html/class_q_rcode.html#a1b90c0989105afa06b6e1c718a454fb5) of the method looks like the following: ``` static QRcode::png ( $text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint = false ) ``` and does not include any colours. You seem to be looking for the [**GitHub version instead**](https://github.com/t0k4rt/phpqrcode), that [defines the method](https://github.com/t0k4rt/phpqrcode/blob/master/phpqrcode.php#L3117-L3121) as the following: ``` public static function png( $text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false, $back_color = 0xFFFFFF, $fore_color = 0x000000 ) { ``` (*Psst, the article you read also mentions it: "Start by downloading the latest PHP QR Code library **from GitHub**", and it also includes a link to the [GitHub project](https://github.com/t0k4rt/phpqrcode)*)
In the `qrimage.php` file try to change `$col[0]` and `$col[1]` values and see the difference, good luck.
178,546
So far any search for Pogoplug security risk does not bring up anything alarming. Just wondering if anyone else has run across any mention of security issues with this device.
2010/08/21
[ "https://superuser.com/questions/178546", "https://superuser.com", "https://superuser.com/users/46807/" ]
Let's go down the stack and look at every aspect of its security. * **Remote Computer**: very easily compromised on an untrustworthy computer via a keylogger, so if you either a) only access your Pogoplug from your (trustworthy) computers, b) change your password often (i.e., at least once every 6 weeks), or c) use the very awesome [Keepass](http://keepass.info) 2.x that has a feature that scrambles then descrambles the password through simulated keystrokes, the clipboard and the arrow keys. * **Remote Computer's Internet-Your Pogoplug**: not as easily compromised because Pogoplug (if the reviews are correct) operates entirely under Secure Sockets (SSL), meaning any data between the remote computer and the pogoplug is encrypted with encryptions algorithms that only quantum computers can crack before the universe explodes. * **The Pogoplug**: There aren't any insomnia-worthy viruses or threats out there, since it runs ARM (only common in phones) and Linux. Unless somebody launches a DDoS attack on it (which, assuming your son isn't Osama bin Laden or targeted by 4chan) means that nobody will a) be able to get into it without the codes, or b) care. * **Your Son and His Friends**: This is the most important part because most modern schemes involve exploiting human psychology and inability to think reasonably when in immense stress. The worst thing that can feasibly happen is that your son accidentally changes the Pogoplug's privacy settings without knowing or forgetting to log out of a borrowed or public computer. **In Summary**: The Pogoplug itself isn't a security problem, the people who use it are. And for the same reason phishing schemes are so widespread nowadays. **Edit**: I should mention that when I was analyzing the security weakpoints, I was assuming that there's some superpowerful group of people after your son (e.g. the NSA, Al Qaeda). Otherwise the chances of people even trying the worst-case attacks I show here are nigh unlikely.
Nope! I have been hearing a lot about this device recently in the trade press and I haven't seen anything about security. That being said, no one can say any product is 100% secure, and the company does appear to be around for the long term, so I am sure they will patch any problems.
178,546
So far any search for Pogoplug security risk does not bring up anything alarming. Just wondering if anyone else has run across any mention of security issues with this device.
2010/08/21
[ "https://superuser.com/questions/178546", "https://superuser.com", "https://superuser.com/users/46807/" ]
The pogoplug essentially makes a connection to the manufacturer's server and provides content through it, at least in part. In my book that is a security concern, but for most people it is no more a threat than posting your pictures on facebook and only letting your friends see them is. You're trusting the manufacturer to actively protect your data though, rather than passively protect it by designing a good password authentication scheme (for example). This is based on what I've read about pogoplug which is very little recently, and a bit more, but a lot longer ago.
Nope! I have been hearing a lot about this device recently in the trade press and I haven't seen anything about security. That being said, no one can say any product is 100% secure, and the company does appear to be around for the long term, so I am sure they will patch any problems.