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
1,181,457
The lifetimes of batteries are independent exponential random variables , each having parameter $\lambda$. A flashlight needs two batteries to work. If one has a flashlight and a stockpile of n batteries, What is the distribution of time that the flashlight can operate? What I have so far: Let $Y$ be the lifetime of the flashlight; $Y\_1=min(X\_1,...,X\_n)$ where $X\_i$ is the lifetime of a battery ($1\le i\le n$), and $Y\_2$ the second smallest of the $X\_i$ (so $Y\_1\le Y\_2$) I wanted to compute: $P[Y\le t]=P[Y\_2\le k+m|Y\_1\le m]$ where $k+m=t$ then we have that $$P[Y\_2\le k+m|Y\_1\le m]={P[Y\_2\le k+m, Y\_1\le m]\over P[Y\_1\le m]}={P[Y\_2\le k+m] P[Y\_1\le m]\over P[Y\_1\le m]}=P[Y\_2\le k+m=t]$$ (because of the independence of the random variables) So $P[Y\_2\le t]=P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\le t]$ (assuming $X\_j=min(X\_1,...,X\_n)$) hence: $$P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\le t]= 1-P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\ge t]=1-P[X\_1\ge t,...,X\_{j-1}\ge t, X\_{j+1}\ge t,... X\_n\ge t]=1-e^{(n-1)\lambda t}$$ I would really appreciate if you can tell me if this is the correct approach :)
2015/03/08
[ "https://math.stackexchange.com/questions/1181457", "https://math.stackexchange.com", "https://math.stackexchange.com/users/128422/" ]
We are given $n$ batteries, and we put them two at a time in the flashlight. When one of the batteries fails, we swap it out and replace it with an unused one, if possible. The key here is that the battery that we did *not* swap out now behaves as a **completely new** battery. That's because the exponential distribution has the special property: given that a battery has survived to time $t$, the distribution of the *additional* time that it survives is **independent** of $t$. Hence, the lifetime of every pair of batteries follows the distribution of the minimum of two exponential random variables. The probability that the minimum is less than $a$ is given by $1 - \exp(-2\lambda a)$, hence the minimum is itself an exponential with parameter $2 \lambda$. Now since we swap out a battery exactly $n-1$ times, the total lifetime of the flashlight is the sum of $n-1$ independent, identically distributed exponentials of $2 \lambda$, [which is a Gamma distribution](https://en.wikipedia.org/wiki/Relationships_among_probability_distributions#Sum_of_variables) with parameters $n-1$ and $2 \lambda$. (This result can be seen easily by noting that the sum of two Gamma-distributed variables is also Gamma distributed, and the exponential is a special case of the Gamma).
This is not an answer, but will not fit in a comment. Given $n$ batteries with run times $x\_1,...,x\_n$ (unknown to the user), just computing the operating time is moderately complex. For example, suppose we have 3 batteries. One starts with batteries $1,2$, then replaces $1$ by $3$ if $x\_1<x\_2$ in which case the operating time is $T(x)= \min(x\_1+x\_3,x\_2)$ or replaces $2$ by $3$ if $x\_1 > x\_2$ in which case the operating time is $T(x)= \min(x\_1, x\_2+x\_3)$. We can ignore the $x\_1=x\_2$ case, in this context. So, using independence and symmetry, we have $F\_T(\alpha) = P\{x| T(x) \le \alpha \} = 2 P\{ x | x\_1 < x\_2 \text{ and } (x\_1+x\_3 \le \alpha \text{ or } x\_2 \le \alpha )\} $ Computing this, we have $F\_T(\alpha) = 2\int\_{x\_2=0}^\alpha \int\_{x\_1=0}^{x\_2} \int\_{x\_3=0}^\infty \phi +2\int\_{x\_2=\alpha}^\infty \int\_{x\_1=0}^{\alpha} \int\_{x\_3=0}^{\alpha-x\_1} \phi$, where $\phi(x) = \lambda^3 e^{-\lambda(x\_1+x\_2+x\_3)}$. Then $F\_T(\alpha) = 1- e^{-2 \alpha \lambda}(1+2 \alpha \lambda)$, for $\alpha \ge 0$. It doesn't get simpler when we add more batteries...
1,181,457
The lifetimes of batteries are independent exponential random variables , each having parameter $\lambda$. A flashlight needs two batteries to work. If one has a flashlight and a stockpile of n batteries, What is the distribution of time that the flashlight can operate? What I have so far: Let $Y$ be the lifetime of the flashlight; $Y\_1=min(X\_1,...,X\_n)$ where $X\_i$ is the lifetime of a battery ($1\le i\le n$), and $Y\_2$ the second smallest of the $X\_i$ (so $Y\_1\le Y\_2$) I wanted to compute: $P[Y\le t]=P[Y\_2\le k+m|Y\_1\le m]$ where $k+m=t$ then we have that $$P[Y\_2\le k+m|Y\_1\le m]={P[Y\_2\le k+m, Y\_1\le m]\over P[Y\_1\le m]}={P[Y\_2\le k+m] P[Y\_1\le m]\over P[Y\_1\le m]}=P[Y\_2\le k+m=t]$$ (because of the independence of the random variables) So $P[Y\_2\le t]=P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\le t]$ (assuming $X\_j=min(X\_1,...,X\_n)$) hence: $$P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\le t]= 1-P[min(X\_1,...,X\_{j-1},X\_{j+1},...X\_n)\ge t]=1-P[X\_1\ge t,...,X\_{j-1}\ge t, X\_{j+1}\ge t,... X\_n\ge t]=1-e^{(n-1)\lambda t}$$ I would really appreciate if you can tell me if this is the correct approach :)
2015/03/08
[ "https://math.stackexchange.com/questions/1181457", "https://math.stackexchange.com", "https://math.stackexchange.com/users/128422/" ]
**Second answer,** for a different interpretation: Batteries cannot die before they go into the flashlight. Because this interpretation involves both the minimum of two exponentials and the sum of several exponentials, it makes a more interesting problem than did the assumptions in my first answer. It is the interpretation suggested in Andre's note and used copper.hat's multiple integration. Step 1: Wait for one of two initial batteries to fail. This waiting time is the minimum of two exponentials with failure rate $\lambda$, and hence $X\_1$ ~ EXP($2\lambda$). Step 2: Throw out dead battery, replace with new one. By the no-memory property, the one of the two batteries in the flashlight that did not die is as good as new. Waiting time for one of these two batteries to die is again $X\_2$ ~ EXP($2\lambda$). Last step $n-1$; Throw out dead battery, replace with $n$th (last remaining replacement) battery: Light goes out after additional time $X\_{n-1}$ ~ EXP($2\lambda$). Total time flashlight is lit is $T = X\_1 + \dots + X\_{n-1}$. This is the sum of $(n-1)$ exponentials, so $T$ ~ GAMMA($n-1,$ $2\lambda$). This is a gamma distribution with shape parameter $n-1$ and rate parameter $2\lambda.$ When the shape parameter is a positive integer the gamma distribution is sometimes called an Erlang distribution (especially in queueing theory). *Check:* A previous answer, apparently using the same assumptions and with $n=3,$ has the CDF of the random variable $T$ as $F\_T(x) = 1 - \exp(-2\lambda x)(1 + 2\lambda x),$ for $x > 0$. The form of the CDF does indeed get messier with increasing $n$, but the mean and variance are simple expressions in $n$ and $\lambda.$ In R, we easily verify (in one instance, anyhow) that this is a special case of the gamma (Erlang) distribution. Let $n = 3$, $\lambda = 1/15$, and $x = 1$. So this is the (small) probability that the flashlight goes dark by time 1. The code 'pgamma(1, 2, 2/15)' and the code '1 - exp(-2/15)\*(1 + 2/15)' both return the probability 0.008136905. Also, 'qgamma(.5, 2, 2/15)' finds the exact median time the flaslhight burns to be 12.58760, and 'mean(rgamma(10^5, 2, 2/15))' approximates the mean as 14.97 (exact is 15).
We are given $n$ batteries, and we put them two at a time in the flashlight. When one of the batteries fails, we swap it out and replace it with an unused one, if possible. The key here is that the battery that we did *not* swap out now behaves as a **completely new** battery. That's because the exponential distribution has the special property: given that a battery has survived to time $t$, the distribution of the *additional* time that it survives is **independent** of $t$. Hence, the lifetime of every pair of batteries follows the distribution of the minimum of two exponential random variables. The probability that the minimum is less than $a$ is given by $1 - \exp(-2\lambda a)$, hence the minimum is itself an exponential with parameter $2 \lambda$. Now since we swap out a battery exactly $n-1$ times, the total lifetime of the flashlight is the sum of $n-1$ independent, identically distributed exponentials of $2 \lambda$, [which is a Gamma distribution](https://en.wikipedia.org/wiki/Relationships_among_probability_distributions#Sum_of_variables) with parameters $n-1$ and $2 \lambda$. (This result can be seen easily by noting that the sum of two Gamma-distributed variables is also Gamma distributed, and the exponential is a special case of the Gamma).
223
Magento offers support for different database back-end. I wonder which one of the OpenSource DB Backend (like MySQL or MariaDB ...) has better performance with Magento architecture. I know that Magento workload is more cpu/cache oriented however it still has 250+ tables and an EAV model.
2013/01/25
[ "https://magento.stackexchange.com/questions/223", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/70/" ]
As said Benmarks, it depends on your hardware environment. But, if you are looking alternate open source solution instead of MySQL, you should look definitely "Percona DB". It's MySQL based but has many performance counters available in the package. Also, they have a blog where they regularly sharing their experince about performance metrics. [Percona DB](http://www.percona.com/)
An apples-to-apples comparison using identical hardware for each backend may be unlikely and likely inapplicable. I believe the answer will be "it depends": it depends on the rest of the business' operating environment and the available hardware and infrastructure. On the one hand there is the efficiency of non-Magento processes which may be affected (or effected) by choice of backend, such as a warehouse management system running atop Oracle. There's also the effect of developer knowledge/proficiency with one backend vs another.
223
Magento offers support for different database back-end. I wonder which one of the OpenSource DB Backend (like MySQL or MariaDB ...) has better performance with Magento architecture. I know that Magento workload is more cpu/cache oriented however it still has 250+ tables and an EAV model.
2013/01/25
[ "https://magento.stackexchange.com/questions/223", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/70/" ]
As said Benmarks, it depends on your hardware environment. But, if you are looking alternate open source solution instead of MySQL, you should look definitely "Percona DB". It's MySQL based but has many performance counters available in the package. Also, they have a blog where they regularly sharing their experince about performance metrics. [Percona DB](http://www.percona.com/)
I've not been able to find enough data on the performance difference between MySQL and MariaDB, however I've seen people opting for Percona MySQL, mainly for its hot backup feature, and also Percona's InnoDB is supposed to be better than the one in MySQL. Here is a post on Percona's performance improvements <http://www.mysqlperformanceblog.com/2009/07/14/performance-improvements-in-percona-5-0-83-and-xtradb/>
13,346,620
In order to create a font picker I need to get the list of fonts available to Firemonkey. As Screen.Fonts doesn't exist in FireMonkey I thought I'd need to use FMX.Platform ? eg: ``` if TPlatformServices.Current.SupportsPlatformService(IFMXSystemFontService, IInterface(FontSvc)) then begin edit1.Text:= FontSvc.GetDefaultFontFamilyName; end else edit1.Text:= DefaultFontFamily; ``` However, the only function available is to return the default Font name. At the moment I'm not bothered about cross-platform support but if I'm going to move to Firemonkey I'd rather not rely on Windows calls where possible.
2012/11/12
[ "https://Stackoverflow.com/questions/13346620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/575511/" ]
The cross platform solution should use the MacApi.AppKit and Windows.Winapi together in conditional defines. First Add these code to your uses clause: ``` {$IFDEF MACOS} MacApi.Appkit,Macapi.CoreFoundation, Macapi.Foundation, {$ENDIF} {$IFDEF MSWINDOWS} Winapi.Messages, Winapi.Windows, {$ENDIF} ``` Then add this code to your implementation: ``` {$IFDEF MSWINDOWS} function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric; FontType: Integer; Data: Pointer): Integer; stdcall; var S: TStrings; Temp: string; begin S := TStrings(Data); Temp := LogFont.lfFaceName; if (S.Count = 0) or (AnsiCompareText(S[S.Count-1], Temp) <> 0) then S.Add(Temp); Result := 1; end; {$ENDIF} procedure CollectFonts(FontList: TStringList); var {$IFDEF MACOS} fManager: NsFontManager; list:NSArray; lItem:NSString; {$ENDIF} {$IFDEF MSWINDOWS} DC: HDC; LFont: TLogFont; {$ENDIF} i: Integer; begin {$IFDEF MACOS} fManager := TNsFontManager.Wrap(TNsFontManager.OCClass.sharedFontManager); list := fManager.availableFontFamilies; if (List <> nil) and (List.count > 0) then begin for i := 0 to List.Count-1 do begin lItem := TNSString.Wrap(List.objectAtIndex(i)); FontList.Add(String(lItem.UTF8String)) end; end; {$ENDIF} {$IFDEF MSWINDOWS} DC := GetDC(0); FillChar(LFont, sizeof(LFont), 0); LFont.lfCharset := DEFAULT_CHARSET; EnumFontFamiliesEx(DC, LFont, @EnumFontsProc, Winapi.Windows.LPARAM(FontList), 0); ReleaseDC(0, DC); {$ENDIF} end; ``` Now you can use CollectFonts procedure. Don't forget to pass a non-nil TStringlist to the procedure.A typical usage may be like this. ``` procedure TForm1.FormCreate(Sender: TObject); var fList: TStringList; i: Integer; begin fList := TStringList.Create; CollectFonts(fList); for i := 0 to fList.Count -1 do begin ListBox1.Items.Add(FList[i]); end; fList.Free; end; ```
I've used the following solution: ``` Printer.ActivePrinter; memo1.lines.AddStrings(Printer.Fonts); ``` declaring FMX.Printer in the uses.
13,346,620
In order to create a font picker I need to get the list of fonts available to Firemonkey. As Screen.Fonts doesn't exist in FireMonkey I thought I'd need to use FMX.Platform ? eg: ``` if TPlatformServices.Current.SupportsPlatformService(IFMXSystemFontService, IInterface(FontSvc)) then begin edit1.Text:= FontSvc.GetDefaultFontFamilyName; end else edit1.Text:= DefaultFontFamily; ``` However, the only function available is to return the default Font name. At the moment I'm not bothered about cross-platform support but if I'm going to move to Firemonkey I'd rather not rely on Windows calls where possible.
2012/11/12
[ "https://Stackoverflow.com/questions/13346620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/575511/" ]
The cross platform solution should use the MacApi.AppKit and Windows.Winapi together in conditional defines. First Add these code to your uses clause: ``` {$IFDEF MACOS} MacApi.Appkit,Macapi.CoreFoundation, Macapi.Foundation, {$ENDIF} {$IFDEF MSWINDOWS} Winapi.Messages, Winapi.Windows, {$ENDIF} ``` Then add this code to your implementation: ``` {$IFDEF MSWINDOWS} function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric; FontType: Integer; Data: Pointer): Integer; stdcall; var S: TStrings; Temp: string; begin S := TStrings(Data); Temp := LogFont.lfFaceName; if (S.Count = 0) or (AnsiCompareText(S[S.Count-1], Temp) <> 0) then S.Add(Temp); Result := 1; end; {$ENDIF} procedure CollectFonts(FontList: TStringList); var {$IFDEF MACOS} fManager: NsFontManager; list:NSArray; lItem:NSString; {$ENDIF} {$IFDEF MSWINDOWS} DC: HDC; LFont: TLogFont; {$ENDIF} i: Integer; begin {$IFDEF MACOS} fManager := TNsFontManager.Wrap(TNsFontManager.OCClass.sharedFontManager); list := fManager.availableFontFamilies; if (List <> nil) and (List.count > 0) then begin for i := 0 to List.Count-1 do begin lItem := TNSString.Wrap(List.objectAtIndex(i)); FontList.Add(String(lItem.UTF8String)) end; end; {$ENDIF} {$IFDEF MSWINDOWS} DC := GetDC(0); FillChar(LFont, sizeof(LFont), 0); LFont.lfCharset := DEFAULT_CHARSET; EnumFontFamiliesEx(DC, LFont, @EnumFontsProc, Winapi.Windows.LPARAM(FontList), 0); ReleaseDC(0, DC); {$ENDIF} end; ``` Now you can use CollectFonts procedure. Don't forget to pass a non-nil TStringlist to the procedure.A typical usage may be like this. ``` procedure TForm1.FormCreate(Sender: TObject); var fList: TStringList; i: Integer; begin fList := TStringList.Create; CollectFonts(fList); for i := 0 to fList.Count -1 do begin ListBox1.Items.Add(FList[i]); end; fList.Free; end; ```
``` unit Unit1; interface uses Windows, SysUtils, Classes, Forms, Controls, StdCtrls; type TForm1 = class(TForm) ComboBox1: TComboBox; procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormShow(Sender: TObject); begin ComboBox1.Items.Assign(Screen.Fonts); ComboBox1.Text := 'Fonts...'; end; end. ```
13,346,620
In order to create a font picker I need to get the list of fonts available to Firemonkey. As Screen.Fonts doesn't exist in FireMonkey I thought I'd need to use FMX.Platform ? eg: ``` if TPlatformServices.Current.SupportsPlatformService(IFMXSystemFontService, IInterface(FontSvc)) then begin edit1.Text:= FontSvc.GetDefaultFontFamilyName; end else edit1.Text:= DefaultFontFamily; ``` However, the only function available is to return the default Font name. At the moment I'm not bothered about cross-platform support but if I'm going to move to Firemonkey I'd rather not rely on Windows calls where possible.
2012/11/12
[ "https://Stackoverflow.com/questions/13346620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/575511/" ]
I've used the following solution: ``` Printer.ActivePrinter; memo1.lines.AddStrings(Printer.Fonts); ``` declaring FMX.Printer in the uses.
``` unit Unit1; interface uses Windows, SysUtils, Classes, Forms, Controls, StdCtrls; type TForm1 = class(TForm) ComboBox1: TComboBox; procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormShow(Sender: TObject); begin ComboBox1.Items.Assign(Screen.Fonts); ComboBox1.Text := 'Fonts...'; end; end. ```
63,068,079
I want to initialize a array of 1 million objects on stack, I need to write one million &i in the following code. Is there any other good way. ```cpp #include <iostream> class A{ public: A(int* p) : p_(p){ std::cout << "A" << std::endl; } private: int *p_; }; int main(){ int i; A a[3] = {&i, &i, &i}; } ```
2020/07/24
[ "https://Stackoverflow.com/questions/63068079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10825418/" ]
C++ new operator can be used to call constructor on a preallocated memory: ``` #include <iostream> #include <cstddef> #include <cstdint> class A{ public: A(int* p) : p_(p){ std::cout << "A" << std::endl; } private: int *p_; }; int main(){ int i; uint8_t buf[1000000 * sizeof(A)]; A* pa = reinterpret_cast<A*>(buf); for (size_t n = 0; n < 1000000; n++) { new (&pa[n]) A(&i); } return 0; } ```
You could use `std::vector` and initialize is with a million elements ``` std::vector<A> a(1000000, &i); ```
63,068,079
I want to initialize a array of 1 million objects on stack, I need to write one million &i in the following code. Is there any other good way. ```cpp #include <iostream> class A{ public: A(int* p) : p_(p){ std::cout << "A" << std::endl; } private: int *p_; }; int main(){ int i; A a[3] = {&i, &i, &i}; } ```
2020/07/24
[ "https://Stackoverflow.com/questions/63068079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10825418/" ]
``` #include <iostream> #include <type_traits> class A{ public: A(int* p) : p_(p){ std::cout << "A" << std::endl; } private: int *p_; }; int main(){ using elemType = std::aligned_storage<sizeof(A), alignof(A)>::type; const size_t count = 1000000; int i; elemType a[count]; for(int idx = 0; idx < count: ++idx) { new (&a[idx]) A(&i); } ... for(int idx = 0; idx < count: ++idx) { reinterpret_cast<A&>(a[idx]).~A(); } return 0; } ```
You could use `std::vector` and initialize is with a million elements ``` std::vector<A> a(1000000, &i); ```
63,068,079
I want to initialize a array of 1 million objects on stack, I need to write one million &i in the following code. Is there any other good way. ```cpp #include <iostream> class A{ public: A(int* p) : p_(p){ std::cout << "A" << std::endl; } private: int *p_; }; int main(){ int i; A a[3] = {&i, &i, &i}; } ```
2020/07/24
[ "https://Stackoverflow.com/questions/63068079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10825418/" ]
``` #include <iostream> #include <type_traits> class A{ public: A(int* p) : p_(p){ std::cout << "A" << std::endl; } private: int *p_; }; int main(){ using elemType = std::aligned_storage<sizeof(A), alignof(A)>::type; const size_t count = 1000000; int i; elemType a[count]; for(int idx = 0; idx < count: ++idx) { new (&a[idx]) A(&i); } ... for(int idx = 0; idx < count: ++idx) { reinterpret_cast<A&>(a[idx]).~A(); } return 0; } ```
C++ new operator can be used to call constructor on a preallocated memory: ``` #include <iostream> #include <cstddef> #include <cstdint> class A{ public: A(int* p) : p_(p){ std::cout << "A" << std::endl; } private: int *p_; }; int main(){ int i; uint8_t buf[1000000 * sizeof(A)]; A* pa = reinterpret_cast<A*>(buf); for (size_t n = 0; n < 1000000; n++) { new (&pa[n]) A(&i); } return 0; } ```
74,423,308
I take it from the database and send it via ajax (wordpress). Everything works fine, except that I don't get the **first row** from the database. As I read on the Internet, a similar problem is in the array, maybe. Can someone explain and help me fix it so that all rows are displayed? Code: ``` $sql = $wpdb->prepare( "SELECT * FROM users" ); $count = 0; $user_object = array(); foreach( $wpdb->get_results( $sql ) as $key => $row ) { $user_id = $row->user_ID; $user_name = $row->user_name; $user_object[$count]= array( "user_ID"=>$user_id, "user_name"=>$user_name, ); $count++; } return wp_send_json( $user_object ); ```
2022/11/13
[ "https://Stackoverflow.com/questions/74423308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11593555/" ]
You don't need to loop your results at all, your code can be simplified further. * There are no placeholders to bind variables to, so there is no need to use `prepare()`. * There is no need to loop and manually set the indexes on the first level or the associative keys on the second level because `get_results()` with `ARRAY_A` will already do this for you. Code: ``` return wp_send_json($wpdb->get_results('SELECT * FROM users', ARRAY_A)); ``` See: <https://developer.wordpress.org/reference/classes/wpdb/get_results/> --- When you want to add PHP variables to your SQL, then using a prepared statement is appropriate. For example: [WordPress prepared statement with IN() condition](https://stackoverflow.com/a/68817629/2943403)
WordPress database tables always use prefix so you have to include prefix using `$wpdb->prefix.'users'` Or if you are trying to get WordPress core users then you can use `$wpdb->users` to get the table name with prefix. Reference: <https://developer.wordpress.org/reference/classes/wpdb/>. You can use `ARRAY_A` for second output parameter of `get_results()` so you don't have to loop through results. Reference: <https://developer.wordpress.org/reference/classes/wpdb/get_results/>. Code: ``` global $wpdb; $sql = $wpdb->prepare( "SELECT * FROM {$wpdb->users}" ); return wp_send_json($wpdb->get_results($sql, ARRAY_A)); ``` Or alternative there is another way to getting users in WordPress using `get_users()`. Reference: <https://developer.wordpress.org/reference/functions/get_users/>
33,158,331
I have a query in Oracle SQL that displays results as follows: **SQL:** ``` select uuid, name, to_char(from_tz(startdate, 'UTC') at time zone 'America/New_York', 'yyyy-mm-dd hh24:mi:ss') as startdate_et, to_char(from_tz(enddate, 'UTC') at time zone 'America/New_York', 'yyyy-mm-dd hh24:mi:ss') as enddate_et, (enddate - startdate) as executiontime from process where name = (select name from jobconfiguration where currentprocessid = 'bGd_AAABNaMAAAFQHvY0UyTa'); ``` **Output:** [![enter image description here](https://i.stack.imgur.com/dwZ1K.png)](https://i.stack.imgur.com/dwZ1K.png) The problem here is the data in the `executiontime` column. The milliseconds value is too long and also I would like to remove the `+00` from the beginning and trim the `02.951000` to `02.95` and `03.284000` to `03.28`. Please guide.
2015/10/15
[ "https://Stackoverflow.com/questions/33158331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325154/" ]
No, the `file` input can't be prepopulated by Laravel or by any software. Your website (and any website) doesn't and shouldn't know the local path to the file. Imagine the security risks if they did! You could trick a user into uploading their SSH private key or something. What you need to do is process the uploaded file regardless, even if there are validation errors. Then you could either store it in your database with a `pending` status, or have some unique `hash` assigned to it, with a matching `hash` stored in the user's session. The point is to be able to identify incomplete uploads that belong to this specific user. Then when you display the form, retrieve those incomplete files either from the session or database, and display the thumbnail next to the file upload. This tells the user that they don't need to re-upload that file. Just make sure that they have a way to remove it as well in case they changed their mind. Once the form is submitted correctly then clear the session `hash` or update the database status to `complete`; whatever you need to do.
There seems to be a lot of questions around for the same issue ([Form::file: How to repopulate with Input::old After Validation Errors and/or on Update?](https://stackoverflow.com/questions/22659345/formfile-how-to-repopulate-with-inputold-after-validation-errors-and-or-on)) and everyone with apparent knowledge says that is not possible. I would proppose a **workaround** that covers the following goals: * Keep form data and file input in case of failed Laravel validation * Use server side validation only. You don't need SHOULD NEVER USE javascript validation. The keyword of it all is **AJAX**. I would do the following: **December 2017 update:** Send all fields and attached files by a **single AJAX POST** 1. Create an AJAX form (method GET **POST**) that contains everything except **including** file input. Remember that it requires to send the **Laravel CSRF token**. 2. In the controller validation you need to make your responses (failed or success) to make a JSON output, so your AJAX send code can get the response in any case, and then you can show it in your browser This way you avoid to have files in any temporal state in your server. A more complex but improved version of this process, **if you are worried about used bandwidth** and you expect having errors in your input fields will be very common, you may do two (or more) AJAX POST validations: The first one with the input fields only, and if it's ok, send all fields (input fields again, now including the attached files) to attempt validation again and do actions with all data in case of success.
33,158,331
I have a query in Oracle SQL that displays results as follows: **SQL:** ``` select uuid, name, to_char(from_tz(startdate, 'UTC') at time zone 'America/New_York', 'yyyy-mm-dd hh24:mi:ss') as startdate_et, to_char(from_tz(enddate, 'UTC') at time zone 'America/New_York', 'yyyy-mm-dd hh24:mi:ss') as enddate_et, (enddate - startdate) as executiontime from process where name = (select name from jobconfiguration where currentprocessid = 'bGd_AAABNaMAAAFQHvY0UyTa'); ``` **Output:** [![enter image description here](https://i.stack.imgur.com/dwZ1K.png)](https://i.stack.imgur.com/dwZ1K.png) The problem here is the data in the `executiontime` column. The milliseconds value is too long and also I would like to remove the `+00` from the beginning and trim the `02.951000` to `02.95` and `03.284000` to `03.28`. Please guide.
2015/10/15
[ "https://Stackoverflow.com/questions/33158331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325154/" ]
No, the `file` input can't be prepopulated by Laravel or by any software. Your website (and any website) doesn't and shouldn't know the local path to the file. Imagine the security risks if they did! You could trick a user into uploading their SSH private key or something. What you need to do is process the uploaded file regardless, even if there are validation errors. Then you could either store it in your database with a `pending` status, or have some unique `hash` assigned to it, with a matching `hash` stored in the user's session. The point is to be able to identify incomplete uploads that belong to this specific user. Then when you display the form, retrieve those incomplete files either from the session or database, and display the thumbnail next to the file upload. This tells the user that they don't need to re-upload that file. Just make sure that they have a way to remove it as well in case they changed their mind. Once the form is submitted correctly then clear the session `hash` or update the database status to `complete`; whatever you need to do.
If your file is an image, you can create a hidden input and write there **base64** string there when the user uploads the image ``` {!! Form::open(array('url' => 'foo/bar')) !!} {!! Form::text('image_name') !!} {!! Form::hidden('base64_image') !!} {!! Form::file('image') !!} {!! Form::submit('Submit!') !!} {!! Form::close() !!} ```
33,158,331
I have a query in Oracle SQL that displays results as follows: **SQL:** ``` select uuid, name, to_char(from_tz(startdate, 'UTC') at time zone 'America/New_York', 'yyyy-mm-dd hh24:mi:ss') as startdate_et, to_char(from_tz(enddate, 'UTC') at time zone 'America/New_York', 'yyyy-mm-dd hh24:mi:ss') as enddate_et, (enddate - startdate) as executiontime from process where name = (select name from jobconfiguration where currentprocessid = 'bGd_AAABNaMAAAFQHvY0UyTa'); ``` **Output:** [![enter image description here](https://i.stack.imgur.com/dwZ1K.png)](https://i.stack.imgur.com/dwZ1K.png) The problem here is the data in the `executiontime` column. The milliseconds value is too long and also I would like to remove the `+00` from the beginning and trim the `02.951000` to `02.95` and `03.284000` to `03.28`. Please guide.
2015/10/15
[ "https://Stackoverflow.com/questions/33158331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325154/" ]
There seems to be a lot of questions around for the same issue ([Form::file: How to repopulate with Input::old After Validation Errors and/or on Update?](https://stackoverflow.com/questions/22659345/formfile-how-to-repopulate-with-inputold-after-validation-errors-and-or-on)) and everyone with apparent knowledge says that is not possible. I would proppose a **workaround** that covers the following goals: * Keep form data and file input in case of failed Laravel validation * Use server side validation only. You don't need SHOULD NEVER USE javascript validation. The keyword of it all is **AJAX**. I would do the following: **December 2017 update:** Send all fields and attached files by a **single AJAX POST** 1. Create an AJAX form (method GET **POST**) that contains everything except **including** file input. Remember that it requires to send the **Laravel CSRF token**. 2. In the controller validation you need to make your responses (failed or success) to make a JSON output, so your AJAX send code can get the response in any case, and then you can show it in your browser This way you avoid to have files in any temporal state in your server. A more complex but improved version of this process, **if you are worried about used bandwidth** and you expect having errors in your input fields will be very common, you may do two (or more) AJAX POST validations: The first one with the input fields only, and if it's ok, send all fields (input fields again, now including the attached files) to attempt validation again and do actions with all data in case of success.
If your file is an image, you can create a hidden input and write there **base64** string there when the user uploads the image ``` {!! Form::open(array('url' => 'foo/bar')) !!} {!! Form::text('image_name') !!} {!! Form::hidden('base64_image') !!} {!! Form::file('image') !!} {!! Form::submit('Submit!') !!} {!! Form::close() !!} ```
41,740,126
Okay, the title might be kind of misleading, but I couldn't really come up with a better explanation for my problem. I'm trying to create a program that takes an array of first names and an array of last names, and puts these together in an array of full names. Problem here is that I'm trying to make sure that the same name doesn't occur twice, so that if a combination of firstname[randomindex] and lastname[randomindex] is already in the full names array, it will reroll the random number used for index untill it finds a combination that has not been used. So far I'm kinda stuck at this: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _100randompersons { class Fyldefylde { private string[] firstnames; private string[] lastnames; private string[] fullnames; private Random random; public Fyldefylde() { firstnames = new string[10] { "Kim", "Allan", "Frank", "Lone", "Line", "Anne", "Per", "Bo", "Grethe", "Mette" }; lastnames = new string[10] { "Pedersen", "Nielsen", "Hansen", "Larsen", "Nygaard", "Harboe", "Bendix", "Højris", "Pilgaard", "Nyager" }; fullnames = new string[100]; random = new Random(); } public string[] getFirstNames() { return firstnames; } public string[] getLastNames() { return lastnames; } public string[] getFullNames() { return fullnames; } public int getRandomIndex(int min, int max) { int randomnumber = random.Next(min, max); return randomnumber; } public void fillFullNames() { for(int i = 0; i < fullnames.Length; i++) { getRandomIndex(0, 10); while(fullnames.Contains(firstnames[getRandomIndex(0,10)] + " " + lastnames[getRandomIndex(0,10)])) { fullnames[i] = firstnames[getRandomIndex(0, 10)] + " " + lastnames[getRandomIndex(0, 10)]; } } } } } ``` Thanks in advance! :)
2017/01/19
[ "https://Stackoverflow.com/questions/41740126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7230001/" ]
It looks like you just want to make all combinations of full names, so why not do that? ``` for (int i = 0; i < firstnames.Length; i++) { for (int j = 0; j < lastnames.Length; j++) { fullnames[i*lastnames.Length + j] = firstnames[i] + " " + lastnames[j]; } } ``` Then if you want your names in a random order, run a method to randomize the order of names If you want the names in a random order then you could always do something like the following ``` string[] firstnames = new string[10] { "Kim", "Allan", "Frank", "Lone", "Line", "Anne", "Per", "Bo", "Grethe", "Mette" }; string[] lastnames = new string[10] { "Pedersen", "Nielsen", "Hansen", "Larsen", "Nygaard", "Harboe", "Bendix", "Højris", "Pilgaard", "Nyager" }; string[] fullnames = new string[100]; List<int> indices = new List<int>(); for (int i = 0; i < firstnames.Length * lastnames.Length; i++) { indices.Add(i); } Random random = new Random(); for (int i = 0; i < firstnames.Length; i++) { for (int j = 0; j < lastnames.Length; j++) { int randomIndex = random.Next(indices.Count() - 1); fullnames[indices[randomIndex]] = firstnames[i] + " " + lastnames[j]; indices.RemoveAt(randomIndex); } } ```
Your best bet is to generate a prototype version of `fullname` which represents every possible combination, then shuffle that if you want randomised output: ``` Random rnd = new Random(); string[] random_full_name = fullname.OrderBy(x => rnd.Next()).ToArray(); ``` You then read this new array out consecutively to achieve your random sample with no duplciates.
41,740,126
Okay, the title might be kind of misleading, but I couldn't really come up with a better explanation for my problem. I'm trying to create a program that takes an array of first names and an array of last names, and puts these together in an array of full names. Problem here is that I'm trying to make sure that the same name doesn't occur twice, so that if a combination of firstname[randomindex] and lastname[randomindex] is already in the full names array, it will reroll the random number used for index untill it finds a combination that has not been used. So far I'm kinda stuck at this: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _100randompersons { class Fyldefylde { private string[] firstnames; private string[] lastnames; private string[] fullnames; private Random random; public Fyldefylde() { firstnames = new string[10] { "Kim", "Allan", "Frank", "Lone", "Line", "Anne", "Per", "Bo", "Grethe", "Mette" }; lastnames = new string[10] { "Pedersen", "Nielsen", "Hansen", "Larsen", "Nygaard", "Harboe", "Bendix", "Højris", "Pilgaard", "Nyager" }; fullnames = new string[100]; random = new Random(); } public string[] getFirstNames() { return firstnames; } public string[] getLastNames() { return lastnames; } public string[] getFullNames() { return fullnames; } public int getRandomIndex(int min, int max) { int randomnumber = random.Next(min, max); return randomnumber; } public void fillFullNames() { for(int i = 0; i < fullnames.Length; i++) { getRandomIndex(0, 10); while(fullnames.Contains(firstnames[getRandomIndex(0,10)] + " " + lastnames[getRandomIndex(0,10)])) { fullnames[i] = firstnames[getRandomIndex(0, 10)] + " " + lastnames[getRandomIndex(0, 10)]; } } } } } ``` Thanks in advance! :)
2017/01/19
[ "https://Stackoverflow.com/questions/41740126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7230001/" ]
You could use a simple HashSet to make sure that values are unique: ``` public void fillFullNames() { HashSet<string> newFullNames = new HashSet<string>(); while (newFullNames.Count != fullnames.Length) { newFullNames.Add(firstnames[getRandomIndex(0, 10)] + " " + lastnames[getRandomIndex(0, 10)]); } fullnames = newFullNames.ToArray(); } ```
Your best bet is to generate a prototype version of `fullname` which represents every possible combination, then shuffle that if you want randomised output: ``` Random rnd = new Random(); string[] random_full_name = fullname.OrderBy(x => rnd.Next()).ToArray(); ``` You then read this new array out consecutively to achieve your random sample with no duplciates.
41,740,126
Okay, the title might be kind of misleading, but I couldn't really come up with a better explanation for my problem. I'm trying to create a program that takes an array of first names and an array of last names, and puts these together in an array of full names. Problem here is that I'm trying to make sure that the same name doesn't occur twice, so that if a combination of firstname[randomindex] and lastname[randomindex] is already in the full names array, it will reroll the random number used for index untill it finds a combination that has not been used. So far I'm kinda stuck at this: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _100randompersons { class Fyldefylde { private string[] firstnames; private string[] lastnames; private string[] fullnames; private Random random; public Fyldefylde() { firstnames = new string[10] { "Kim", "Allan", "Frank", "Lone", "Line", "Anne", "Per", "Bo", "Grethe", "Mette" }; lastnames = new string[10] { "Pedersen", "Nielsen", "Hansen", "Larsen", "Nygaard", "Harboe", "Bendix", "Højris", "Pilgaard", "Nyager" }; fullnames = new string[100]; random = new Random(); } public string[] getFirstNames() { return firstnames; } public string[] getLastNames() { return lastnames; } public string[] getFullNames() { return fullnames; } public int getRandomIndex(int min, int max) { int randomnumber = random.Next(min, max); return randomnumber; } public void fillFullNames() { for(int i = 0; i < fullnames.Length; i++) { getRandomIndex(0, 10); while(fullnames.Contains(firstnames[getRandomIndex(0,10)] + " " + lastnames[getRandomIndex(0,10)])) { fullnames[i] = firstnames[getRandomIndex(0, 10)] + " " + lastnames[getRandomIndex(0, 10)]; } } } } } ``` Thanks in advance! :)
2017/01/19
[ "https://Stackoverflow.com/questions/41740126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7230001/" ]
It looks like you just want to make all combinations of full names, so why not do that? ``` for (int i = 0; i < firstnames.Length; i++) { for (int j = 0; j < lastnames.Length; j++) { fullnames[i*lastnames.Length + j] = firstnames[i] + " " + lastnames[j]; } } ``` Then if you want your names in a random order, run a method to randomize the order of names If you want the names in a random order then you could always do something like the following ``` string[] firstnames = new string[10] { "Kim", "Allan", "Frank", "Lone", "Line", "Anne", "Per", "Bo", "Grethe", "Mette" }; string[] lastnames = new string[10] { "Pedersen", "Nielsen", "Hansen", "Larsen", "Nygaard", "Harboe", "Bendix", "Højris", "Pilgaard", "Nyager" }; string[] fullnames = new string[100]; List<int> indices = new List<int>(); for (int i = 0; i < firstnames.Length * lastnames.Length; i++) { indices.Add(i); } Random random = new Random(); for (int i = 0; i < firstnames.Length; i++) { for (int j = 0; j < lastnames.Length; j++) { int randomIndex = random.Next(indices.Count() - 1); fullnames[indices[randomIndex]] = firstnames[i] + " " + lastnames[j]; indices.RemoveAt(randomIndex); } } ```
You could use a simple HashSet to make sure that values are unique: ``` public void fillFullNames() { HashSet<string> newFullNames = new HashSet<string>(); while (newFullNames.Count != fullnames.Length) { newFullNames.Add(firstnames[getRandomIndex(0, 10)] + " " + lastnames[getRandomIndex(0, 10)]); } fullnames = newFullNames.ToArray(); } ```
53,805,631
I don't know what can I tell more. I have this method: ``` public async Task<HttpResponseMessage> SendAsyncRequest(string uri, string content, HttpMethod method, bool tryReauthorizeOn401 = true) { HttpRequestMessage rm = new HttpRequestMessage(method, uri); if (!string.IsNullOrWhiteSpace(content)) rm.Content = new StringContent(content, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.SendAsync(rm); if (response.StatusCode == HttpStatusCode.Unauthorized && tryReauthorizeOn401) { var res = await AuthenticateUser(); if(res.user == null) return response; return await SendAsyncRequest(uri, content, method, false); } return response; } ``` Nothing special. client.SendAsync(rm) is executed, response.StatusCode is Ok. Application just crashes when exiting from this method. Output shows me just this assert: ``` 12-16 20:09:22.025 F/ ( 1683): * Assertion at /Users/builder/jenkins/workspace/xamarin-android-d15-9/xamarin-android/external/mono/mono/mini/debugger-agent.c:4957, condition `is_ok (error)' not met, function:set_set_notification_for_wait_completion_flag, Could not execute the method because the containing type is not fully instantiated. assembly:<unknown assembly> type:<unknown type> member:(null) 12-16 20:09:22.025 F/libc ( 1683): Fatal signal 6 (SIGABRT), code -6 in tid 1683 (omerang.Android) ``` And nothing more. client is HttpClient. I have setting in my Android project: **HttpClient Implementation** set to Android. Does anyone have any idea what could be wrong? **edit** SendAsyncRequest is used like that: ``` public async Task<(HttpResponseMessage response, IEnumerable<T> items)> GetListFromRequest<T>(string uri) { HttpResponseMessage response = await SendAsyncRequest(uri, null, HttpMethod.Get); if (!response.IsSuccessStatusCode) return (response, null); string content = await response.Content.ReadAsStringAsync(); var items = JsonConvert.DeserializeObject<IEnumerable<T>>(content); return (response, new List<T>(items)); } ```
2018/12/16
[ "https://Stackoverflow.com/questions/53805631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5330895/" ]
Based on the provided example project code you provided ``` protected override async void OnStart() { Controller c = new Controller(); TodoItem item = await c.GetTodoItem(1); TodoItem item2 = await c.GetTodoItem(2); } ``` You are calling `async void` fire and forget on startup. You wont be able to catch any thrown exceptions, which would explain why the App crashes with no warning. Reference [Async/Await - Best Practices in Asynchronous Programming](https://msdn.microsoft.com/en-us/magazine/jj991977.aspx) `async void` should only be used with event handlers, so I would suggest adding an event and handler. based on the provided example, it could look like as follows ``` public partial class App : Application { public App() { InitializeComponent(); MainPage = new MainPage(); } private even EventHander starting = delegate { }; private async void onStarting(object sender, EventArgs args) { starting -= onStarting; try { var controller = new Controller(); TodoItem item = await controller.GetTodoItem(1); TodoItem item2 = await controller.GetTodoItem(2); } catch(Exception ex) { //...handler error here } } protected override void OnStart() { starting += onStarting; starting(this, EventArgs.Empty); } //...omitted for brevity } ``` With that, you should now at least be able to catch the thrown exception to determine what is failing.
try to update your compileSdkVersion to a higher version and check. also try following > > > ``` > > Go to: File > Invalidate Caches/Restart and select Invalidate and Restart > > ``` > >
56,066,777
I'm using plotly to display some shapes and add some annotations (text) over them. However I don't know how to control layer ordering to plot objects in plotly and the text is always behind the shapes (I didn't found any example in plotly R API docs). Here follows a reproducible example: ``` library("plotly") shapes <- list( list(type = "rect", fillcolor = "red", line = list(color = "white"), x0 = 0.0, x1 = 0.5, xref = "x", y0 = 0.0, y1 = 1.0, yref = "y", opacity = 0.3), list(type = "rect", fillcolor = "grey", line = list(color = "white"), x0 = 0.5, x1 = 1.0, xref = "x", y0 = 0.0, y1 = 1.0, yref = "y", opacity = 0.98) ) plot_ly() %>% layout(shapes = shapes) %>% add_text(x = c(0.25, 0.75), y = 0.5, text = c("Easy Visible", "Barely visible"), textfont = list(color = '#000000')) ``` Which produces the following output (using opacity parameter we can see that the text is behind the shape): [![enter image description here](https://i.stack.imgur.com/pqX78.png)](https://i.stack.imgur.com/pqX78.png) Any idea on how to add texts in front of opaque shapes?
2019/05/09
[ "https://Stackoverflow.com/questions/56066777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4862402/" ]
A `HashMap<T, T>` is not a Map but a done something very weird to your equals() and hashCode() methods. As commented, creating a temporary short lived instance is cheap because the garbage collector uses generations. But what you must check for existence is the key not the object itself.
I don't know what you're doing to use up a lot of heap memory but why not look at weak and strong references. * Weak references to a single object are kept around as long as there is a single hard reference. When the hard reference is garbage collected, so are the weak references. * Strong references will only go away when you start to run out of heap space. This would happen as you want to use more heap space for other objects. The older ones are GC'd. So depending on what you are doing, you may want to check them out.
582,452
I would like to call multiple .msi files in silent mode, and halt the entire installation if any fail. Is it possible to get the return codes of msiexec.exe being called from the [run] section? Currently I can only see error messages in the windows event viewer.
2009/02/24
[ "https://Stackoverflow.com/questions/582452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145/" ]
There is currently no way to check the successful execution of *[Run]* entries. The code just logs the process exit code and continues with the next entry (it can be examined in the Inno Setup source file *Main.pas*, the function is *ProcessRunEntry()*, starting at line 3404 in the current version 5.2.3). If you need to make sure that multiple executions of msiexec were all successful you will need to code an intermediate layer. This can be as simple as a small stub that is executed in the [Run] entries and starts msiexec.exe with the correct parameters, waits for the process to finish, then writes the return code to a file. Another way to check for success of such an installation step would be to add a custom procedure call for each *[Run]* entry by using the *AfterInstall* Parameter. In such a function you could for example check whether an OCX control has been successfully installed: ``` [Run] Filename: "{tmp}\MyInstallation1.exe"; Parameters: "/foo"; AfterInstall: AfterMyInstallation1 [Code] var MyInstallation1Success: boolean; procedure AfterMyInstallation1; var V: Variant; begin try V := CreateOleObject('MyInstallation.InstalledOcxControl.1'); MyInstallation1Success := True; except MyInstallation1Success := False; end; end; ``` or whether the directories and registry entries for the dependency are all there. Each *[Run]* entry is only executed when its optional *Check* parameter does return true. So depending on your needs you could either start all silent installations one after the other, and after the last has finished execute a script function to check that all dependencies were successfully installed; or you could write a check function for each dependency installation, which would then return false and thus skip all other installations after the first failed one. Note however that all *[Run]* entries are executed after the steps for file copying, registry writing etc. are completed, so you are basically already finished with the installation. If you want to really execute all your installation steps only when all dependencies are correctly installed, then you would have to do that earlier in the process, when the installation can still be cancelled. **Edit:** Check out the question ["How do you make Inno Setup not look frozen while performing a long Exec?"](https://stackoverflow.com/questions/591899/how-do-you-make-inno-setup-not-look-frozen-while-performing-a-long-exec) where some information is given and a sample script is linked to about using the *Exec()* function for installing dependencies. So if you do not use *[Run]* entries there is a good chance to achieve what you want.
You can use [my answer](https://stackoverflow.com/a/24323119/2164198) to similar question to run commands safely in [Run] section with proper notification and rollback on error. The link above provides complete solution, but idea is folowing: 1) Write error message to temporary file {tmp}\install.error using InnoSetup's BeforeInstall parameter. 2) Use Windows command shell "cmd.exe /s /c" to run desired program. Also use conditional execution of "del" command with "&&" - <http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true>. So error message file would be deleted if command succeed (exit code 0). Please be aware of special quotes handling in "cmd.exe /s /c". 3) Check existence of error message file {tmp}\install.error using InnoSetup's AfterInstall parameter and abort install with proper notification or confirmation (and optional presenting of log file) and perform rollback using Exec(ExpandConstant('{uninstallexe}'), ... 4) There are some additional steps should be done like overriding InnoSetup's ShouldSkipPage(PageID: Integer) function to hide final page, etc.
6,275,693
I'm using the following unmanaged C++ code to instantiate the CLR from an Excel 2003 add-in (a COM shim for a .NET add-in): ``` hr = CorBindToRuntimeEx( 0, // version, use default 0, // flavor, use default 0, // domain-neutral"ness" and gc settings CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (PVOID*) &m_pHost); ``` and for the vast majority of the machines in our organisation (a few hundred) this works perfectly, even those with multiple CLR versions installed; however for a few machines a wrong (older) version of the CLR is instantiated which then fails to load the assembly as it requires the .NET 2 runtime. Yesterday for the first time I ran Process Explorer and this was quite revealing showing the following on one of the problem machines: ``` process pid type Handle or DLL ------- --- ---- ------------- procexp.exe 5056 DLL c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorworks.dll EXCEL.EXE 7180 DLL c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorworks.dll ``` i.e. Excel has loaded the wrong version of the runtime even though a newer one is availble. Now I need to find out why. A few possibilities that come to mind: 1. There is something odd with the 'priority' of CLR instantiation on the specific machine, even though the MS docs (http://msdn.microsoft.com/en-us/library/ms231419.aspx) appear to indicate that you'll always get the newest unless you request a specific version. 2. Another add-in in Excel has already (deliberately) instantiated a .NET 1 CLR and Excel can't host more than one. I strongly suspect the second of these but don't know how to prove / fix it. Has anyone seen similar behaviour? Any suggestions on what is going on? A few other notes: * All workstations are running Windows XP SP3 * Excel 2003 SP3 is the only version of Excel in our organisation I can't change either of these so a newer Excel version is not an option.
2011/06/08
[ "https://Stackoverflow.com/questions/6275693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323105/" ]
I would compress them into one file in order to reduce the http requests. Look at the [HTML5Boilerplate's Build Script](http://html5boilerplate.com). It allows you to code in separate files and deploy in one minified file. This is always best practice.
Using method 1 would result in requests for the `css1.css` and `css2.css` files so you would make 3 requests as opposed to 2 if you requested the files seperately. Combining the files into a single file such as method 2 would conform to the Yahoo rules.
6,275,693
I'm using the following unmanaged C++ code to instantiate the CLR from an Excel 2003 add-in (a COM shim for a .NET add-in): ``` hr = CorBindToRuntimeEx( 0, // version, use default 0, // flavor, use default 0, // domain-neutral"ness" and gc settings CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (PVOID*) &m_pHost); ``` and for the vast majority of the machines in our organisation (a few hundred) this works perfectly, even those with multiple CLR versions installed; however for a few machines a wrong (older) version of the CLR is instantiated which then fails to load the assembly as it requires the .NET 2 runtime. Yesterday for the first time I ran Process Explorer and this was quite revealing showing the following on one of the problem machines: ``` process pid type Handle or DLL ------- --- ---- ------------- procexp.exe 5056 DLL c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorworks.dll EXCEL.EXE 7180 DLL c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorworks.dll ``` i.e. Excel has loaded the wrong version of the runtime even though a newer one is availble. Now I need to find out why. A few possibilities that come to mind: 1. There is something odd with the 'priority' of CLR instantiation on the specific machine, even though the MS docs (http://msdn.microsoft.com/en-us/library/ms231419.aspx) appear to indicate that you'll always get the newest unless you request a specific version. 2. Another add-in in Excel has already (deliberately) instantiated a .NET 1 CLR and Excel can't host more than one. I strongly suspect the second of these but don't know how to prove / fix it. Has anyone seen similar behaviour? Any suggestions on what is going on? A few other notes: * All workstations are running Windows XP SP3 * Excel 2003 SP3 is the only version of Excel in our organisation I can't change either of these so a newer Excel version is not an option.
2011/06/08
[ "https://Stackoverflow.com/questions/6275693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323105/" ]
I would compress them into one file in order to reduce the http requests. Look at the [HTML5Boilerplate's Build Script](http://html5boilerplate.com). It allows you to code in separate files and deploy in one minified file. This is always best practice.
The best way to do this is with some sort of build process which combines all our source css into one file (similar to your method 2) but retains the original CSS for development and debugging in multiple files. There are many tool which help with this and depending on your platform and any framewroks you are using different ones have different strengths. You might also like to take a look at sass if you're comfortable with ruby as well, it's great for organising CSS code. If you're using php I would heartily recommend minify, which does JavaScript as well. Most of the tools will also compress our CSS for you too removing unnecessary white space while keeping your source stylesheets nice and clean.
6,275,693
I'm using the following unmanaged C++ code to instantiate the CLR from an Excel 2003 add-in (a COM shim for a .NET add-in): ``` hr = CorBindToRuntimeEx( 0, // version, use default 0, // flavor, use default 0, // domain-neutral"ness" and gc settings CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (PVOID*) &m_pHost); ``` and for the vast majority of the machines in our organisation (a few hundred) this works perfectly, even those with multiple CLR versions installed; however for a few machines a wrong (older) version of the CLR is instantiated which then fails to load the assembly as it requires the .NET 2 runtime. Yesterday for the first time I ran Process Explorer and this was quite revealing showing the following on one of the problem machines: ``` process pid type Handle or DLL ------- --- ---- ------------- procexp.exe 5056 DLL c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorworks.dll EXCEL.EXE 7180 DLL c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorworks.dll ``` i.e. Excel has loaded the wrong version of the runtime even though a newer one is availble. Now I need to find out why. A few possibilities that come to mind: 1. There is something odd with the 'priority' of CLR instantiation on the specific machine, even though the MS docs (http://msdn.microsoft.com/en-us/library/ms231419.aspx) appear to indicate that you'll always get the newest unless you request a specific version. 2. Another add-in in Excel has already (deliberately) instantiated a .NET 1 CLR and Excel can't host more than one. I strongly suspect the second of these but don't know how to prove / fix it. Has anyone seen similar behaviour? Any suggestions on what is going on? A few other notes: * All workstations are running Windows XP SP3 * Excel 2003 SP3 is the only version of Excel in our organisation I can't change either of these so a newer Excel version is not an option.
2011/06/08
[ "https://Stackoverflow.com/questions/6275693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323105/" ]
I would compress them into one file in order to reduce the http requests. Look at the [HTML5Boilerplate's Build Script](http://html5boilerplate.com). It allows you to code in separate files and deploy in one minified file. This is always best practice.
best way is to combine all the files, compress them with YUI compressor. you can find detailed help at this [link](http://beardscratchers.com/journal/compressing-css-and-javascript-with-yui-compressor)
6,275,693
I'm using the following unmanaged C++ code to instantiate the CLR from an Excel 2003 add-in (a COM shim for a .NET add-in): ``` hr = CorBindToRuntimeEx( 0, // version, use default 0, // flavor, use default 0, // domain-neutral"ness" and gc settings CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (PVOID*) &m_pHost); ``` and for the vast majority of the machines in our organisation (a few hundred) this works perfectly, even those with multiple CLR versions installed; however for a few machines a wrong (older) version of the CLR is instantiated which then fails to load the assembly as it requires the .NET 2 runtime. Yesterday for the first time I ran Process Explorer and this was quite revealing showing the following on one of the problem machines: ``` process pid type Handle or DLL ------- --- ---- ------------- procexp.exe 5056 DLL c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorworks.dll EXCEL.EXE 7180 DLL c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorworks.dll ``` i.e. Excel has loaded the wrong version of the runtime even though a newer one is availble. Now I need to find out why. A few possibilities that come to mind: 1. There is something odd with the 'priority' of CLR instantiation on the specific machine, even though the MS docs (http://msdn.microsoft.com/en-us/library/ms231419.aspx) appear to indicate that you'll always get the newest unless you request a specific version. 2. Another add-in in Excel has already (deliberately) instantiated a .NET 1 CLR and Excel can't host more than one. I strongly suspect the second of these but don't know how to prove / fix it. Has anyone seen similar behaviour? Any suggestions on what is going on? A few other notes: * All workstations are running Windows XP SP3 * Excel 2003 SP3 is the only version of Excel in our organisation I can't change either of these so a newer Excel version is not an option.
2011/06/08
[ "https://Stackoverflow.com/questions/6275693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323105/" ]
I would compress them into one file in order to reduce the http requests. Look at the [HTML5Boilerplate's Build Script](http://html5boilerplate.com). It allows you to code in separate files and deploy in one minified file. This is always best practice.
There are some problems using @import 1. Different browsers treat import differently (Was a problem in older browsers which may not be used now) 2. I guess IE6 and IE7 do not support @media. In link tag you can specify media as screen, print, etc. But IE6 and IE7 do not support @media in CSS. So specifying media types would not be possible in IE6 and IE7 when using @import. 3. Each import would result in a new HTTP request Method 1 does follow Yahoo rules. You may split your CSS into multiple files in Development environment and when deploying to production you can club them together.
6,275,693
I'm using the following unmanaged C++ code to instantiate the CLR from an Excel 2003 add-in (a COM shim for a .NET add-in): ``` hr = CorBindToRuntimeEx( 0, // version, use default 0, // flavor, use default 0, // domain-neutral"ness" and gc settings CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (PVOID*) &m_pHost); ``` and for the vast majority of the machines in our organisation (a few hundred) this works perfectly, even those with multiple CLR versions installed; however for a few machines a wrong (older) version of the CLR is instantiated which then fails to load the assembly as it requires the .NET 2 runtime. Yesterday for the first time I ran Process Explorer and this was quite revealing showing the following on one of the problem machines: ``` process pid type Handle or DLL ------- --- ---- ------------- procexp.exe 5056 DLL c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorworks.dll EXCEL.EXE 7180 DLL c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorworks.dll ``` i.e. Excel has loaded the wrong version of the runtime even though a newer one is availble. Now I need to find out why. A few possibilities that come to mind: 1. There is something odd with the 'priority' of CLR instantiation on the specific machine, even though the MS docs (http://msdn.microsoft.com/en-us/library/ms231419.aspx) appear to indicate that you'll always get the newest unless you request a specific version. 2. Another add-in in Excel has already (deliberately) instantiated a .NET 1 CLR and Excel can't host more than one. I strongly suspect the second of these but don't know how to prove / fix it. Has anyone seen similar behaviour? Any suggestions on what is going on? A few other notes: * All workstations are running Windows XP SP3 * Excel 2003 SP3 is the only version of Excel in our organisation I can't change either of these so a newer Excel version is not an option.
2011/06/08
[ "https://Stackoverflow.com/questions/6275693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323105/" ]
The best way to do this is with some sort of build process which combines all our source css into one file (similar to your method 2) but retains the original CSS for development and debugging in multiple files. There are many tool which help with this and depending on your platform and any framewroks you are using different ones have different strengths. You might also like to take a look at sass if you're comfortable with ruby as well, it's great for organising CSS code. If you're using php I would heartily recommend minify, which does JavaScript as well. Most of the tools will also compress our CSS for you too removing unnecessary white space while keeping your source stylesheets nice and clean.
Using method 1 would result in requests for the `css1.css` and `css2.css` files so you would make 3 requests as opposed to 2 if you requested the files seperately. Combining the files into a single file such as method 2 would conform to the Yahoo rules.
6,275,693
I'm using the following unmanaged C++ code to instantiate the CLR from an Excel 2003 add-in (a COM shim for a .NET add-in): ``` hr = CorBindToRuntimeEx( 0, // version, use default 0, // flavor, use default 0, // domain-neutral"ness" and gc settings CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (PVOID*) &m_pHost); ``` and for the vast majority of the machines in our organisation (a few hundred) this works perfectly, even those with multiple CLR versions installed; however for a few machines a wrong (older) version of the CLR is instantiated which then fails to load the assembly as it requires the .NET 2 runtime. Yesterday for the first time I ran Process Explorer and this was quite revealing showing the following on one of the problem machines: ``` process pid type Handle or DLL ------- --- ---- ------------- procexp.exe 5056 DLL c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorworks.dll EXCEL.EXE 7180 DLL c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorworks.dll ``` i.e. Excel has loaded the wrong version of the runtime even though a newer one is availble. Now I need to find out why. A few possibilities that come to mind: 1. There is something odd with the 'priority' of CLR instantiation on the specific machine, even though the MS docs (http://msdn.microsoft.com/en-us/library/ms231419.aspx) appear to indicate that you'll always get the newest unless you request a specific version. 2. Another add-in in Excel has already (deliberately) instantiated a .NET 1 CLR and Excel can't host more than one. I strongly suspect the second of these but don't know how to prove / fix it. Has anyone seen similar behaviour? Any suggestions on what is going on? A few other notes: * All workstations are running Windows XP SP3 * Excel 2003 SP3 is the only version of Excel in our organisation I can't change either of these so a newer Excel version is not an option.
2011/06/08
[ "https://Stackoverflow.com/questions/6275693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323105/" ]
There are some problems using @import 1. Different browsers treat import differently (Was a problem in older browsers which may not be used now) 2. I guess IE6 and IE7 do not support @media. In link tag you can specify media as screen, print, etc. But IE6 and IE7 do not support @media in CSS. So specifying media types would not be possible in IE6 and IE7 when using @import. 3. Each import would result in a new HTTP request Method 1 does follow Yahoo rules. You may split your CSS into multiple files in Development environment and when deploying to production you can club them together.
Using method 1 would result in requests for the `css1.css` and `css2.css` files so you would make 3 requests as opposed to 2 if you requested the files seperately. Combining the files into a single file such as method 2 would conform to the Yahoo rules.
6,275,693
I'm using the following unmanaged C++ code to instantiate the CLR from an Excel 2003 add-in (a COM shim for a .NET add-in): ``` hr = CorBindToRuntimeEx( 0, // version, use default 0, // flavor, use default 0, // domain-neutral"ness" and gc settings CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (PVOID*) &m_pHost); ``` and for the vast majority of the machines in our organisation (a few hundred) this works perfectly, even those with multiple CLR versions installed; however for a few machines a wrong (older) version of the CLR is instantiated which then fails to load the assembly as it requires the .NET 2 runtime. Yesterday for the first time I ran Process Explorer and this was quite revealing showing the following on one of the problem machines: ``` process pid type Handle or DLL ------- --- ---- ------------- procexp.exe 5056 DLL c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorworks.dll EXCEL.EXE 7180 DLL c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorworks.dll ``` i.e. Excel has loaded the wrong version of the runtime even though a newer one is availble. Now I need to find out why. A few possibilities that come to mind: 1. There is something odd with the 'priority' of CLR instantiation on the specific machine, even though the MS docs (http://msdn.microsoft.com/en-us/library/ms231419.aspx) appear to indicate that you'll always get the newest unless you request a specific version. 2. Another add-in in Excel has already (deliberately) instantiated a .NET 1 CLR and Excel can't host more than one. I strongly suspect the second of these but don't know how to prove / fix it. Has anyone seen similar behaviour? Any suggestions on what is going on? A few other notes: * All workstations are running Windows XP SP3 * Excel 2003 SP3 is the only version of Excel in our organisation I can't change either of these so a newer Excel version is not an option.
2011/06/08
[ "https://Stackoverflow.com/questions/6275693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323105/" ]
The best way to do this is with some sort of build process which combines all our source css into one file (similar to your method 2) but retains the original CSS for development and debugging in multiple files. There are many tool which help with this and depending on your platform and any framewroks you are using different ones have different strengths. You might also like to take a look at sass if you're comfortable with ruby as well, it's great for organising CSS code. If you're using php I would heartily recommend minify, which does JavaScript as well. Most of the tools will also compress our CSS for you too removing unnecessary white space while keeping your source stylesheets nice and clean.
best way is to combine all the files, compress them with YUI compressor. you can find detailed help at this [link](http://beardscratchers.com/journal/compressing-css-and-javascript-with-yui-compressor)
6,275,693
I'm using the following unmanaged C++ code to instantiate the CLR from an Excel 2003 add-in (a COM shim for a .NET add-in): ``` hr = CorBindToRuntimeEx( 0, // version, use default 0, // flavor, use default 0, // domain-neutral"ness" and gc settings CLSID_CorRuntimeHost, IID_ICorRuntimeHost, (PVOID*) &m_pHost); ``` and for the vast majority of the machines in our organisation (a few hundred) this works perfectly, even those with multiple CLR versions installed; however for a few machines a wrong (older) version of the CLR is instantiated which then fails to load the assembly as it requires the .NET 2 runtime. Yesterday for the first time I ran Process Explorer and this was quite revealing showing the following on one of the problem machines: ``` process pid type Handle or DLL ------- --- ---- ------------- procexp.exe 5056 DLL c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorworks.dll EXCEL.EXE 7180 DLL c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorworks.dll ``` i.e. Excel has loaded the wrong version of the runtime even though a newer one is availble. Now I need to find out why. A few possibilities that come to mind: 1. There is something odd with the 'priority' of CLR instantiation on the specific machine, even though the MS docs (http://msdn.microsoft.com/en-us/library/ms231419.aspx) appear to indicate that you'll always get the newest unless you request a specific version. 2. Another add-in in Excel has already (deliberately) instantiated a .NET 1 CLR and Excel can't host more than one. I strongly suspect the second of these but don't know how to prove / fix it. Has anyone seen similar behaviour? Any suggestions on what is going on? A few other notes: * All workstations are running Windows XP SP3 * Excel 2003 SP3 is the only version of Excel in our organisation I can't change either of these so a newer Excel version is not an option.
2011/06/08
[ "https://Stackoverflow.com/questions/6275693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323105/" ]
There are some problems using @import 1. Different browsers treat import differently (Was a problem in older browsers which may not be used now) 2. I guess IE6 and IE7 do not support @media. In link tag you can specify media as screen, print, etc. But IE6 and IE7 do not support @media in CSS. So specifying media types would not be possible in IE6 and IE7 when using @import. 3. Each import would result in a new HTTP request Method 1 does follow Yahoo rules. You may split your CSS into multiple files in Development environment and when deploying to production you can club them together.
best way is to combine all the files, compress them with YUI compressor. you can find detailed help at this [link](http://beardscratchers.com/journal/compressing-css-and-javascript-with-yui-compressor)
13,132,144
for raw PCM data with sampling rate - say Fs - what bit rate or sample rate to use? Can I set WaveFormat sample rate parameter to same as Fs?
2012/10/30
[ "https://Stackoverflow.com/questions/13132144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1784426/" ]
NAudio will calculate the bit rate for you, if you provide sample rate and channels in the WaveFormat constructor with two parameters. (you can also specify bit depth, but this will normally be 16). You can specify any sample rate you like, but if you want to play it easily in Windows, go for a standard value (e.g. 44100, 32000, 48000, 16000).
96 khz and 44.1 kHz are standard audio sampling rates, bit rate will span from 4 to 32 depending on your needs
1,214,132
I was running Ubuntu 18.04 and just converted to Xubuntu. Is there a way to add icons to the desktop? I would like a few to launch programs.
2020/03/01
[ "https://askubuntu.com/questions/1214132", "https://askubuntu.com", "https://askubuntu.com/users/653494/" ]
Right-click on the desktop and choose `Create Launcher` from the context-menu to create custom launchers. You can also choose any program from the application-menu with a right-click and select `Add to Desktop` from the context-menu.
**Creating Desktop shortcut using terminal** You could do it in the next way: ``` ln -s /usr/share/applications/google-chrome.desktop /home/user/Desktop/ ``` But it shows an alert: `Untrusted application launcher` Also, you could create it by creating app.desktop file on your desktop with the next content: ``` vim.tiny ~/Desktop/firefox.desktop [Desktop Entry] Version=1.0 Type=Application Name=Firefox Comment=Browser Exec=firefox Icon=firefox Path=/home/user/.firefox Terminal=false StartupNotify=false chmod +x ~/Desktop/firefox.desktop ```
49,050,425
I'm working on a project which has more than one user type (SuperUser - SchoolAdmin - Teacher) And each role has privilige to see some elements. How do i hide elements depending on the logged user role using \*ngIf? This is the project [link](https://stackblitz.com/edit/angular-vduzzk) on Stack-blitz, i uploaded some of it to guide me with the live preview. Inside app you will find common services >> auth, this is the folder which has login service and authentication guard. Inside models >> enum, you will find user type enum. Inside component sign-in you will find the form which defines user type. Inside routes you will see the expected roles made for each component. Users that i made for testing: This should route you to the school-list Admin (which has super user role): [email protected] Password: 12345 This should route you to the dashboard Student (which has student role): [email protected] Password: 12345 For example is i want to hide element on the dash-board to be only shown to the super user role, how can i do this? I know that there is a way with ngIf but i'm stuck on the right way to write it inside the NgIf, i want examples on my code not a dummy code. Update: issue has been resolved so i deleted the users made for testing.
2018/03/01
[ "https://Stackoverflow.com/questions/49050425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9122537/" ]
In your project, when a user is registering you are asking if he is a 'Teacher', 'Parent' or a 'Student'. So here you have your condition. When you sign-in or register you should save your user data somewhere (in a service for exemple which you can use with [@injection](https://angular.io/guide/dependency-injection). Then with that data you should make some test in your DOM like this: ``` /* if type_id == id(student) */ <div *ngIf="myService.currentUser.type_id"> // your student display ... </div> /* if type_id == id(teacher) */ <div *ngIf="myService.currentUser.type_id"> // your teacher display ... </div> ``` Is this helping you ? You should read this docs [Services](https://angular.io/tutorial/toh-pt4) [Exemple in your case] Your service: ``` import { Injectable } from '@angular/core'; /* other import */ @Injectable() export class UserService { public currentUser: any; constructor(){} public login(loginData: LoginModel): any { const apiUrl: string = environment.apiBaseUrl + '/api/en/users/login'; let promise = new Promise((resolve, reject) => { // this is a promise. learn what is a promise in Javascript. this one is only more structured in TypeScript // a promise is returned to make sure that action is taken only after the response to the api is recieved this.http.post(apiUrl, loginData).subscribe((data: any) => { if(data.status) { var userData = { token: data.token, user:data.user }; this.currentUser = data.user // HERE SAVE YOUR user data return resolve(userData); } else { return reject(data) } }, (err: HttpErrorResponse) => { return reject(err); }); }); return promise; } } ``` Then inject that service in your constructor and your service in Component: ``` // Don't forgot to import UserService !! constructor(public userService: UserService){} ``` DOM: ``` *ngIf="userService.currentUser.type_id == 1" ```
boolean value true or false is used for hiding. In HTML file `<div *ngIf = !test>_contents to be printed_</div>` In .ts file initialize `test = false;` so whenever `this.test = true;` div will show otherwise will be in hide . Check your condition and make the `test = true;`
49,050,425
I'm working on a project which has more than one user type (SuperUser - SchoolAdmin - Teacher) And each role has privilige to see some elements. How do i hide elements depending on the logged user role using \*ngIf? This is the project [link](https://stackblitz.com/edit/angular-vduzzk) on Stack-blitz, i uploaded some of it to guide me with the live preview. Inside app you will find common services >> auth, this is the folder which has login service and authentication guard. Inside models >> enum, you will find user type enum. Inside component sign-in you will find the form which defines user type. Inside routes you will see the expected roles made for each component. Users that i made for testing: This should route you to the school-list Admin (which has super user role): [email protected] Password: 12345 This should route you to the dashboard Student (which has student role): [email protected] Password: 12345 For example is i want to hide element on the dash-board to be only shown to the super user role, how can i do this? I know that there is a way with ngIf but i'm stuck on the right way to write it inside the NgIf, i want examples on my code not a dummy code. Update: issue has been resolved so i deleted the users made for testing.
2018/03/01
[ "https://Stackoverflow.com/questions/49050425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9122537/" ]
In your project, when a user is registering you are asking if he is a 'Teacher', 'Parent' or a 'Student'. So here you have your condition. When you sign-in or register you should save your user data somewhere (in a service for exemple which you can use with [@injection](https://angular.io/guide/dependency-injection). Then with that data you should make some test in your DOM like this: ``` /* if type_id == id(student) */ <div *ngIf="myService.currentUser.type_id"> // your student display ... </div> /* if type_id == id(teacher) */ <div *ngIf="myService.currentUser.type_id"> // your teacher display ... </div> ``` Is this helping you ? You should read this docs [Services](https://angular.io/tutorial/toh-pt4) [Exemple in your case] Your service: ``` import { Injectable } from '@angular/core'; /* other import */ @Injectable() export class UserService { public currentUser: any; constructor(){} public login(loginData: LoginModel): any { const apiUrl: string = environment.apiBaseUrl + '/api/en/users/login'; let promise = new Promise((resolve, reject) => { // this is a promise. learn what is a promise in Javascript. this one is only more structured in TypeScript // a promise is returned to make sure that action is taken only after the response to the api is recieved this.http.post(apiUrl, loginData).subscribe((data: any) => { if(data.status) { var userData = { token: data.token, user:data.user }; this.currentUser = data.user // HERE SAVE YOUR user data return resolve(userData); } else { return reject(data) } }, (err: HttpErrorResponse) => { return reject(err); }); }); return promise; } } ``` Then inject that service in your constructor and your service in Component: ``` // Don't forgot to import UserService !! constructor(public userService: UserService){} ``` DOM: ``` *ngIf="userService.currentUser.type_id == 1" ```
You should do: ``` <div *ngIf="superUserLogged"> // your SuperUser display ... </div> <div *ngIf="schoolAdminLogged"> // your SuperUser display ... </div> <div *ngIf="teacherLogged"> // your SuperUser display ... </div> ``` and in \*.ts file when ever someone logs to system you do: ``` onLogin(userrLogged: string) { this.superUserLogged = false; this.schoolAdminLogged = false; this.teacherLogged = false; switch (userrLogged) { case 'SuperUser': this.superUserLogged = true; break; case 'SchoolAdmin': this.schoolAdminLogged = true; break; case 'Teacher': this.teacherLogged = true; break; } ```
44,685,473
There are tons of questions on passing strings to a javascript function - that's not what I'm asking here. My problem is that I have to pass an integer (a customer ID) as a string to a javascript function from PHP. The reason I have to do this is sometimes a customer ID can have leading zeros, and I do not know how many leading zeros will be needed, so I can't pad or format with leading zeros in javascript. Here's the PHP that calls my function. The $row is a resulting array from an odbc query. ``` parse_str("customerId=" . $row["customerId"], $output); // This is called via AJAX, so returning HTML as response ... echo "<td><input type='checkbox' id='" . $output["customerId"] . "' onclick='disableAccount(" . $row["userAccountId"] . ", " . $output["customerId"] . ");' checked /></td> ``` The above works fine, and correctly passes a string with leading zeros to the funtion. Here's part of that function. ``` function disableAccount(userAccountId, customerId) { // Do stuff here } ``` As an example, I have a customerId of "026608". When the `disableAccount` function is called, the `customerId` parameter is parsed as an integer, which strips the leading zero, and I now have a parameter of '26608'. As I mentioned above, I can't use padding to add a leading zero to the customerId, as there isn't always a leading zero on the customerId. The customerId can also have more than one leading zero. How can I get my function to parse a string, i.e. "026608" as a parameter with the leading zeros? Thanks in advance!
2017/06/21
[ "https://Stackoverflow.com/questions/44685473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3470694/" ]
try to pass/escape the quotes so it gets parsed as string by the js ``` (\"" . $row["userAccountId"] . \"" ```
Great spot by john Smith, also another useful function for leading zeroes (though in this instance, not more efficient than john's) is the [sprintf](http://php.net/manual/en/function.sprintf.php) function. ``` $id = 321; function disableAccount($userAccountId, customerId) { //Result is 000321 $userAccIdWithZeros = sprintf('%06d', $userAccountId); //Rest of your code... } ```
44,685,473
There are tons of questions on passing strings to a javascript function - that's not what I'm asking here. My problem is that I have to pass an integer (a customer ID) as a string to a javascript function from PHP. The reason I have to do this is sometimes a customer ID can have leading zeros, and I do not know how many leading zeros will be needed, so I can't pad or format with leading zeros in javascript. Here's the PHP that calls my function. The $row is a resulting array from an odbc query. ``` parse_str("customerId=" . $row["customerId"], $output); // This is called via AJAX, so returning HTML as response ... echo "<td><input type='checkbox' id='" . $output["customerId"] . "' onclick='disableAccount(" . $row["userAccountId"] . ", " . $output["customerId"] . ");' checked /></td> ``` The above works fine, and correctly passes a string with leading zeros to the funtion. Here's part of that function. ``` function disableAccount(userAccountId, customerId) { // Do stuff here } ``` As an example, I have a customerId of "026608". When the `disableAccount` function is called, the `customerId` parameter is parsed as an integer, which strips the leading zero, and I now have a parameter of '26608'. As I mentioned above, I can't use padding to add a leading zero to the customerId, as there isn't always a leading zero on the customerId. The customerId can also have more than one leading zero. How can I get my function to parse a string, i.e. "026608" as a parameter with the leading zeros? Thanks in advance!
2017/06/21
[ "https://Stackoverflow.com/questions/44685473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3470694/" ]
try to pass/escape the quotes so it gets parsed as string by the js ``` (\"" . $row["userAccountId"] . \"" ```
Use the [heredoc](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc) syntax whenever you produce HTML in PHP, it's more readable: ``` echo <<< _ <td> <input type="checkbox" id="{$output['customerId']}" onclick="disableAccount('{$row['userAccountId']}', this.id);" checked /> </td> _; ``` ... because you don't have to escape your quotes, and you might have spotted your issue at once.
26,822,038
I have a problem in my code. I've been trying to design a form that could update data in a database and showing it without refreshing the page. I could do this, but I wanted that the form would work if the user pressed the Enter key. Here is my code: ``` <form name="chat" id="chat"> <textarea name="message" type="text" id="message" size="63" ></textarea> <input type="button" value="Send" onClick="send();"/> </form> <script> //This function will display the messages function showmessages(){ //Send an XMLHttpRequest to the 'show-message.php' file if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","chat.php?jogo=<?php echo $numerojogo;?>",false); xmlhttp.send(null); } else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.open("GET","chat.php",false); xmlhttp.send(); } //Replace the content of the messages with the response from the 'show-messages.php' file document.getElementById('chatbox').innerHTML = xmlhttp.responseText; //Repeat the function each 30 seconds setTimeout('showmessages()',30000); } //Start the showmessages() function showmessages(); //This function will submit the message function send(){ //Send an XMLHttpRequest to the 'send.php' file with all the required informations~ var sendto = 'adicionar.php?message=' + document.getElementById('message').value + '&jogador=<?php echo $user;?>' + '&jogo=<?php echo $numerojogo;?>'; if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET",sendto,false); xmlhttp.send(null); document.getElementById("chat").reset(); } else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.open("GET",sendto,false); xmlhttp.send(); } var error = ''; //If an error occurs the 'send.php' file send`s the number of the error and based on that number a message is displayed switch(parseInt(xmlhttp.responseText)){ case 1: error = 'The database is down!'; break; case 2: error = 'The database is down!'; break; case 3: error = 'Don`t forget the message!'; break; case 4: error = 'The message is too long!'; break; case 5: error = 'Don`t forget the name!'; break; case 6: error = 'The name is too long!'; break; case 7: error = 'This name is already used by somebody else!'; break; case 8: error = 'The database is down!'; } if(error == ''){ $('input[type=text]').attr('value', ''); showmessages(); } else{ document.getElementById('error').innerHTML = error; } } </script> ``` I've tried to put onsubmit instead of onclick but without success :/ EDIT: Already solved I'm so dumb.. Thank you for the help misko! Here is my code in case you're having the same trouble as me: ``` <form name="chat" id="chat" onsubmit="send();return false;"> <input name="message" type="text" id="message" size="63" ></input> <input type="button" value="Send" onClick="send();"/> </form> ```
2014/11/08
[ "https://Stackoverflow.com/questions/26822038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1085949/" ]
If it works *onclick* I think that *onsubmit* in `<form>` should work too: > > > ``` > <form name="chat" id="chat" onsubmit="send();"> > <textarea name="message" type="text" id="message" size="63" ></textarea> > <input type="button" value="Send" onClick="send();"/> > </form> > > ``` > > Have you tried that this way?
What about this approach. Determines if carriage return has been pressed. (Ascii 13) ``` $(document).ready(function(){ $("form").keydown(function(event){ if(event.which == 13) { event.preventdefault(); // submit } }); }); ```
26,822,038
I have a problem in my code. I've been trying to design a form that could update data in a database and showing it without refreshing the page. I could do this, but I wanted that the form would work if the user pressed the Enter key. Here is my code: ``` <form name="chat" id="chat"> <textarea name="message" type="text" id="message" size="63" ></textarea> <input type="button" value="Send" onClick="send();"/> </form> <script> //This function will display the messages function showmessages(){ //Send an XMLHttpRequest to the 'show-message.php' file if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","chat.php?jogo=<?php echo $numerojogo;?>",false); xmlhttp.send(null); } else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.open("GET","chat.php",false); xmlhttp.send(); } //Replace the content of the messages with the response from the 'show-messages.php' file document.getElementById('chatbox').innerHTML = xmlhttp.responseText; //Repeat the function each 30 seconds setTimeout('showmessages()',30000); } //Start the showmessages() function showmessages(); //This function will submit the message function send(){ //Send an XMLHttpRequest to the 'send.php' file with all the required informations~ var sendto = 'adicionar.php?message=' + document.getElementById('message').value + '&jogador=<?php echo $user;?>' + '&jogo=<?php echo $numerojogo;?>'; if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET",sendto,false); xmlhttp.send(null); document.getElementById("chat").reset(); } else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.open("GET",sendto,false); xmlhttp.send(); } var error = ''; //If an error occurs the 'send.php' file send`s the number of the error and based on that number a message is displayed switch(parseInt(xmlhttp.responseText)){ case 1: error = 'The database is down!'; break; case 2: error = 'The database is down!'; break; case 3: error = 'Don`t forget the message!'; break; case 4: error = 'The message is too long!'; break; case 5: error = 'Don`t forget the name!'; break; case 6: error = 'The name is too long!'; break; case 7: error = 'This name is already used by somebody else!'; break; case 8: error = 'The database is down!'; } if(error == ''){ $('input[type=text]').attr('value', ''); showmessages(); } else{ document.getElementById('error').innerHTML = error; } } </script> ``` I've tried to put onsubmit instead of onclick but without success :/ EDIT: Already solved I'm so dumb.. Thank you for the help misko! Here is my code in case you're having the same trouble as me: ``` <form name="chat" id="chat" onsubmit="send();return false;"> <input name="message" type="text" id="message" size="63" ></input> <input type="button" value="Send" onClick="send();"/> </form> ```
2014/11/08
[ "https://Stackoverflow.com/questions/26822038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1085949/" ]
--- You will need to add an event listener on that input field. See <http://api.jquery.com/keypress/> and my example below. ```js $( "#message" ).keypress(function( event ) { if ( event.which == 13 ) { event.preventDefault(); send(); } }); ```
What about this approach. Determines if carriage return has been pressed. (Ascii 13) ``` $(document).ready(function(){ $("form").keydown(function(event){ if(event.which == 13) { event.preventdefault(); // submit } }); }); ```
38,498,175
I have to write a regex with matches following: * String should start with alphabets - [a-zA-Z] * String can contain alphabets, spaces, numbers, `_` and `-` (underscore and hyphen) * String should not end with `_` or `-` (underscore and hyphen) * Underscore character should not have space before and after. I came up with the following regex, but it doesn't seems to work ``` /^[a-zA-Z0-9]+(\b_|_\b)[a-zA-Z0-9]+$/ ``` **Test case:** ``` HelloWorld // Match Hello_World //Match Hello _World // doesn't match Hello_ World // doesn't match Hello _ World // doesn't match Hello_World_1 // Match He110_W0rld // Match Hello - World // Match Hello-World // Match _HelloWorld // doesn't match Hello_-_World // match ```
2016/07/21
[ "https://Stackoverflow.com/questions/38498175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664047/" ]
What about this? ``` ^[a-zA-Z](\B_\B|[a-zA-Z0-9 -])*[a-zA-Z0-9 ]$ ``` Broken down: ``` ^ [a-zA-Z] allowed characters at beginning ( \B_\B underscore with no word-boundary | or [a-zA-Z0-9 -] other allowed characters )* [a-zA-Z0-9 ] allowed characters at end $ ```
Oh! I love me some regex! Would this work? `/^[a-z]$|^[a-z](?:_(?=[^ ]))?(?:[a-z\d -][^ ]_[^ ])*[a-z\d -]*[^_-]$/i` I was a tad unsure of rule 4--do you mean underscores can have a space before *or* after *or* neither, but not before *and* after?
38,498,175
I have to write a regex with matches following: * String should start with alphabets - [a-zA-Z] * String can contain alphabets, spaces, numbers, `_` and `-` (underscore and hyphen) * String should not end with `_` or `-` (underscore and hyphen) * Underscore character should not have space before and after. I came up with the following regex, but it doesn't seems to work ``` /^[a-zA-Z0-9]+(\b_|_\b)[a-zA-Z0-9]+$/ ``` **Test case:** ``` HelloWorld // Match Hello_World //Match Hello _World // doesn't match Hello_ World // doesn't match Hello _ World // doesn't match Hello_World_1 // Match He110_W0rld // Match Hello - World // Match Hello-World // Match _HelloWorld // doesn't match Hello_-_World // match ```
2016/07/21
[ "https://Stackoverflow.com/questions/38498175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664047/" ]
You may use ``` ^(?!.*(?:[_-]$|_ | _))[a-zA-Z][\w -]*$ ``` See the [regex demo](https://regex101.com/r/eD1uV6/2) *Explanation*: * `^` - start of string * `(?!.*(?:[_-]$|_ | _))` - after some chars (`.*`) there must not appear (`(?!...)`) a `_` or `-` at the end of string (`[_-]$`), nor space+`_` or `_`+space * `[a-zA-Z]` - the first char matched and consumed must be an ASCII letter * `[\w -]*` - 0+ word (`\w` = `[a-zA-Z0-9_]`) chars or space or `-` * `$` - end of string
Oh! I love me some regex! Would this work? `/^[a-z]$|^[a-z](?:_(?=[^ ]))?(?:[a-z\d -][^ ]_[^ ])*[a-z\d -]*[^_-]$/i` I was a tad unsure of rule 4--do you mean underscores can have a space before *or* after *or* neither, but not before *and* after?
38,498,175
I have to write a regex with matches following: * String should start with alphabets - [a-zA-Z] * String can contain alphabets, spaces, numbers, `_` and `-` (underscore and hyphen) * String should not end with `_` or `-` (underscore and hyphen) * Underscore character should not have space before and after. I came up with the following regex, but it doesn't seems to work ``` /^[a-zA-Z0-9]+(\b_|_\b)[a-zA-Z0-9]+$/ ``` **Test case:** ``` HelloWorld // Match Hello_World //Match Hello _World // doesn't match Hello_ World // doesn't match Hello _ World // doesn't match Hello_World_1 // Match He110_W0rld // Match Hello - World // Match Hello-World // Match _HelloWorld // doesn't match Hello_-_World // match ```
2016/07/21
[ "https://Stackoverflow.com/questions/38498175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664047/" ]
You could use this one: ``` ^(?!^[ _-]|.*[ _-]$|.* _|.*_ )[\w -]*$ ``` [regex tester](https://regex101.com/r/rE0tS8/1) For the test cases I used modifier `gm` to match each line individually. If emtpy string should not be considered as acceptable, then change the final `*` to a `+`: ``` ^(?!^[ _-]|.*[ _-]$|.* _|.*_ )[\w -]+$ ``` ### Meaning of each part * `^` and `$` match the beginning/ending of the input * `(?! )`: list of things that should *not* match: + `|`: logical OR + `^[ _-]`: starts with any of these three characters + `.*[ _-]$`: ends with any of these three characters + `.* _`: has space followed by underscore anywhere + `.*_`: has underscore followed by space anywhere * `[\w -]`: any alphanumeric character or underscore (also matched by `\w`) or space or hyphen * `*`: zero or more times * `+`: one or more times
Oh! I love me some regex! Would this work? `/^[a-z]$|^[a-z](?:_(?=[^ ]))?(?:[a-z\d -][^ ]_[^ ])*[a-z\d -]*[^_-]$/i` I was a tad unsure of rule 4--do you mean underscores can have a space before *or* after *or* neither, but not before *and* after?
38,498,175
I have to write a regex with matches following: * String should start with alphabets - [a-zA-Z] * String can contain alphabets, spaces, numbers, `_` and `-` (underscore and hyphen) * String should not end with `_` or `-` (underscore and hyphen) * Underscore character should not have space before and after. I came up with the following regex, but it doesn't seems to work ``` /^[a-zA-Z0-9]+(\b_|_\b)[a-zA-Z0-9]+$/ ``` **Test case:** ``` HelloWorld // Match Hello_World //Match Hello _World // doesn't match Hello_ World // doesn't match Hello _ World // doesn't match Hello_World_1 // Match He110_W0rld // Match Hello - World // Match Hello-World // Match _HelloWorld // doesn't match Hello_-_World // match ```
2016/07/21
[ "https://Stackoverflow.com/questions/38498175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664047/" ]
You may use ``` ^(?!.*(?:[_-]$|_ | _))[a-zA-Z][\w -]*$ ``` See the [regex demo](https://regex101.com/r/eD1uV6/2) *Explanation*: * `^` - start of string * `(?!.*(?:[_-]$|_ | _))` - after some chars (`.*`) there must not appear (`(?!...)`) a `_` or `-` at the end of string (`[_-]$`), nor space+`_` or `_`+space * `[a-zA-Z]` - the first char matched and consumed must be an ASCII letter * `[\w -]*` - 0+ word (`\w` = `[a-zA-Z0-9_]`) chars or space or `-` * `$` - end of string
What about this? ``` ^[a-zA-Z](\B_\B|[a-zA-Z0-9 -])*[a-zA-Z0-9 ]$ ``` Broken down: ``` ^ [a-zA-Z] allowed characters at beginning ( \B_\B underscore with no word-boundary | or [a-zA-Z0-9 -] other allowed characters )* [a-zA-Z0-9 ] allowed characters at end $ ```
38,498,175
I have to write a regex with matches following: * String should start with alphabets - [a-zA-Z] * String can contain alphabets, spaces, numbers, `_` and `-` (underscore and hyphen) * String should not end with `_` or `-` (underscore and hyphen) * Underscore character should not have space before and after. I came up with the following regex, but it doesn't seems to work ``` /^[a-zA-Z0-9]+(\b_|_\b)[a-zA-Z0-9]+$/ ``` **Test case:** ``` HelloWorld // Match Hello_World //Match Hello _World // doesn't match Hello_ World // doesn't match Hello _ World // doesn't match Hello_World_1 // Match He110_W0rld // Match Hello - World // Match Hello-World // Match _HelloWorld // doesn't match Hello_-_World // match ```
2016/07/21
[ "https://Stackoverflow.com/questions/38498175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664047/" ]
You could use this one: ``` ^(?!^[ _-]|.*[ _-]$|.* _|.*_ )[\w -]*$ ``` [regex tester](https://regex101.com/r/rE0tS8/1) For the test cases I used modifier `gm` to match each line individually. If emtpy string should not be considered as acceptable, then change the final `*` to a `+`: ``` ^(?!^[ _-]|.*[ _-]$|.* _|.*_ )[\w -]+$ ``` ### Meaning of each part * `^` and `$` match the beginning/ending of the input * `(?! )`: list of things that should *not* match: + `|`: logical OR + `^[ _-]`: starts with any of these three characters + `.*[ _-]$`: ends with any of these three characters + `.* _`: has space followed by underscore anywhere + `.*_`: has underscore followed by space anywhere * `[\w -]`: any alphanumeric character or underscore (also matched by `\w`) or space or hyphen * `*`: zero or more times * `+`: one or more times
What about this? ``` ^[a-zA-Z](\B_\B|[a-zA-Z0-9 -])*[a-zA-Z0-9 ]$ ``` Broken down: ``` ^ [a-zA-Z] allowed characters at beginning ( \B_\B underscore with no word-boundary | or [a-zA-Z0-9 -] other allowed characters )* [a-zA-Z0-9 ] allowed characters at end $ ```
38,498,175
I have to write a regex with matches following: * String should start with alphabets - [a-zA-Z] * String can contain alphabets, spaces, numbers, `_` and `-` (underscore and hyphen) * String should not end with `_` or `-` (underscore and hyphen) * Underscore character should not have space before and after. I came up with the following regex, but it doesn't seems to work ``` /^[a-zA-Z0-9]+(\b_|_\b)[a-zA-Z0-9]+$/ ``` **Test case:** ``` HelloWorld // Match Hello_World //Match Hello _World // doesn't match Hello_ World // doesn't match Hello _ World // doesn't match Hello_World_1 // Match He110_W0rld // Match Hello - World // Match Hello-World // Match _HelloWorld // doesn't match Hello_-_World // match ```
2016/07/21
[ "https://Stackoverflow.com/questions/38498175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/664047/" ]
You may use ``` ^(?!.*(?:[_-]$|_ | _))[a-zA-Z][\w -]*$ ``` See the [regex demo](https://regex101.com/r/eD1uV6/2) *Explanation*: * `^` - start of string * `(?!.*(?:[_-]$|_ | _))` - after some chars (`.*`) there must not appear (`(?!...)`) a `_` or `-` at the end of string (`[_-]$`), nor space+`_` or `_`+space * `[a-zA-Z]` - the first char matched and consumed must be an ASCII letter * `[\w -]*` - 0+ word (`\w` = `[a-zA-Z0-9_]`) chars or space or `-` * `$` - end of string
You could use this one: ``` ^(?!^[ _-]|.*[ _-]$|.* _|.*_ )[\w -]*$ ``` [regex tester](https://regex101.com/r/rE0tS8/1) For the test cases I used modifier `gm` to match each line individually. If emtpy string should not be considered as acceptable, then change the final `*` to a `+`: ``` ^(?!^[ _-]|.*[ _-]$|.* _|.*_ )[\w -]+$ ``` ### Meaning of each part * `^` and `$` match the beginning/ending of the input * `(?! )`: list of things that should *not* match: + `|`: logical OR + `^[ _-]`: starts with any of these three characters + `.*[ _-]$`: ends with any of these three characters + `.* _`: has space followed by underscore anywhere + `.*_`: has underscore followed by space anywhere * `[\w -]`: any alphanumeric character or underscore (also matched by `\w`) or space or hyphen * `*`: zero or more times * `+`: one or more times
1,946,817
The question is to show > > $(∑\_{i=1}^n |x\_i | )^p≥∑\_{i=1}^n |x\_i |^p $ for $p\ge1$ , or in plain words, the sum's power is no less than the sum of powers if the power is no less than 1. > > > It is best that it can be proved using Holder's inequality or any other commonly used inequalities like Minkowski’s inequality. Do not use measure theory (for this is a super-easy special case of Lp norm on counting measure), do not take derivative. Also do not use the monotonicity of p-norm, because the purpose of this claim is to prove the monotonicity. The above claim is a special case that vector 1-norm is larger than any vector p-norm. I try to prove this as an effort to prove the monotonicity of p-norm using common inequalities but not taking derivative (see [For vector p-norm, can we prove it is decreasing without using derivative?](https://math.stackexchange.com/questions/1946511/for-vector-p-norm-can-we-prove-it-is-decreasing-without-using-derivative)). If the above can be proved, then the monotonicity can be proved by Holder's inequality as the following, > > [![enter image description here](https://i.stack.imgur.com/GZ074.png)](https://i.stack.imgur.com/GZ074.png) > > > where the second inequality uses above result when moving the power $p+1-q$ outside of the brackets.
2016/09/29
[ "https://math.stackexchange.com/questions/1946817", "https://math.stackexchange.com", "https://math.stackexchange.com/users/181974/" ]
The essential fact needed here is that a recursive definition like that of $F\_n$ can be replaced by an equivalent explicit definition. Specifically, the Fibonacci sequence $W=\{\langle k,F\_k\rangle:k\in\mathbb N\}$ can be defined as the set of all those ordered pairs $\langle k,x\rangle$ such that there exists a function $f$ with the following properties: (1) the domain of $f$ is $\{0,1,\dots,k\}$ (known in set theory as $k+1$), (2) $f(0)=1$, (3) if $k\geq1$ then $f(1)=1$, (4) for all $j$ such that $2\leq j\leq k$, $f(j)=f(j-1)+f(j-2)$, and (5) $f(k)=x$. In view of this explicit definition, we can prove the existence of $W$ by applying the separation axiom (also called subset axiom, Aussonderung, and comprehension axiom) of ZF to the set $\mathbb N\times\mathbb N$. And once we have $W$, we get the desired $S$ as the range of $W$, i.e., as the set of second components of the ordered pairs in $W$.
It does make sense. Define $S\_n = \{ F\_0, F\_1, F\_2, \dots, F\_n \}$. (I think you'll agree that this set exists for every $n$.) Then let $$S = \bigcup\_{n \in \mathbb{N}} S\_n$$ Since each $S\_n$ exists, and $\mathbb{N}$ certainly exists, the union does as well (we have an axiom, the Axiom of Unions, to tell us that).
42,181,045
I have something like this: ``` A //branch 1 \ B - C //branch 2 \ D //branch 3 ``` And I would like to get something like this: ``` A - E //branch_1 \ B' - C' //branch_2 \ D' //branch_3 ``` I would like to perform a command and rebase all branches at once, so I don't have to rebase them one by one. Is this possible?
2017/02/11
[ "https://Stackoverflow.com/questions/42181045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675615/" ]
Short answer: no, it's not possible ... but you *can* minimize the amount of work you have to do. Long answer on minimizing work follows. The key to understanding this is that Git's branch *names*—the names `branch_1`, `branch_2`, and `branch_3` in your example—are merely identifiers that "point to" one specific commit. It's the commits themselves that form the actual branches. For details, see [What exactly do we mean by "branch"?](https://stackoverflow.com/q/25068543/1256452) Meanwhile, what `git rebase` does is to *copy* some commits, with the new copies normally being made on a new base (hence "re-base"). In your particular case, there's only one *chain of commits* that requires copying. That's the `B--C--D` chain. If we strip off all the labels (branch names) we can draw the graph fragment this way: ``` A--E \ B--C--D ``` Your task is to copy `B--C--D` to `B'--C'--D'`, which are like `B` through `D` but come after `E` instead of coming after `A`. I'll put them on top so that we can keep the original `B--C--D` chain in the picture too: ``` B'-C'-D' / A--E \ B--C--D ``` Once you've made the copies, you can then change the *labels* so that they point to the copies, rather than pointing to the originals; and now we need to move `D'` up so that we can point `branch_2` to `C'`: ``` D' <-- branch_3 / B'-C' <-- branch_2 / A--E <-- branch_1 ``` This takes a minimum of two Git commands to accomplish: 1. `git rebase`, to copy `B-C-D` to `B'-C'-D'` and move `branch_3` to point to `D'`. Normally this would be two commands: ``` git checkout branch_3 && git rebase branch_1 ``` but you can actually do this with one Git command as `git rebase` has the option of doing the initial `git checkout`: ``` git rebase branch_1 branch_3 ``` 2. `git branch -f`, to re-point `branch_2`. We know (from our careful graph drawing that showed us that we could do a single `git rebase` of `branch_3` to copy all the commits) that `branch_2` points to the commit "one step back" from the commit to which `branch_3` points. That is, at the start, `branch_2` names commit `C` and `branch_3` names commit `D`. Hence, once we're all done, `branch_2` needs to name commit `C'`. Since it *was* one step back from the tip of the old `branch_3`, it must be one step back from the tip of the new `branch_3` afterward.1 So now that we have done the `rebase` and have the `B'-C'-D'` chain, we simply direct Git to move the label `branch_2` to point one step back from wherever `branch_3` points: ``` git branch -f branch_2 branch_3~1 ``` Thus, for this case, it takes at least two Git commands (three if you prefer a separate `git checkout`). Note that there are cases where more or different commands are required, even if we are moving / copying just two branch names. For instance, if we started with: ``` F--J <-- br1 \ G--H--K <-- br2 \ I <-- br3 ``` and wanted to copy all of `G-H-(K;I)`, we cannot do this with one `git rebase` command. What we *can* do is rebase either `br2` or `br3` first, copying three of the four commits; then use `git rebase --onto <target> <upstream> <branch>` with the remaining branch, to copy the one remaining commit. (In fact, though, `git rebase --onto` is the most general form: we can always do the entire job with just a series of `git rebase --onto <target> <upstream> <branch>` commands, one per branch. This is because `git rebase` really does *two* things: (1) copy some set of commits, possibly empty; (2) move a branch label a la `git branch -f`. The copied set is determined from the result of `<upstream>..HEAD`—see [`gitrevisions`](https://www.kernel.org/pub/software/scm/git/docs/gitrevisions.html) and footnote 1 below—and with the copy location being set by `--onto`; and the branch's destination is wherever `HEAD` winds up after doing the copying. If the to-copy set is empty, `HEAD` winds up right at the `--onto` target. So it *seems* like a simple(ish) script could do all the work ... but see footnote 1.) --- 1This assumes, however, that `git rebase` actually winds up copying *all* the commits. (The safety level of this assumption varies a lot depending on the rebase in question.) In fact, while the initial set of commits to copy is determined by running `git rev-list --no-merges <upstream>..HEAD`—or its equivalent, really—that initial set is immediately further whittled-down by computing the `git patch-id` for each commit in both the "to copy" and "don't need to copy because now will be upstream" ranges. That is, instead of `<upstream>..HEAD`, the rebase code uses `<upstream>...HEAD` combined with `--right-only --cherry-pick`.2 So we omit not just merge commits, but also commits that are already upstream. We could write a script that does this ourselves, so that we can locate the relative position of each branch-name in the set of branches we wish to rebase. (I did most of this as an experiment some time ago.) But there is another problem: during the cherry-picking process, it's possible that some commits will become empty due to conflict resolution, and you will `git rebase --skip` them. This *changes* the relative position of the remaining copied commits. What this means in the end is that unless `git rebase` is augmented a bit, to record which commits map to which new commits and which commits were dropped entirely, it's impossible to make a completely-correct, completely-reliable multi-rebase script. I think one could get sufficiently close, without modifying Git itself, using the `HEAD` reflog: this would only go awry if someone starts this kind of complex rebase, but then in the middle of it, does some `git reset --soft`s and the like and then resumes the rebase. 2This is literally true for some forms of `git rebase` and not for others. The code to generate the list varies depends on whether you're using `--interactive` and/or `--keep-empty` and/or `--preserve-merges`. A [non-interactive `git am` based rebase](https://github.com/git/git/blob/master/git-rebase--am.sh) uses: ``` if test -n "$keep_empty" then # we have to do this the hard way. git format-patch completely squashes # empty commits and even if it didn't the format doesn't really lend # itself well to recording empty patches. fortunately, cherry-pick # makes this easy git cherry-pick ${gpg_sign_opt:+"$gpg_sign_opt"} --allow-empty \ --right-only "$revisions" \ ${restrict_revision+^$restrict_revision} ret=$? else rm -f "$GIT_DIR/rebased-patches" git format-patch -k --stdout --full-index --cherry-pick --right-only \ --src-prefix=a/ --dst-prefix=b/ --no-renames --no-cover-letter \ "$revisions" ${restrict_revision+^$restrict_revision} \ >"$GIT_DIR/rebased-patches" ret=$? [snip] git am $git_am_opt --rebasing --resolvemsg="$resolvemsg" \ ${gpg_sign_opt:+"$gpg_sign_opt"} <"$GIT_DIR/rebased-patches" ret=$? [snip] ``` The `--cherry-pick --right-only` are passed through whichever command is used (cherry-pick or format-patch) to the `git rev-list` code, so that it can get the right-hand-side list of commit IDs, with "pre-picked cherries" removed, from the symmetric difference. Interactive rebase is considerably more complicated (!).
In order to at least find out *which branches* you will have to update after the initial rebase, you can run ``` $ git branch --contains <commit A> ```
42,181,045
I have something like this: ``` A //branch 1 \ B - C //branch 2 \ D //branch 3 ``` And I would like to get something like this: ``` A - E //branch_1 \ B' - C' //branch_2 \ D' //branch_3 ``` I would like to perform a command and rebase all branches at once, so I don't have to rebase them one by one. Is this possible?
2017/02/11
[ "https://Stackoverflow.com/questions/42181045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675615/" ]
Short answer: no, it's not possible ... but you *can* minimize the amount of work you have to do. Long answer on minimizing work follows. The key to understanding this is that Git's branch *names*—the names `branch_1`, `branch_2`, and `branch_3` in your example—are merely identifiers that "point to" one specific commit. It's the commits themselves that form the actual branches. For details, see [What exactly do we mean by "branch"?](https://stackoverflow.com/q/25068543/1256452) Meanwhile, what `git rebase` does is to *copy* some commits, with the new copies normally being made on a new base (hence "re-base"). In your particular case, there's only one *chain of commits* that requires copying. That's the `B--C--D` chain. If we strip off all the labels (branch names) we can draw the graph fragment this way: ``` A--E \ B--C--D ``` Your task is to copy `B--C--D` to `B'--C'--D'`, which are like `B` through `D` but come after `E` instead of coming after `A`. I'll put them on top so that we can keep the original `B--C--D` chain in the picture too: ``` B'-C'-D' / A--E \ B--C--D ``` Once you've made the copies, you can then change the *labels* so that they point to the copies, rather than pointing to the originals; and now we need to move `D'` up so that we can point `branch_2` to `C'`: ``` D' <-- branch_3 / B'-C' <-- branch_2 / A--E <-- branch_1 ``` This takes a minimum of two Git commands to accomplish: 1. `git rebase`, to copy `B-C-D` to `B'-C'-D'` and move `branch_3` to point to `D'`. Normally this would be two commands: ``` git checkout branch_3 && git rebase branch_1 ``` but you can actually do this with one Git command as `git rebase` has the option of doing the initial `git checkout`: ``` git rebase branch_1 branch_3 ``` 2. `git branch -f`, to re-point `branch_2`. We know (from our careful graph drawing that showed us that we could do a single `git rebase` of `branch_3` to copy all the commits) that `branch_2` points to the commit "one step back" from the commit to which `branch_3` points. That is, at the start, `branch_2` names commit `C` and `branch_3` names commit `D`. Hence, once we're all done, `branch_2` needs to name commit `C'`. Since it *was* one step back from the tip of the old `branch_3`, it must be one step back from the tip of the new `branch_3` afterward.1 So now that we have done the `rebase` and have the `B'-C'-D'` chain, we simply direct Git to move the label `branch_2` to point one step back from wherever `branch_3` points: ``` git branch -f branch_2 branch_3~1 ``` Thus, for this case, it takes at least two Git commands (three if you prefer a separate `git checkout`). Note that there are cases where more or different commands are required, even if we are moving / copying just two branch names. For instance, if we started with: ``` F--J <-- br1 \ G--H--K <-- br2 \ I <-- br3 ``` and wanted to copy all of `G-H-(K;I)`, we cannot do this with one `git rebase` command. What we *can* do is rebase either `br2` or `br3` first, copying three of the four commits; then use `git rebase --onto <target> <upstream> <branch>` with the remaining branch, to copy the one remaining commit. (In fact, though, `git rebase --onto` is the most general form: we can always do the entire job with just a series of `git rebase --onto <target> <upstream> <branch>` commands, one per branch. This is because `git rebase` really does *two* things: (1) copy some set of commits, possibly empty; (2) move a branch label a la `git branch -f`. The copied set is determined from the result of `<upstream>..HEAD`—see [`gitrevisions`](https://www.kernel.org/pub/software/scm/git/docs/gitrevisions.html) and footnote 1 below—and with the copy location being set by `--onto`; and the branch's destination is wherever `HEAD` winds up after doing the copying. If the to-copy set is empty, `HEAD` winds up right at the `--onto` target. So it *seems* like a simple(ish) script could do all the work ... but see footnote 1.) --- 1This assumes, however, that `git rebase` actually winds up copying *all* the commits. (The safety level of this assumption varies a lot depending on the rebase in question.) In fact, while the initial set of commits to copy is determined by running `git rev-list --no-merges <upstream>..HEAD`—or its equivalent, really—that initial set is immediately further whittled-down by computing the `git patch-id` for each commit in both the "to copy" and "don't need to copy because now will be upstream" ranges. That is, instead of `<upstream>..HEAD`, the rebase code uses `<upstream>...HEAD` combined with `--right-only --cherry-pick`.2 So we omit not just merge commits, but also commits that are already upstream. We could write a script that does this ourselves, so that we can locate the relative position of each branch-name in the set of branches we wish to rebase. (I did most of this as an experiment some time ago.) But there is another problem: during the cherry-picking process, it's possible that some commits will become empty due to conflict resolution, and you will `git rebase --skip` them. This *changes* the relative position of the remaining copied commits. What this means in the end is that unless `git rebase` is augmented a bit, to record which commits map to which new commits and which commits were dropped entirely, it's impossible to make a completely-correct, completely-reliable multi-rebase script. I think one could get sufficiently close, without modifying Git itself, using the `HEAD` reflog: this would only go awry if someone starts this kind of complex rebase, but then in the middle of it, does some `git reset --soft`s and the like and then resumes the rebase. 2This is literally true for some forms of `git rebase` and not for others. The code to generate the list varies depends on whether you're using `--interactive` and/or `--keep-empty` and/or `--preserve-merges`. A [non-interactive `git am` based rebase](https://github.com/git/git/blob/master/git-rebase--am.sh) uses: ``` if test -n "$keep_empty" then # we have to do this the hard way. git format-patch completely squashes # empty commits and even if it didn't the format doesn't really lend # itself well to recording empty patches. fortunately, cherry-pick # makes this easy git cherry-pick ${gpg_sign_opt:+"$gpg_sign_opt"} --allow-empty \ --right-only "$revisions" \ ${restrict_revision+^$restrict_revision} ret=$? else rm -f "$GIT_DIR/rebased-patches" git format-patch -k --stdout --full-index --cherry-pick --right-only \ --src-prefix=a/ --dst-prefix=b/ --no-renames --no-cover-letter \ "$revisions" ${restrict_revision+^$restrict_revision} \ >"$GIT_DIR/rebased-patches" ret=$? [snip] git am $git_am_opt --rebasing --resolvemsg="$resolvemsg" \ ${gpg_sign_opt:+"$gpg_sign_opt"} <"$GIT_DIR/rebased-patches" ret=$? [snip] ``` The `--cherry-pick --right-only` are passed through whichever command is used (cherry-pick or format-patch) to the `git rev-list` code, so that it can get the right-hand-side list of commit IDs, with "pre-picked cherries" removed, from the symmetric difference. Interactive rebase is considerably more complicated (!).
This question is a superset of [How do I rebase a chain of local git branches?](https://stackoverflow.com/questions/20834648/how-do-i-rebase-a-chain-of-local-git-branches/58864534#58864534) The solution I am using today is a tool called [git-chain](https://github.com/Shopify/git-chain) which aims to solve this problem. In your example, you can specify a chain ``` git chain setup -c myfeature branch1 branch2 branch3 ``` Once this chain is set up, you can make new commits to `branch1` and then run `git chain rebase -c myfeature` and the tool figures out all the refs and rebases everything nicely for you. As an added benefit, it also calculates and handles any amendments or new commits to `branch1`, `branch2`, and `branch3`.
42,181,045
I have something like this: ``` A //branch 1 \ B - C //branch 2 \ D //branch 3 ``` And I would like to get something like this: ``` A - E //branch_1 \ B' - C' //branch_2 \ D' //branch_3 ``` I would like to perform a command and rebase all branches at once, so I don't have to rebase them one by one. Is this possible?
2017/02/11
[ "https://Stackoverflow.com/questions/42181045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675615/" ]
Short answer: no, it's not possible ... but you *can* minimize the amount of work you have to do. Long answer on minimizing work follows. The key to understanding this is that Git's branch *names*—the names `branch_1`, `branch_2`, and `branch_3` in your example—are merely identifiers that "point to" one specific commit. It's the commits themselves that form the actual branches. For details, see [What exactly do we mean by "branch"?](https://stackoverflow.com/q/25068543/1256452) Meanwhile, what `git rebase` does is to *copy* some commits, with the new copies normally being made on a new base (hence "re-base"). In your particular case, there's only one *chain of commits* that requires copying. That's the `B--C--D` chain. If we strip off all the labels (branch names) we can draw the graph fragment this way: ``` A--E \ B--C--D ``` Your task is to copy `B--C--D` to `B'--C'--D'`, which are like `B` through `D` but come after `E` instead of coming after `A`. I'll put them on top so that we can keep the original `B--C--D` chain in the picture too: ``` B'-C'-D' / A--E \ B--C--D ``` Once you've made the copies, you can then change the *labels* so that they point to the copies, rather than pointing to the originals; and now we need to move `D'` up so that we can point `branch_2` to `C'`: ``` D' <-- branch_3 / B'-C' <-- branch_2 / A--E <-- branch_1 ``` This takes a minimum of two Git commands to accomplish: 1. `git rebase`, to copy `B-C-D` to `B'-C'-D'` and move `branch_3` to point to `D'`. Normally this would be two commands: ``` git checkout branch_3 && git rebase branch_1 ``` but you can actually do this with one Git command as `git rebase` has the option of doing the initial `git checkout`: ``` git rebase branch_1 branch_3 ``` 2. `git branch -f`, to re-point `branch_2`. We know (from our careful graph drawing that showed us that we could do a single `git rebase` of `branch_3` to copy all the commits) that `branch_2` points to the commit "one step back" from the commit to which `branch_3` points. That is, at the start, `branch_2` names commit `C` and `branch_3` names commit `D`. Hence, once we're all done, `branch_2` needs to name commit `C'`. Since it *was* one step back from the tip of the old `branch_3`, it must be one step back from the tip of the new `branch_3` afterward.1 So now that we have done the `rebase` and have the `B'-C'-D'` chain, we simply direct Git to move the label `branch_2` to point one step back from wherever `branch_3` points: ``` git branch -f branch_2 branch_3~1 ``` Thus, for this case, it takes at least two Git commands (three if you prefer a separate `git checkout`). Note that there are cases where more or different commands are required, even if we are moving / copying just two branch names. For instance, if we started with: ``` F--J <-- br1 \ G--H--K <-- br2 \ I <-- br3 ``` and wanted to copy all of `G-H-(K;I)`, we cannot do this with one `git rebase` command. What we *can* do is rebase either `br2` or `br3` first, copying three of the four commits; then use `git rebase --onto <target> <upstream> <branch>` with the remaining branch, to copy the one remaining commit. (In fact, though, `git rebase --onto` is the most general form: we can always do the entire job with just a series of `git rebase --onto <target> <upstream> <branch>` commands, one per branch. This is because `git rebase` really does *two* things: (1) copy some set of commits, possibly empty; (2) move a branch label a la `git branch -f`. The copied set is determined from the result of `<upstream>..HEAD`—see [`gitrevisions`](https://www.kernel.org/pub/software/scm/git/docs/gitrevisions.html) and footnote 1 below—and with the copy location being set by `--onto`; and the branch's destination is wherever `HEAD` winds up after doing the copying. If the to-copy set is empty, `HEAD` winds up right at the `--onto` target. So it *seems* like a simple(ish) script could do all the work ... but see footnote 1.) --- 1This assumes, however, that `git rebase` actually winds up copying *all* the commits. (The safety level of this assumption varies a lot depending on the rebase in question.) In fact, while the initial set of commits to copy is determined by running `git rev-list --no-merges <upstream>..HEAD`—or its equivalent, really—that initial set is immediately further whittled-down by computing the `git patch-id` for each commit in both the "to copy" and "don't need to copy because now will be upstream" ranges. That is, instead of `<upstream>..HEAD`, the rebase code uses `<upstream>...HEAD` combined with `--right-only --cherry-pick`.2 So we omit not just merge commits, but also commits that are already upstream. We could write a script that does this ourselves, so that we can locate the relative position of each branch-name in the set of branches we wish to rebase. (I did most of this as an experiment some time ago.) But there is another problem: during the cherry-picking process, it's possible that some commits will become empty due to conflict resolution, and you will `git rebase --skip` them. This *changes* the relative position of the remaining copied commits. What this means in the end is that unless `git rebase` is augmented a bit, to record which commits map to which new commits and which commits were dropped entirely, it's impossible to make a completely-correct, completely-reliable multi-rebase script. I think one could get sufficiently close, without modifying Git itself, using the `HEAD` reflog: this would only go awry if someone starts this kind of complex rebase, but then in the middle of it, does some `git reset --soft`s and the like and then resumes the rebase. 2This is literally true for some forms of `git rebase` and not for others. The code to generate the list varies depends on whether you're using `--interactive` and/or `--keep-empty` and/or `--preserve-merges`. A [non-interactive `git am` based rebase](https://github.com/git/git/blob/master/git-rebase--am.sh) uses: ``` if test -n "$keep_empty" then # we have to do this the hard way. git format-patch completely squashes # empty commits and even if it didn't the format doesn't really lend # itself well to recording empty patches. fortunately, cherry-pick # makes this easy git cherry-pick ${gpg_sign_opt:+"$gpg_sign_opt"} --allow-empty \ --right-only "$revisions" \ ${restrict_revision+^$restrict_revision} ret=$? else rm -f "$GIT_DIR/rebased-patches" git format-patch -k --stdout --full-index --cherry-pick --right-only \ --src-prefix=a/ --dst-prefix=b/ --no-renames --no-cover-letter \ "$revisions" ${restrict_revision+^$restrict_revision} \ >"$GIT_DIR/rebased-patches" ret=$? [snip] git am $git_am_opt --rebasing --resolvemsg="$resolvemsg" \ ${gpg_sign_opt:+"$gpg_sign_opt"} <"$GIT_DIR/rebased-patches" ret=$? [snip] ``` The `--cherry-pick --right-only` are passed through whichever command is used (cherry-pick or format-patch) to the `git rev-list` code, so that it can get the right-hand-side list of commit IDs, with "pre-picked cherries" removed, from the symmetric difference. Interactive rebase is considerably more complicated (!).
The git-branchless suite of tools can neatly solve this problem: ``` $ git checkout branch1 $ git commit -m 'E' $ git move -s B -d branch1 # the above is the same as the following, # because `branch1` is already checked out: $ git move -s B # or, if you want to address branches instead of commits # (this will also move all descendant commits/branches): $ git move -b branch2 -d branch1 ``` Disclaimer: I'm the author. See the [documentation for `git move`](https://github.com/arxanas/git-branchless/wiki/Command:-git-move).
42,181,045
I have something like this: ``` A //branch 1 \ B - C //branch 2 \ D //branch 3 ``` And I would like to get something like this: ``` A - E //branch_1 \ B' - C' //branch_2 \ D' //branch_3 ``` I would like to perform a command and rebase all branches at once, so I don't have to rebase them one by one. Is this possible?
2017/02/11
[ "https://Stackoverflow.com/questions/42181045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675615/" ]
This question is a superset of [How do I rebase a chain of local git branches?](https://stackoverflow.com/questions/20834648/how-do-i-rebase-a-chain-of-local-git-branches/58864534#58864534) The solution I am using today is a tool called [git-chain](https://github.com/Shopify/git-chain) which aims to solve this problem. In your example, you can specify a chain ``` git chain setup -c myfeature branch1 branch2 branch3 ``` Once this chain is set up, you can make new commits to `branch1` and then run `git chain rebase -c myfeature` and the tool figures out all the refs and rebases everything nicely for you. As an added benefit, it also calculates and handles any amendments or new commits to `branch1`, `branch2`, and `branch3`.
In order to at least find out *which branches* you will have to update after the initial rebase, you can run ``` $ git branch --contains <commit A> ```
42,181,045
I have something like this: ``` A //branch 1 \ B - C //branch 2 \ D //branch 3 ``` And I would like to get something like this: ``` A - E //branch_1 \ B' - C' //branch_2 \ D' //branch_3 ``` I would like to perform a command and rebase all branches at once, so I don't have to rebase them one by one. Is this possible?
2017/02/11
[ "https://Stackoverflow.com/questions/42181045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675615/" ]
This question is a superset of [How do I rebase a chain of local git branches?](https://stackoverflow.com/questions/20834648/how-do-i-rebase-a-chain-of-local-git-branches/58864534#58864534) The solution I am using today is a tool called [git-chain](https://github.com/Shopify/git-chain) which aims to solve this problem. In your example, you can specify a chain ``` git chain setup -c myfeature branch1 branch2 branch3 ``` Once this chain is set up, you can make new commits to `branch1` and then run `git chain rebase -c myfeature` and the tool figures out all the refs and rebases everything nicely for you. As an added benefit, it also calculates and handles any amendments or new commits to `branch1`, `branch2`, and `branch3`.
The git-branchless suite of tools can neatly solve this problem: ``` $ git checkout branch1 $ git commit -m 'E' $ git move -s B -d branch1 # the above is the same as the following, # because `branch1` is already checked out: $ git move -s B # or, if you want to address branches instead of commits # (this will also move all descendant commits/branches): $ git move -b branch2 -d branch1 ``` Disclaimer: I'm the author. See the [documentation for `git move`](https://github.com/arxanas/git-branchless/wiki/Command:-git-move).
33,352,386
i have this following code: ``` for ( int i = 0 ; i < 100 ; i++) for (int j = 0 ; j < 80 ; j ++) { ... } ``` i splitted it to 8 threads. ``` pthread_t thread1, thread2,thread3,thread4,thread5,thread6,thread7,thread8; int rc1,rc2,rc3,rc4,rc5,rc6,rc7,rc8; struct threads { ... } void *PrintHello(void *args) { for (int j = 0 ; j < 10 ; j ++) { } } for ( int i = 0 i < 100 ; i ++) { rc1 = pthread_create(&thread1, NULL,PrintHello,threads);, pthread_join(thread1,NULL); rc2 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread2,NULL); rc3 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread3,NULL); rc4 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread4,NULL); rc5 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread5,NULL); rc6 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread6,NULL); rc7 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread7,NULL); rc8 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread8,NULL); } ``` i think, second one should be faster than first one .But, second one behaves like that there is only one thread.In other words, The code that is not splitted and the code that is splitted run in same time. why do they have same run time, while second one has 8 thread, first one has one thread? thanks in advance.
2015/10/26
[ "https://Stackoverflow.com/questions/33352386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2921443/" ]
`pthread_join(thread1,NULL);` is going to halt execution of the main thread until `thread1` finishes. You need to move all of the `pthread_join`s to after you construct all of the threads so they can all run concurrently. You are also using `thread1` for every `pthread_create(&thread1, NULL,PrintHello,threads);`. You need to use the other threads as well ``` for (int i = 0 i < 100; i++) { rc1 = pthread_create(&thread1, NULL, PrintHello, threads); rc2 = pthread_create(&thread2, NULL, PrintHello, threads); rc3 = pthread_create(&thread3, NULL, PrintHello, threads); rc4 = pthread_create(&thread4, NULL, PrintHello, threads); rc5 = pthread_create(&thread5, NULL, PrintHello, threads); rc6 = pthread_create(&thread6, NULL, PrintHello, threads); rc7 = pthread_create(&thread7, NULL, PrintHello, threads); rc8 = pthread_create(&thread8, NULL, PrintHello, threads); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); pthread_join(thread4, NULL); pthread_join(thread5, NULL); pthread_join(thread6, NULL); pthread_join(thread7, NULL); pthread_join(thread8, NULL); } ```
Besides of what @NathanOliver said, keep in mind that spawning a thread comes at a significant cost, so whatever work you intend the threads to do, it has to be more costly than the penalty you get for actually spawning all these threads. So if your `PrintHello` method actually does exactly that, you will probably still see a performance degradation versus the single threaded version. The usual way these costs are offset is to spawn a finite amount of thread at the very beginning and divide work as it becomes available among them. Also, last but not least, if your `PrintHello` method actually does only that, ie `printf("Hello\n")` or similar, you will most likely not see a performance improvement no matter what, as `printf()` will most likely take a shared lock which will see huge contention with all of your threads repeatedly trying to take it. The bottom line is, multithreading is great to improve performance, but it's not trivial. Most of the time just throwing threads at your code is not going to improve your performance at all, and in the worst case will actually degrade it. If you want to see speed ups, you should profile your code and look out for big tasks of work that can be easily divided among several works that can all work independently on a part of the result. Those kinds of work can very easily be multithreaded and can see a increased throughput over single threaded code.
33,352,386
i have this following code: ``` for ( int i = 0 ; i < 100 ; i++) for (int j = 0 ; j < 80 ; j ++) { ... } ``` i splitted it to 8 threads. ``` pthread_t thread1, thread2,thread3,thread4,thread5,thread6,thread7,thread8; int rc1,rc2,rc3,rc4,rc5,rc6,rc7,rc8; struct threads { ... } void *PrintHello(void *args) { for (int j = 0 ; j < 10 ; j ++) { } } for ( int i = 0 i < 100 ; i ++) { rc1 = pthread_create(&thread1, NULL,PrintHello,threads);, pthread_join(thread1,NULL); rc2 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread2,NULL); rc3 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread3,NULL); rc4 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread4,NULL); rc5 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread5,NULL); rc6 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread6,NULL); rc7 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread7,NULL); rc8 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread8,NULL); } ``` i think, second one should be faster than first one .But, second one behaves like that there is only one thread.In other words, The code that is not splitted and the code that is splitted run in same time. why do they have same run time, while second one has 8 thread, first one has one thread? thanks in advance.
2015/10/26
[ "https://Stackoverflow.com/questions/33352386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2921443/" ]
`pthread_join(thread1,NULL);` is going to halt execution of the main thread until `thread1` finishes. You need to move all of the `pthread_join`s to after you construct all of the threads so they can all run concurrently. You are also using `thread1` for every `pthread_create(&thread1, NULL,PrintHello,threads);`. You need to use the other threads as well ``` for (int i = 0 i < 100; i++) { rc1 = pthread_create(&thread1, NULL, PrintHello, threads); rc2 = pthread_create(&thread2, NULL, PrintHello, threads); rc3 = pthread_create(&thread3, NULL, PrintHello, threads); rc4 = pthread_create(&thread4, NULL, PrintHello, threads); rc5 = pthread_create(&thread5, NULL, PrintHello, threads); rc6 = pthread_create(&thread6, NULL, PrintHello, threads); rc7 = pthread_create(&thread7, NULL, PrintHello, threads); rc8 = pthread_create(&thread8, NULL, PrintHello, threads); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); pthread_join(thread4, NULL); pthread_join(thread5, NULL); pthread_join(thread6, NULL); pthread_join(thread7, NULL); pthread_join(thread8, NULL); } ```
Additionally to @NathanOliver and @JustSid it is not really great to define 8 threads separatly and write 8 times the same code if they all do the same work. Much better to use something like ``` pthread_t threadlist[8]; int results[8]; ``` To initialize it a simple for loop will do. ``` for(int i = 0; i < 8; i++) results[i] = pthread_create(&threadlist[i], NULL, PrintHello, threads); ``` And start the threads with ``` for(int i = 0; i < 8; i++) pthread_join(threadlist[i], NULL); ``` This reduces the code much. Maybe there are *really* slightly changes in runtime but a for loop with an int are only a few more assembler commands. I do not know if this is even measurable.
33,352,386
i have this following code: ``` for ( int i = 0 ; i < 100 ; i++) for (int j = 0 ; j < 80 ; j ++) { ... } ``` i splitted it to 8 threads. ``` pthread_t thread1, thread2,thread3,thread4,thread5,thread6,thread7,thread8; int rc1,rc2,rc3,rc4,rc5,rc6,rc7,rc8; struct threads { ... } void *PrintHello(void *args) { for (int j = 0 ; j < 10 ; j ++) { } } for ( int i = 0 i < 100 ; i ++) { rc1 = pthread_create(&thread1, NULL,PrintHello,threads);, pthread_join(thread1,NULL); rc2 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread2,NULL); rc3 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread3,NULL); rc4 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread4,NULL); rc5 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread5,NULL); rc6 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread6,NULL); rc7 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread7,NULL); rc8 = pthread_create(&thread1, NULL,PrintHello,threads); pthread_join(thread8,NULL); } ``` i think, second one should be faster than first one .But, second one behaves like that there is only one thread.In other words, The code that is not splitted and the code that is splitted run in same time. why do they have same run time, while second one has 8 thread, first one has one thread? thanks in advance.
2015/10/26
[ "https://Stackoverflow.com/questions/33352386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2921443/" ]
Besides of what @NathanOliver said, keep in mind that spawning a thread comes at a significant cost, so whatever work you intend the threads to do, it has to be more costly than the penalty you get for actually spawning all these threads. So if your `PrintHello` method actually does exactly that, you will probably still see a performance degradation versus the single threaded version. The usual way these costs are offset is to spawn a finite amount of thread at the very beginning and divide work as it becomes available among them. Also, last but not least, if your `PrintHello` method actually does only that, ie `printf("Hello\n")` or similar, you will most likely not see a performance improvement no matter what, as `printf()` will most likely take a shared lock which will see huge contention with all of your threads repeatedly trying to take it. The bottom line is, multithreading is great to improve performance, but it's not trivial. Most of the time just throwing threads at your code is not going to improve your performance at all, and in the worst case will actually degrade it. If you want to see speed ups, you should profile your code and look out for big tasks of work that can be easily divided among several works that can all work independently on a part of the result. Those kinds of work can very easily be multithreaded and can see a increased throughput over single threaded code.
Additionally to @NathanOliver and @JustSid it is not really great to define 8 threads separatly and write 8 times the same code if they all do the same work. Much better to use something like ``` pthread_t threadlist[8]; int results[8]; ``` To initialize it a simple for loop will do. ``` for(int i = 0; i < 8; i++) results[i] = pthread_create(&threadlist[i], NULL, PrintHello, threads); ``` And start the threads with ``` for(int i = 0; i < 8; i++) pthread_join(threadlist[i], NULL); ``` This reduces the code much. Maybe there are *really* slightly changes in runtime but a for loop with an int are only a few more assembler commands. I do not know if this is even measurable.
49,649,080
I am currently coding an autocompletion component in Javascript which completes two input fields `plz` (postal code) and `ort` (city) based on postal code. The autocomplete fires as soon as you have entered 3 digits. Now sadly many postal codes in Germany do not work as identifiers - several small cities can all have the same postal code. To try my code, please type `562` ===== in the input labelled **PLZ**. An autosuggest list opens which holds a maximum of 10 items which can be visible at once. Use `↓` to go down the list. I need a solution for the problem that the currently *active* item does not cause the list to scroll when you navigate it using `↓` or `↑`. If anyone could point me in the right direction here, I'd be more than glad to implement it myself. ```js let plz = [{"plz":"56244","ort":"Rückeroth","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ötzingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Niedersayn","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Vielbach","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Hartenfels","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ewighausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Leuterod","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Kuhnhöfen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Goddert","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Freirachdorf","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Maxsain","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Freilingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Weidenhahn","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Helferskirchen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Arnshöfen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Hahn am See","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Sessenhausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Wölferlingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Steinen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Schenkelberg","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Krümmel","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ettinghausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"}] let plzAutoCompleteConfig = { minCharactersToRun: 3, maxResults: 100, allowedKeyCodes: [8, 9, 13, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105] } let plzOrtAutoComplete = function plzOrtAutoComplete() { if (!document.querySelector('[data-has-plz-ort-autocomplete]')) return; // find all plz autocompletes let autocompletes = Array.from(document.querySelectorAll('[data-has-plz-ort-autocomplete]')) for (let autocomplete of autocompletes) { let plzInput = document.getElementById(autocomplete.getAttribute('data-plz')) let ortInput = document.getElementById(autocomplete.getAttribute('data-ort')) let suggestList = document.createElement('ul') suggestList.flush = function() { this.innerHTML = '' } suggestList.className = 'autocomplete-suggest list-unstyled' plzInput.parentNode.appendChild(suggestList) for (let eventName of ['input', 'focus']) { plzInput.addEventListener(eventName, function(evt) { const checkInput = () => { let matches = plz.filter(x => { return x.plz.startsWith(this.value) }) switch (true) { case (matches.length > plzAutoCompleteConfig.maxResults): suggestList.flush() break case ((matches.length <= plzAutoCompleteConfig.maxResults && matches.length > 1) || (matches.length === 1 && this.value.length < 5)): suggestList.flush() for (let match of matches) { let li = document.createElement('li') li.textContent = `${match.plz} ${match.ort}` li.title = `${match.plz} ${match.ort} in ${match.bundesland}, ${match.kreis} übernehmen durch Enter oder Klick` li.addEventListener('click', () => { plzInput.value = match.plz ortInput.value = match.ort ortInput.focus() suggestList.flush() }) li.addEventListener('mouseenter', function() { this.classList.add('active') }) li.addEventListener('mouseleave', function() { this.classList.remove('active') }) suggestList.appendChild(li) } this.parentNode.appendChild(suggestList) break case (matches.length === 1 && this.value.length === 5): if (event.type !== 'focus' && ['deleteContentBackward', 'deleteContentForward'].indexOf(evt.inputType) === -1) { suggestList.flush() plzInput.value = matches[0].plz ortInput.value = matches[0].ort ortInput.focus() } break default: { suggestList.flush() break } } } if (isNaN(Number(this.value))) { this.value = '' return } if (this.value.length >= plzAutoCompleteConfig.minCharactersToRun) { if (['deleteContentBackward', 'deleteContentForward'].indexOf(evt.inputType) > -1) { console.log(this.value) } checkInput() } }) } plzInput.addEventListener('keydown', function(evt) { let keyCode = evt.keyCode || evt.which; let activeLi = suggestList.querySelector('li.active') if (keyCode) { if (!plzAutoCompleteConfig.allowedKeyCodes.includes(keyCode)) { evt.preventDefault() } else { switch (keyCode) { case 8: // backspace suggestList.flush() break case 13: // Enter evt.preventDefault() if (!suggestList.hasChildNodes()) { return } if (!activeLi) { return } else { plzInput.value = activeLi.textContent.substr(0, 5) ortInput.value = activeLi.textContent.substr(6) suggestList.flush() ortInput.focus() } break case 37: break case 38: // cursor up if (!suggestList.hasChildNodes()) { return } if (activeLi) { activeLi.classList.remove('active') let prevLi = activeLi.previousSibling if (prevLi) { prevLi.classList.add('active') } else { suggestList.querySelector('li:last-of-type').classList.add('active') } } else { suggestList.querySelector('li:last-of-type').classList.add('active') } break case 39: break case 40: if (!suggestList.hasChildNodes()) { return } if (activeLi) { activeLi.classList.remove('active') let nextLi = activeLi.nextSibling if (nextLi) { nextLi.classList.add('active') } else { suggestList.querySelector('li:first-of-type').classList.add('active') } } else { suggestList.querySelector('li:first-of-type').classList.add('active') } break case 46: // delete suggestList.flush() break default: break } } } }) plzInput.addEventListener('blur', function(evt) { setTimeout(function() { suggestList.flush() }, 250) }) ortInput.addEventListener('input', function(evt) { console.log(this.value) }) } } plzOrtAutoComplete(); ``` ```css .autocomplete-suggest { background-color: #fff; border: 1px solid #ddd; box-shadow: 3px 3px 5px #ccc; max-height: 6em; left: 5px; opacity: 1; overflow-y: auto; pointer-events: all; position: absolute; z-index: 999; transition-duration: .2s; } .autocomplete-suggest:empty { max-height: 0; opacity: 0; pointer-events: none; } .autocomplete-suggest li { line-height: 1.5em; margin: 0 auto; padding: .3em 1.2em .2em .6em; transition: all .2s ease-in-out; white-space: nowrap; } .autocomplete-suggest li:nth-child(even) { background-color: rgba(0, 0, 0, 0.05); } .autocomplete-suggest li:hover, .autocomplete-suggest li.active { cursor: pointer; background-color: #a00; color: #fff; } ``` ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <div class="form-row" data-has-plz-ort-autocomplete data-plz="eazVersicherterPLZ" data-ort="eazVersicherterOrt"> <div class="form-group col-sm-4"> <label for="eazVersicherterPLZ">PLZ</label> <input class="form-control" type="text" id="eazVersicherterPLZ" name="eazVersicherterPLZ" data-plz="eazVersicherterOrt" maxlength=5 /> </div> <div class="form-group col-sm-8"> <label for="eazVersicherterOrt">Ort</label> <input class="form-control" type="text" id="eazVersicherterOrt" name="eazVersicherterOrt"> </div> </div> ``` This is the autosuggest HTML being generated by the Javascript: ``` <ul class="autocomplete-suggest list-unstyled"> <li>56244 Rückeroth</li> <li>56244 Ötzingen</li> <li>56244 Niedersayn</li> <li>56244 Vielbach</li> <li>56244 Hartenfels</li> <li>56244 Ewighausen</li> <li>56244 Leuterod</li> <li>56244 Kuhnhöfen</li> <li>56244 Goddert</li> <li>56244 Freirachdorf</li> <li>56244 Maxsain</li> <li>56244 Freilingen</li> <li>56244 Weidenhahn</li> <li>56244 Helferskirchen</li> <li>56244 Arnshöfen</li> <li>56244 Hahn am See</li> <li>56244 Sessenhausen</li> <li>56244 Wölferlingen</li> <li>56244 Steinen</li> <li>56244 Schenkelberg</li> <li>56244 Krümmel</li> <li>56244 Ettinghausen</li> </ul> ```
2018/04/04
[ "https://Stackoverflow.com/questions/49649080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3744304/" ]
I would simply add this on cursor up and cursor down at the end: ``` suggestList.scrollTop = suggestList.querySelector('.active').offsetTop; ``` It will make the list scroll with the active element. Full code: ```js let plz = [{"plz":"56244","ort":"Rückeroth","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ötzingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Niedersayn","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Vielbach","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Hartenfels","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ewighausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Leuterod","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Kuhnhöfen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Goddert","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Freirachdorf","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Maxsain","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Freilingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Weidenhahn","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Helferskirchen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Arnshöfen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Hahn am See","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Sessenhausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Wölferlingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Steinen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Schenkelberg","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Krümmel","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ettinghausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"}] let plzAutoCompleteConfig = { minCharactersToRun: 3, maxResults: 100, allowedKeyCodes: [8, 9, 13, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105] } let plzOrtAutoComplete = function plzOrtAutoComplete() { if (!document.querySelector('[data-has-plz-ort-autocomplete]')) return; // find all plz autocompletes let autocompletes = Array.from(document.querySelectorAll('[data-has-plz-ort-autocomplete]')) for (let autocomplete of autocompletes) { let plzInput = document.getElementById(autocomplete.getAttribute('data-plz')) let ortInput = document.getElementById(autocomplete.getAttribute('data-ort')) let suggestList = document.createElement('ul') suggestList.flush = function() { this.innerHTML = '' } suggestList.className = 'autocomplete-suggest list-unstyled' plzInput.parentNode.appendChild(suggestList) for (let eventName of ['input', 'focus']) { plzInput.addEventListener(eventName, function(evt) { const checkInput = () => { let matches = plz.filter(x => { return x.plz.startsWith(this.value) }) switch (true) { case (matches.length > plzAutoCompleteConfig.maxResults): suggestList.flush() break case ((matches.length <= plzAutoCompleteConfig.maxResults && matches.length > 1) || (matches.length === 1 && this.value.length < 5)): suggestList.flush() for (let match of matches) { let li = document.createElement('li') li.textContent = `${match.plz} ${match.ort}` li.title = `${match.plz} ${match.ort} in ${match.bundesland}, ${match.kreis} übernehmen durch Enter oder Klick` li.addEventListener('click', () => { plzInput.value = match.plz ortInput.value = match.ort ortInput.focus() suggestList.flush() }) li.addEventListener('mouseenter', function() { this.classList.add('active') }) li.addEventListener('mouseleave', function() { this.classList.remove('active') }) suggestList.appendChild(li) } this.parentNode.appendChild(suggestList) break case (matches.length === 1 && this.value.length === 5): if (event.type !== 'focus' && ['deleteContentBackward', 'deleteContentForward'].indexOf(evt.inputType) === -1) { suggestList.flush() plzInput.value = matches[0].plz ortInput.value = matches[0].ort ortInput.focus() } break default: { suggestList.flush() break } } } if (isNaN(Number(this.value))) { this.value = '' return } if (this.value.length >= plzAutoCompleteConfig.minCharactersToRun) { if (['deleteContentBackward', 'deleteContentForward'].indexOf(evt.inputType) > -1) { console.log(this.value) } checkInput() } }) } plzInput.addEventListener('keydown', function(evt) { let keyCode = evt.keyCode || evt.which; let activeLi = suggestList.querySelector('li.active') if (keyCode) { if (!plzAutoCompleteConfig.allowedKeyCodes.includes(keyCode)) { evt.preventDefault() } else { switch (keyCode) { case 8: // backspace suggestList.flush() break case 13: // Enter evt.preventDefault() if (!suggestList.hasChildNodes()) { return } if (!activeLi) { return } else { plzInput.value = activeLi.textContent.substr(0, 5) ortInput.value = activeLi.textContent.substr(6) suggestList.flush() ortInput.focus() } break case 37: break case 38: // cursor up if (!suggestList.hasChildNodes()) { return } if (activeLi) { activeLi.classList.remove('active') let prevLi = activeLi.previousSibling if (prevLi) { prevLi.classList.add('active') } else { suggestList.querySelector('li:last-of-type').classList.add('active') } } else { suggestList.querySelector('li:last-of-type').classList.add('active') } /*code addedd*/ suggestList.scrollTop = suggestList.querySelector('.active').offsetTop; break case 39: break case 40: //cursor down if (!suggestList.hasChildNodes()) { return } if (activeLi) { activeLi.classList.remove('active') let nextLi = activeLi.nextSibling if (nextLi) { nextLi.classList.add('active') } else { suggestList.querySelector('li:first-of-type').classList.add('active') } } else { suggestList.querySelector('li:first-of-type').classList.add('active') } /*added code*/ suggestList.scrollTop = suggestList.querySelector('.active').offsetTop; break case 46: // delete suggestList.flush() break default: break } } } }) plzInput.addEventListener('blur', function(evt) { setTimeout(function() { suggestList.flush() }, 250) }) ortInput.addEventListener('input', function(evt) { console.log(this.value) }) } } plzOrtAutoComplete(); ``` ```css .autocomplete-suggest { background-color: #fff; border: 1px solid #ddd; box-shadow: 3px 3px 5px #ccc; max-height: 20em; left: 5px; opacity: 1; overflow-y: auto; pointer-events: all; position: absolute; z-index: 999; transition-duration: .2s; } .autocomplete-suggest:empty { max-height: 0; opacity: 0; pointer-events: none; } .autocomplete-suggest li { line-height: 1.5em; margin: 0 auto; padding: .3em 1.2em .2em .6em; transition: all .2s ease-in-out; white-space: nowrap; } .autocomplete-suggest li:nth-child(even) { background-color: rgba(0, 0, 0, 0.05); } .autocomplete-suggest li:hover, .autocomplete-suggest li.active { cursor: pointer; background-color: #a00; color: #fff; } ``` ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <div class="form-row" data-has-plz-ort-autocomplete data-plz="eazVersicherterPLZ" data-ort="eazVersicherterOrt"> <div class="form-group col-md-4"> <label for="eazVersicherterPLZ">PLZ</label> <input class="form-control" type="text" id="eazVersicherterPLZ" name="eazVersicherterPLZ" data-plz="eazVersicherterOrt" maxlength=5 /> </div> <div class="form-group col-md-8"> <label for="eazVersicherterOrt">Ort</label> <input class="form-control" type="text" id="eazVersicherterOrt" name="eazVersicherterOrt"> </div> </div> ``` You can also play with some offset if you don't want the active element to be always on the top: ``` suggestList.scrollTop = suggestList.querySelector('.active').offsetTop - x; ``` You can adjust the `x` value to make the active element on bottom, middle or keep it at the top. ```js let plz = [{"plz":"56244","ort":"Rückeroth","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ötzingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Niedersayn","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Vielbach","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Hartenfels","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ewighausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Leuterod","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Kuhnhöfen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Goddert","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Freirachdorf","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Maxsain","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Freilingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Weidenhahn","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Helferskirchen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Arnshöfen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Hahn am See","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Sessenhausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Wölferlingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Steinen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Schenkelberg","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Krümmel","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ettinghausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"}] let plzAutoCompleteConfig = { minCharactersToRun: 3, maxResults: 100, allowedKeyCodes: [8, 9, 13, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105] } let plzOrtAutoComplete = function plzOrtAutoComplete() { if (!document.querySelector('[data-has-plz-ort-autocomplete]')) return; // find all plz autocompletes let autocompletes = Array.from(document.querySelectorAll('[data-has-plz-ort-autocomplete]')) for (let autocomplete of autocompletes) { let plzInput = document.getElementById(autocomplete.getAttribute('data-plz')) let ortInput = document.getElementById(autocomplete.getAttribute('data-ort')) let suggestList = document.createElement('ul') suggestList.flush = function() { this.innerHTML = '' } suggestList.className = 'autocomplete-suggest list-unstyled' plzInput.parentNode.appendChild(suggestList) for (let eventName of ['input', 'focus']) { plzInput.addEventListener(eventName, function(evt) { const checkInput = () => { let matches = plz.filter(x => { return x.plz.startsWith(this.value) }) switch (true) { case (matches.length > plzAutoCompleteConfig.maxResults): suggestList.flush() break case ((matches.length <= plzAutoCompleteConfig.maxResults && matches.length > 1) || (matches.length === 1 && this.value.length < 5)): suggestList.flush() for (let match of matches) { let li = document.createElement('li') li.textContent = `${match.plz} ${match.ort}` li.title = `${match.plz} ${match.ort} in ${match.bundesland}, ${match.kreis} übernehmen durch Enter oder Klick` li.addEventListener('click', () => { plzInput.value = match.plz ortInput.value = match.ort ortInput.focus() suggestList.flush() }) li.addEventListener('mouseenter', function() { this.classList.add('active') }) li.addEventListener('mouseleave', function() { this.classList.remove('active') }) suggestList.appendChild(li) } this.parentNode.appendChild(suggestList) break case (matches.length === 1 && this.value.length === 5): if (event.type !== 'focus' && ['deleteContentBackward', 'deleteContentForward'].indexOf(evt.inputType) === -1) { suggestList.flush() plzInput.value = matches[0].plz ortInput.value = matches[0].ort ortInput.focus() } break default: { suggestList.flush() break } } } if (isNaN(Number(this.value))) { this.value = '' return } if (this.value.length >= plzAutoCompleteConfig.minCharactersToRun) { if (['deleteContentBackward', 'deleteContentForward'].indexOf(evt.inputType) > -1) { console.log(this.value) } checkInput() } }) } plzInput.addEventListener('keydown', function(evt) { let keyCode = evt.keyCode || evt.which; let activeLi = suggestList.querySelector('li.active') if (keyCode) { if (!plzAutoCompleteConfig.allowedKeyCodes.includes(keyCode)) { evt.preventDefault() } else { switch (keyCode) { case 8: // backspace suggestList.flush() break case 13: // Enter evt.preventDefault() if (!suggestList.hasChildNodes()) { return } if (!activeLi) { return } else { plzInput.value = activeLi.textContent.substr(0, 5) ortInput.value = activeLi.textContent.substr(6) suggestList.flush() ortInput.focus() } break case 37: break case 38: // cursor up if (!suggestList.hasChildNodes()) { return } if (activeLi) { activeLi.classList.remove('active') let prevLi = activeLi.previousSibling if (prevLi) { prevLi.classList.add('active') } else { suggestList.querySelector('li:last-of-type').classList.add('active') } } else { suggestList.querySelector('li:last-of-type').classList.add('active') } /*code addedd*/ suggestList.scrollTop = suggestList.querySelector('.active').offsetTop - 100; break case 39: break case 40: //cursor down if (!suggestList.hasChildNodes()) { return } if (activeLi) { activeLi.classList.remove('active') let nextLi = activeLi.nextSibling if (nextLi) { nextLi.classList.add('active') } else { suggestList.querySelector('li:first-of-type').classList.add('active') } } else { suggestList.querySelector('li:first-of-type').classList.add('active') } /*added code*/ suggestList.scrollTop = suggestList.querySelector('.active').offsetTop - 100; break case 46: // delete suggestList.flush() break default: break } } } }) plzInput.addEventListener('blur', function(evt) { setTimeout(function() { suggestList.flush() }, 250) }) ortInput.addEventListener('input', function(evt) { console.log(this.value) }) } } plzOrtAutoComplete(); ``` ```css .autocomplete-suggest { background-color: #fff; border: 1px solid #ddd; box-shadow: 3px 3px 5px #ccc; max-height: 20em; left: 5px; opacity: 1; overflow-y: auto; pointer-events: all; position: absolute; z-index: 999; transition-duration: .2s; } .autocomplete-suggest:empty { max-height: 0; opacity: 0; pointer-events: none; } .autocomplete-suggest li { line-height: 1.5em; margin: 0 auto; padding: .3em 1.2em .2em .6em; transition: all .2s ease-in-out; white-space: nowrap; } .autocomplete-suggest li:nth-child(even) { background-color: rgba(0, 0, 0, 0.05); } .autocomplete-suggest li:hover, .autocomplete-suggest li.active { cursor: pointer; background-color: #a00; color: #fff; } ``` ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <div class="form-row" data-has-plz-ort-autocomplete data-plz="eazVersicherterPLZ" data-ort="eazVersicherterOrt"> <div class="form-group col-md-4"> <label for="eazVersicherterPLZ">PLZ</label> <input class="form-control" type="text" id="eazVersicherterPLZ" name="eazVersicherterPLZ" data-plz="eazVersicherterOrt" maxlength=5 /> </div> <div class="form-group col-md-8"> <label for="eazVersicherterOrt">Ort</label> <input class="form-control" type="text" id="eazVersicherterOrt" name="eazVersicherterOrt"> </div> </div> ```
For those interested, here's how I ended up implementing it: ```js let plz = [{"plz":"56244","ort":"Rückeroth","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ötzingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Niedersayn","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Vielbach","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Hartenfels","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ewighausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Leuterod","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Kuhnhöfen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Goddert","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Freirachdorf","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Maxsain","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Freilingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Weidenhahn","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Helferskirchen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Arnshöfen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Hahn am See","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Sessenhausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Wölferlingen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Steinen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Schenkelberg","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Krümmel","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"},{"plz":"56244","ort":"Ettinghausen","bundesland":"Rheinland-Pfalz","kreis":"Westerwaldkreis"}] let plzAutoCompleteConfig = { minCharactersToRun: 3, maxResults: 100, allowedKeyCodes: [8, 9, 13, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105] } let plzOrtAutoComplete = function plzOrtAutoComplete() { if (!document.querySelector('[data-has-plz-ort-autocomplete]')) return; // find all plz autocompletes let autocompletes = Array.from(document.querySelectorAll('[data-has-plz-ort-autocomplete]')) for (let autocomplete of autocompletes) { let plzInput = document.getElementById(autocomplete.getAttribute('data-plz')) let ortInput = document.getElementById(autocomplete.getAttribute('data-ort')) let suggestList = document.createElement('ul') suggestList.flush = function() { this.innerHTML = '' } suggestList.className = 'autocomplete-suggest list-unstyled' plzInput.parentNode.appendChild(suggestList) for (let eventName of ['input', 'focus']) { plzInput.addEventListener(eventName, function(evt) { const checkInput = () => { let matches = plz.filter(x => { return x.plz.startsWith(this.value) }) switch(true) { case(matches.length > plzAutoCompleteConfig.maxResults): suggestList.flush() break case((matches.length <= plzAutoCompleteConfig.maxResults && matches.length > 1) || (matches.length === 1 && this.value.length < 5)): suggestList.flush() for (let match of matches) { let li = document.createElement('li') li.textContent = `${match.plz} ${match.ort}` li.title = `${match.plz} ${match.ort} in ${match.bundesland}, ${match.kreis} übernehmen durch Enter oder Klick` li.addEventListener('click', () => { plzInput.value = match.plz ortInput.value = match.ort ortInput.focus() suggestList.flush() }) li.addEventListener('mouseenter', function() { this.classList.add('active') }) li.addEventListener('mouseleave', function() { this.classList.remove('active') }) suggestList.appendChild(li) } this.parentNode.appendChild(suggestList) break case(matches.length === 1 && this.value.length === 5): if (event.type !== 'focus' && ['deleteContentBackward', 'deleteContentForward'].indexOf(evt.inputType) === -1) { suggestList.flush() plzInput.value = matches[0].plz ortInput.value = matches[0].ort ortInput.focus() } break default: { suggestList.flush() break } } } if (isNaN(Number(this.value))) { this.value = '' return } if (this.value.length >= plzAutoCompleteConfig.minCharactersToRun) { if (['deleteContentBackward', 'deleteContentForward'].indexOf(evt.inputType) > -1) { console.log(this.value) } checkInput() } }) } plzInput.addEventListener('keydown', function(evt) { let keyCode = evt.keyCode || evt.which; let activeLi = suggestList.querySelector('.active') if (keyCode) { if (!plzAutoCompleteConfig.allowedKeyCodes.includes(keyCode)) { evt.preventDefault() } else { switch (keyCode) { case 8: // backspace suggestList.flush() break case 13: // Enter evt.preventDefault() if (!suggestList.hasChildNodes()) { return } if (!activeLi) { return } else { plzInput.value = activeLi.textContent.substr(0,5) ortInput.value = activeLi.textContent.substr(6) suggestList.flush() ortInput.focus() } break case 37: break case 38: // cursor up if (!suggestList.hasChildNodes()) { return } for (let item of Array.from(suggestList.querySelectorAll('li'))) { if (item !== activeLi) { item.classList.remove('active') } } if (activeLi) { activeLi.classList.remove('active') let prevLi = activeLi.previousSibling || suggestList.querySelector('li:last-of-type') if (prevLi) { prevLi.classList.add('active') if (prevLi.offsetTop < suggestList.scrollTop || prevLi.offsetTop > suggestList.scrollTop + suggestList.getBoundingClientRect().height) { suggestList.scrollTop = prevLi.offsetTop } } } break case 39: break case 40: // cursor down if (!suggestList.hasChildNodes()) { return } for (let item of Array.from(suggestList.querySelectorAll('li'))) { if (item !== activeLi) { item.classList.remove('active') } } if (activeLi) { activeLi.classList.remove('active') let nextLi = activeLi.nextSibling || suggestList.querySelector('li:first-of-type') if (nextLi) { activeLi.classList.remove('active') nextLi.classList.add('active') if (nextLi.offsetTop < suggestList.scrollTop || nextLi.offsetTop > suggestList.scrollTop + suggestList.getBoundingClientRect().height - 32) { suggestList.scrollTop = nextLi.offsetTop - suggestList.getBoundingClientRect().height + 32 } } } else { suggestList.querySelector('li:first-of-type').classList.add('active') } break case 46: // delete suggestList.flush() break default: break } } } }) plzInput.addEventListener('blur', function(evt) { setTimeout(function() { suggestList.flush() }, 200500) }) ortInput.addEventListener('input', function(evt) { console.log(this.value) }) } } plzOrtAutoComplete(); ``` ```css .autocomplete-suggest { background-color: #fff; border: 1px solid #ddd; box-shadow: 3px 3px 5px #ccc; max-height: 6em; left: 5px; opacity: 1; overflow-y: auto; pointer-events: all; position: absolute; z-index: 999; transition-duration: .2s; } .autocomplete-suggest:empty { max-height: 0; opacity: 0; pointer-events: none; } .autocomplete-suggest li { line-height: 1.5em; margin: 0 auto; padding: .3em 1.2em .2em .6em; white-space: nowrap; } .autocomplete-suggest li:hover, .autocomplete-suggest li.active { cursor: pointer; background-color: #a00; color: #fff; } ``` ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <div class="form-row" data-has-plz-ort-autocomplete data-plz="eazVersicherterPLZ" data-ort="eazVersicherterOrt"> <div class="form-group col-sm-4"> <label for="eazVersicherterPLZ">PLZ</label> <input class="form-control" type="text" id="eazVersicherterPLZ" name="eazVersicherterPLZ" data-plz="eazVersicherterOrt" maxlength=5 /> </div> <div class="form-group col-sm-8"> <label for="eazVersicherterOrt">Ort</label> <input class="form-control" type="text" id="eazVersicherterOrt" name="eazVersicherterOrt"> </div> </div> ```
8,522
My mom and I have kept in touch with my ex's parents, mostly his mom "Suzanne" and grandma. So we wanted and decided to send a Christmas card. My mom also wanted to make something for Suzanne, which she thought she would appreciate. (My mom is into crafts and is really good at sewing). She also wanted to send grandma a little something, a pair of earrings. It didn't cost her much because we have a friend who makes jewelry. Now my mom asked me (her English isn't as good as mine) to send Suzanne an email, telling her to expect a package before Christmas and to let us know when she received it. I did. And then I get two emails. The first email was to let me know the package was received and that they couldn't wait to open it on Christmas day. They were thankful and excited blah blah... Then I get nothing on Christmas day which I thought was strange and then I finally get an email two days later, saying that they still haven't opened the package. The reason given was that Suzanne basically felt or somehow guessed from the size of the package that not everyone would be getting a gift and not knowing who would and who would not, (she also didn't want grandma to get upset if she didn't get a gift) decided that the package should be opened some other time, not when the whole family was around. I was like "Why make it such a big deal...at least the card was addressed to everyone..." but alright. And this is the last I heard from Suzanne. I'm really curious if Suzanne finally opened the package and if she gave grandma the gift and if she liked the gift my mom made her so I would like to send an email asking about it. However, I'm not quite sure how to approach the fact that the package wasn't opened for the reasons mentioned and perhaps even apologize for not sending everyone gifts. It might be useful to know that when we lived in the US my mom would bring everyone in the family gifts on Christmas day but this time she wasn't able to. My mom is also upset that mailing gifts sometimes costs more than the gift itself, which doesn't make mailing larger packages a good idea, unless you got money to waste. So my question is, **how to tell Suzanne that we weren't able to get something for everyone this Christmas and to apologize if this made her uncomfortable in any way without sounding awkward.** I had warned my mom this would be awkward and told her we should have sent a little something for everyone or a gift for the house instead but she didn't want to spend more money and perhaps didn't plan it right to begin with.
2017/12/28
[ "https://interpersonal.stackexchange.com/questions/8522", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/4084/" ]
You don't owe Suzanne an explanation or an apology. The ball is in Suzanne's court. You sent a gift, she should send a thank you note. I would not email to ask if she enjoyed the gifts since you know that she received them. If you do decide to email, you don't need to bring up the delay in opening the package or that you didn't provide gifts for everyone.
First of all, I'd just let it drop in this case. I don't see any good way to ask about it here without causing awkwardness. I mean, if there were high stakes, I'd probably suggest something that would only be a little bit awkward, but here, it seems different. Suzanne should absolutely make sure to thank you, obviously, and I hope she thinks to particularly send thanks for the work and care that went into the gift from your mom. That's just basic thoughtfulness. I think, if I were in her position, I would probably also not open the package in front of everybody, just thinking about how my family does presents and trying to imagine it. If "everybody" just includes adults, it could go either way. The only thing I'd say for sure is that, if there are kids involved, you should make sure to send them something. It can be one thing for all of them or very small gifts, but it'll just keep Christmas running smoothly for the recipients. Ultimately, I'd say it sounds like the whole situation was just a minor mismatch in expectations between you two. I'm sure they appreciated the gifts or, if they haven't opened the package yet, they've got some (possibly convoluted) reason why. In a week or two, you could possibly add a little line to an email but it depends so much on your relationship and how you ask. But I think this is just one of those things that happens sometimes.
8,522
My mom and I have kept in touch with my ex's parents, mostly his mom "Suzanne" and grandma. So we wanted and decided to send a Christmas card. My mom also wanted to make something for Suzanne, which she thought she would appreciate. (My mom is into crafts and is really good at sewing). She also wanted to send grandma a little something, a pair of earrings. It didn't cost her much because we have a friend who makes jewelry. Now my mom asked me (her English isn't as good as mine) to send Suzanne an email, telling her to expect a package before Christmas and to let us know when she received it. I did. And then I get two emails. The first email was to let me know the package was received and that they couldn't wait to open it on Christmas day. They were thankful and excited blah blah... Then I get nothing on Christmas day which I thought was strange and then I finally get an email two days later, saying that they still haven't opened the package. The reason given was that Suzanne basically felt or somehow guessed from the size of the package that not everyone would be getting a gift and not knowing who would and who would not, (she also didn't want grandma to get upset if she didn't get a gift) decided that the package should be opened some other time, not when the whole family was around. I was like "Why make it such a big deal...at least the card was addressed to everyone..." but alright. And this is the last I heard from Suzanne. I'm really curious if Suzanne finally opened the package and if she gave grandma the gift and if she liked the gift my mom made her so I would like to send an email asking about it. However, I'm not quite sure how to approach the fact that the package wasn't opened for the reasons mentioned and perhaps even apologize for not sending everyone gifts. It might be useful to know that when we lived in the US my mom would bring everyone in the family gifts on Christmas day but this time she wasn't able to. My mom is also upset that mailing gifts sometimes costs more than the gift itself, which doesn't make mailing larger packages a good idea, unless you got money to waste. So my question is, **how to tell Suzanne that we weren't able to get something for everyone this Christmas and to apologize if this made her uncomfortable in any way without sounding awkward.** I had warned my mom this would be awkward and told her we should have sent a little something for everyone or a gift for the house instead but she didn't want to spend more money and perhaps didn't plan it right to begin with.
2017/12/28
[ "https://interpersonal.stackexchange.com/questions/8522", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/4084/" ]
You don't owe Suzanne an explanation or an apology. The ball is in Suzanne's court. You sent a gift, she should send a thank you note. I would not email to ask if she enjoyed the gifts since you know that she received them. If you do decide to email, you don't need to bring up the delay in opening the package or that you didn't provide gifts for everyone.
A gift is a gift. That means, it is given freely, not on a basis of an obligation. You don't owe anyone a gift. If someone thinks you owe him a gift, it is his problem not yours. So you don't owe any explanation, let alone apology to anyone for not having given them a gift. And not to open the package in order that someone else did not feel bad that they did not receive anything is just incredibly oversensitive, in my opinion. How strange and selfish folk! They should rejoice that someone they love has received a gift and is glad, and not envy him or feel hurt that they did not get anything. The implied or assumed obligation "to give to everyone" is a most silly thing that is destroying the beauty of giving and receiving gifts (as, apparently, in this case). So, in my opinion you did everything right. It is understandable that you would like to know if they liked their gifts, but again: a gift is a gift. It is meant to make happy the recipient; you don't give a gift in oredr to make happy yourself about how happy you have made them. If they don't say "thank you" and don't share their happines with you, it is probably rude from their part, but you have to cope with that; you cannot solicit gratitude that is not freely given. So: be magnanimous, get over it, next time give gifts to whomever you wish/can afford to give, don't give to whomever you don't, give in order to make the recipient happy and not in order to fulfill any putative obligation or to solicit gratitude -- and above all, don't let these silly worries poison your Christmastide!
72,892,606
For compliance reasons we want to block SQL analysts from running `SELECT *` on a table. Instead, we want to force them to explicitly ask for the columns they want to select. How can I enforce this with Snowflake? I saw a tip for SQL server using a calculated column, does Snowflake have an equivalent? [![enter image description here](https://i.stack.imgur.com/fD1PI.png)](https://i.stack.imgur.com/fD1PI.png) * <https://twitter.com/venzann/status/1133168053867278341>
2022/07/07
[ "https://Stackoverflow.com/questions/72892606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132438/" ]
Sure, you can create tables with derived/computed columns in Snowflake: ```sql create or replace table mytable ( i number, s string , no_select_star number as (1/0)); ``` Once that table has data, you won't be able to run `select *` on it, as the division by 0 is an invalid number: [![enter image description here](https://i.stack.imgur.com/OGz6v.png)](https://i.stack.imgur.com/OGz6v.png) You can also append a computed column to an existing table for the same effects: ```sql alter table mytable2 add column no_select_star number as (1/0); ``` In action: [![enter image description here](https://i.stack.imgur.com/ZFe9G.png)](https://i.stack.imgur.com/ZFe9G.png)
Here's an alternative approach. 1. No dodgy columns 2. No schema pollution 3. Education message to user customisable 4. Native Snowflake functionality 5. Handles '\*' in any position (select col , \* ...) 6. Does take more thought to set up -> must be applied to each column 7. Can update ALL your tables with new error messages in one fell swoop 8. Extendable/adaptable to include any other dodgy SQL your lovely users dream up 9. You get to learn about [Dynamic Masking](https://docs.snowflake.com/en/user-guide/security-column-ddm-use.html) which is super cool! 10. To use in production you'd need to handle ALL datatypes -> would be nice if there was a Dynamic Mask for the entire table. 11. Still runs the SQL in background but hopefully after the users get sick of seeing 'bad bad bad' they'll change their ways. 12. Allows you to exempt SOME users (e.g. exempt yourself for select top 10 \*) ``` create or replace masking policy select_star_bad_bad_bad as (val string) returns string -> case when REGEXP_COUNT(current_statement(),$$\*+$$) >0 then'select * = bad bad bad' else val end; alter table if exists mytable1 modify column s set masking policy select_star_bad_bad_bad; ```
72,892,606
For compliance reasons we want to block SQL analysts from running `SELECT *` on a table. Instead, we want to force them to explicitly ask for the columns they want to select. How can I enforce this with Snowflake? I saw a tip for SQL server using a calculated column, does Snowflake have an equivalent? [![enter image description here](https://i.stack.imgur.com/fD1PI.png)](https://i.stack.imgur.com/fD1PI.png) * <https://twitter.com/venzann/status/1133168053867278341>
2022/07/07
[ "https://Stackoverflow.com/questions/72892606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132438/" ]
> > *it's a workaround and by definition workarounds are not ideal solutions. What I'm wondering is if there's some way to get a message to the user that it's the select \* that's causing the error. I tried a JS UDF that throws an error, but that can't be used as a default for a column.* > > > It is possible to use truncation error to display custom message: ``` create or replace table mytable ( i number, s string , no_select_star string as ('Code smell: SELECT * '::CHAR(1)) ); INSERT INTO mytable(i, s) VALUES (1, 'a'); ``` Query: ``` SELECT * FROM mytable; ``` Output: [![enter image description here](https://i.stack.imgur.com/R2unm.png)](https://i.stack.imgur.com/R2unm.png)
Here's an alternative approach. 1. No dodgy columns 2. No schema pollution 3. Education message to user customisable 4. Native Snowflake functionality 5. Handles '\*' in any position (select col , \* ...) 6. Does take more thought to set up -> must be applied to each column 7. Can update ALL your tables with new error messages in one fell swoop 8. Extendable/adaptable to include any other dodgy SQL your lovely users dream up 9. You get to learn about [Dynamic Masking](https://docs.snowflake.com/en/user-guide/security-column-ddm-use.html) which is super cool! 10. To use in production you'd need to handle ALL datatypes -> would be nice if there was a Dynamic Mask for the entire table. 11. Still runs the SQL in background but hopefully after the users get sick of seeing 'bad bad bad' they'll change their ways. 12. Allows you to exempt SOME users (e.g. exempt yourself for select top 10 \*) ``` create or replace masking policy select_star_bad_bad_bad as (val string) returns string -> case when REGEXP_COUNT(current_statement(),$$\*+$$) >0 then'select * = bad bad bad' else val end; alter table if exists mytable1 modify column s set masking policy select_star_bad_bad_bad; ```
72,892,606
For compliance reasons we want to block SQL analysts from running `SELECT *` on a table. Instead, we want to force them to explicitly ask for the columns they want to select. How can I enforce this with Snowflake? I saw a tip for SQL server using a calculated column, does Snowflake have an equivalent? [![enter image description here](https://i.stack.imgur.com/fD1PI.png)](https://i.stack.imgur.com/fD1PI.png) * <https://twitter.com/venzann/status/1133168053867278341>
2022/07/07
[ "https://Stackoverflow.com/questions/72892606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132438/" ]
Why not use a row access policy, instead? It might take some tweaking, but you could create a row access policy similar to: ``` create or replace row access policy test_policy as (val varchar) returns boolean -> case when lower(current_statement()) like '%select%*%' then false else true end; ``` Applying this policy to a table would not return any records if a `select *` was present in the query. You could apply this policy to every table and it wouldn't affect your schema in any way.
Here's an alternative approach. 1. No dodgy columns 2. No schema pollution 3. Education message to user customisable 4. Native Snowflake functionality 5. Handles '\*' in any position (select col , \* ...) 6. Does take more thought to set up -> must be applied to each column 7. Can update ALL your tables with new error messages in one fell swoop 8. Extendable/adaptable to include any other dodgy SQL your lovely users dream up 9. You get to learn about [Dynamic Masking](https://docs.snowflake.com/en/user-guide/security-column-ddm-use.html) which is super cool! 10. To use in production you'd need to handle ALL datatypes -> would be nice if there was a Dynamic Mask for the entire table. 11. Still runs the SQL in background but hopefully after the users get sick of seeing 'bad bad bad' they'll change their ways. 12. Allows you to exempt SOME users (e.g. exempt yourself for select top 10 \*) ``` create or replace masking policy select_star_bad_bad_bad as (val string) returns string -> case when REGEXP_COUNT(current_statement(),$$\*+$$) >0 then'select * = bad bad bad' else val end; alter table if exists mytable1 modify column s set masking policy select_star_bad_bad_bad; ```
20,426,086
Hi I am trying to compile a child class, Car.java that extends the abstract class Vehicle.java and also implements the interface Comparable. I am getting the following errors when I try to compile the Car.java class: Car is not abstract and does not override Abstract Method get PassengerCapacity() in Vehicle, cannot find symbol and Missing Method body, or declare Abstract What do I look for to rectify it? The Car.java class extends the Abstact class vehicle and also implements the Comparable interface ie: public class Car extends Vehicle implements Comparable I have to write 2 classes Car.java and Bus.java. They both Extend Vehicle and Implement Comparable. Everything needs to work for me to run the programs selectionSort.java and SortVehicle.java. These errors are preventing me from completing my class Car.java as I cannot get past them to then be able to write the Bus.java class and then run the SortSelection.java and SortVehicle.java programs. Vehicle.java, SelectionSort.java and SortVehicle.java have been supplied to me without any errors or issues. I would be grateful for any help in rectifying these errors. My Car.java Code is: ``` public class Car extends Vehicle implements Comparable { public static final int MAX_ENGINE_CAPACITY = 2000; public static final int MIN_ENGINE_CAPACITY = 1800; public static final int MAX_NUMBER_OF_SEATS = 7; public static final int MIN_NUMBER_OF_SEATS = 7; private String vehicleColour; private int numberOfSeats; private int engineCapacity; public Car (Car otherCar) { super(); this.vehicleColour = otherCar.vehicleColour; this.numberOfSeats = otherCar.numberOfSeats; this.engineCapacity = otherCar.engineCapacity; } /public Car() { super(); this.vehicleColour = new vehicleColour(); this.numberOfSeats = MIN_NUMBER_OF_SEATS; this.engineCapacity = MIN_ENGINE_CAPACITY; } public Car (String aModel, int aYearOfManufacture, String aVehicleColour, int aNumberOfSeats, int aEngineCapacity) { super(aModel, aYearOfManufacture); this.vehicleColour = otherCar.vehicleColour; this.numberOfSeats = otherCar.numberOfSeats; this.engineCapacity = otherCar.engineCapacity; } public String getVehicleColour() { return this.vehicleColour; } public int getNumberOfSeats() { return this.numberOfSeats; } public int getEngineCapacity() { return this.engineCapacity; } public void setVehicleColour (String newVehicleColour); { if (newVehicleColour == null) { System.out.println("Fatal Error setting vehicle colour."); System.exit(0); } else this.vehiclColour = newVehicleColour; } public void setNumberOfSeats (int newNumberOfSeats) { if (newNumberOfSeats == null) { System.out.println("Fatal Error setting number Of Seats."); System.exit(0); } else this.numberOfSeats = newNumberOfSeats; } public void setEngineCapacity (int newEngineCapacity); { if (newEngineCapacity == null) { System.out.println("Fatal Error setting number Of Seats."); System.exit(0); } else this.engineCapacity = newEngineCapacity; } ``` } And the Vehicle.java code is: ``` public abstract class Vehicle { public static final int MAX_REASONABLE_YEAR_OF_MANUFACTURE = 2100; public static final int MIN_REASONABLE_YEAR_OF_MANUFACTURE = 1000; private String model; private int yearOfManufacture; public Vehicle () { this.model = "(model unspecified)"; this.yearOfManufacture = MIN_REASONABLE_YEAR_OF_MANUFACTURE; } public Vehicle (String aModel, int aYearOfManufacture) { this.model = aModel; if (yearOfManufactureReasonable(aYearOfManufacture)) this.yearOfManufacture = aYearOfManufacture; else { System.out.println("Fatal Error: unreasonable year of manufacture used defining vehicle."); System.exit(0); } } public Vehicle (Vehicle otherVehicle) { this.model = otherVehicle.model; this.yearOfManufacture = otherVehicle.yearOfManufacture; } private static boolean yearOfManufactureReasonable(int aYearOfManufacture) { return (aYearOfManufacture >= MIN_REASONABLE_YEAR_OF_MANUFACTURE && aYearOfManufacture <= MAX_REASONABLE_YEAR_OF_MANUFACTURE); } public String getModel () { return this.model; } public int getYearOfManufacture () { return this.yearOfManufacture; } public void setModel (String aModel) { this.model = aModel; } public void setYearOfManufacture (int aYearOfManufacture) { if (yearOfManufactureReasonable(aYearOfManufacture)) this.yearOfManufacture = aYearOfManufacture; } public String toString () { return (this.model + ", " + this.yearOfManufacture); } public boolean equals (Object otherObject) { if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Vehicle otherVehicle = (Vehicle)otherObject; return (this.model.equals(otherVehicle.model) && this.yearOfManufacture == otherVehicle.yearOfManufacture); } public abstract int getPassengerCapacity (); public boolean greaterPassengerCapacityThan (Vehicle otherVehicle) { return (this.getPassengerCapacity() > otherVehicle.getPassengerCapacity()); } ``` } the full list of errors I get are as follows: ``` Car.java:5: error: Car is not abstract and does not override abstract method get PassengerCapacity() in Vehicle public class Car extends Vehicle implements Comparable ^ Car.java:27: error: cannot find symbol this.vehicleColour = new vehicleColour(); ^ symbol: class vehicleColour location: class Car Car.java:35: error: cannot find symbol this.vehicleColour = otherCar.vehicleColour; ^ symbol: variable otherCar location: class Car Car.java:36: error: cannot find symbol this.numberOfSeats = otherCar.numberOfSeats; ^ symbol: variable otherCar location: class Car Car.java:37: error: cannot find symbol this.engineCapacity = otherCar.engineCapacity; ^ symbol: variable otherCar location: class Car Car.java:56: error: missing method body, or declare abstract public void setVehicleColour (String newVehicleColour); ^ Car.java:58: error: cannot find symbol if (newVehicleColour == null) ^ symbol: variable newVehicleColour location: class Car Car.java:64: error: cannot find symbol this.vehiclColour = newVehicleColour; ^ symbol: variable vehiclColour Car.java:64: error: cannot find symbol this.vehiclColour = newVehicleColour; ^ symbol: variable newVehicleColour location: class Car Car.java:69: error: incomparable types: int and <null> if (newNumberOfSeats == null) ^ Car.java:78: error: missing method body, or declare abstract public void setEngineCapacity (int newEngineCapacity); ^ Car.java:80: error: cannot find symbol if (newEngineCapacity == null) ^ symbol: variable newEngineCapacity location: class Car Car.java:86: error: cannot find symbol this.engineCapacity = newEngineCapacity; ^ symbol: variable newEngineCapacity location: class Car 13 errors ```
2013/12/06
[ "https://Stackoverflow.com/questions/20426086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3074723/" ]
You have to implement `getPassengerCapacity()` method in your `Car` class or Mark your `Car` class as `abstract`. You cannot extend an abstract class and leave a method without implementing the body. If you don't want to implement that method, then this class needs to be marked as `abstract` as well.
your error message states that your class Car must implement the abstract method PassengerCapacity() defined in Vehicle. If you think you've done it may be you just mistyped a keyword in the signature of the method ?
20,426,086
Hi I am trying to compile a child class, Car.java that extends the abstract class Vehicle.java and also implements the interface Comparable. I am getting the following errors when I try to compile the Car.java class: Car is not abstract and does not override Abstract Method get PassengerCapacity() in Vehicle, cannot find symbol and Missing Method body, or declare Abstract What do I look for to rectify it? The Car.java class extends the Abstact class vehicle and also implements the Comparable interface ie: public class Car extends Vehicle implements Comparable I have to write 2 classes Car.java and Bus.java. They both Extend Vehicle and Implement Comparable. Everything needs to work for me to run the programs selectionSort.java and SortVehicle.java. These errors are preventing me from completing my class Car.java as I cannot get past them to then be able to write the Bus.java class and then run the SortSelection.java and SortVehicle.java programs. Vehicle.java, SelectionSort.java and SortVehicle.java have been supplied to me without any errors or issues. I would be grateful for any help in rectifying these errors. My Car.java Code is: ``` public class Car extends Vehicle implements Comparable { public static final int MAX_ENGINE_CAPACITY = 2000; public static final int MIN_ENGINE_CAPACITY = 1800; public static final int MAX_NUMBER_OF_SEATS = 7; public static final int MIN_NUMBER_OF_SEATS = 7; private String vehicleColour; private int numberOfSeats; private int engineCapacity; public Car (Car otherCar) { super(); this.vehicleColour = otherCar.vehicleColour; this.numberOfSeats = otherCar.numberOfSeats; this.engineCapacity = otherCar.engineCapacity; } /public Car() { super(); this.vehicleColour = new vehicleColour(); this.numberOfSeats = MIN_NUMBER_OF_SEATS; this.engineCapacity = MIN_ENGINE_CAPACITY; } public Car (String aModel, int aYearOfManufacture, String aVehicleColour, int aNumberOfSeats, int aEngineCapacity) { super(aModel, aYearOfManufacture); this.vehicleColour = otherCar.vehicleColour; this.numberOfSeats = otherCar.numberOfSeats; this.engineCapacity = otherCar.engineCapacity; } public String getVehicleColour() { return this.vehicleColour; } public int getNumberOfSeats() { return this.numberOfSeats; } public int getEngineCapacity() { return this.engineCapacity; } public void setVehicleColour (String newVehicleColour); { if (newVehicleColour == null) { System.out.println("Fatal Error setting vehicle colour."); System.exit(0); } else this.vehiclColour = newVehicleColour; } public void setNumberOfSeats (int newNumberOfSeats) { if (newNumberOfSeats == null) { System.out.println("Fatal Error setting number Of Seats."); System.exit(0); } else this.numberOfSeats = newNumberOfSeats; } public void setEngineCapacity (int newEngineCapacity); { if (newEngineCapacity == null) { System.out.println("Fatal Error setting number Of Seats."); System.exit(0); } else this.engineCapacity = newEngineCapacity; } ``` } And the Vehicle.java code is: ``` public abstract class Vehicle { public static final int MAX_REASONABLE_YEAR_OF_MANUFACTURE = 2100; public static final int MIN_REASONABLE_YEAR_OF_MANUFACTURE = 1000; private String model; private int yearOfManufacture; public Vehicle () { this.model = "(model unspecified)"; this.yearOfManufacture = MIN_REASONABLE_YEAR_OF_MANUFACTURE; } public Vehicle (String aModel, int aYearOfManufacture) { this.model = aModel; if (yearOfManufactureReasonable(aYearOfManufacture)) this.yearOfManufacture = aYearOfManufacture; else { System.out.println("Fatal Error: unreasonable year of manufacture used defining vehicle."); System.exit(0); } } public Vehicle (Vehicle otherVehicle) { this.model = otherVehicle.model; this.yearOfManufacture = otherVehicle.yearOfManufacture; } private static boolean yearOfManufactureReasonable(int aYearOfManufacture) { return (aYearOfManufacture >= MIN_REASONABLE_YEAR_OF_MANUFACTURE && aYearOfManufacture <= MAX_REASONABLE_YEAR_OF_MANUFACTURE); } public String getModel () { return this.model; } public int getYearOfManufacture () { return this.yearOfManufacture; } public void setModel (String aModel) { this.model = aModel; } public void setYearOfManufacture (int aYearOfManufacture) { if (yearOfManufactureReasonable(aYearOfManufacture)) this.yearOfManufacture = aYearOfManufacture; } public String toString () { return (this.model + ", " + this.yearOfManufacture); } public boolean equals (Object otherObject) { if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Vehicle otherVehicle = (Vehicle)otherObject; return (this.model.equals(otherVehicle.model) && this.yearOfManufacture == otherVehicle.yearOfManufacture); } public abstract int getPassengerCapacity (); public boolean greaterPassengerCapacityThan (Vehicle otherVehicle) { return (this.getPassengerCapacity() > otherVehicle.getPassengerCapacity()); } ``` } the full list of errors I get are as follows: ``` Car.java:5: error: Car is not abstract and does not override abstract method get PassengerCapacity() in Vehicle public class Car extends Vehicle implements Comparable ^ Car.java:27: error: cannot find symbol this.vehicleColour = new vehicleColour(); ^ symbol: class vehicleColour location: class Car Car.java:35: error: cannot find symbol this.vehicleColour = otherCar.vehicleColour; ^ symbol: variable otherCar location: class Car Car.java:36: error: cannot find symbol this.numberOfSeats = otherCar.numberOfSeats; ^ symbol: variable otherCar location: class Car Car.java:37: error: cannot find symbol this.engineCapacity = otherCar.engineCapacity; ^ symbol: variable otherCar location: class Car Car.java:56: error: missing method body, or declare abstract public void setVehicleColour (String newVehicleColour); ^ Car.java:58: error: cannot find symbol if (newVehicleColour == null) ^ symbol: variable newVehicleColour location: class Car Car.java:64: error: cannot find symbol this.vehiclColour = newVehicleColour; ^ symbol: variable vehiclColour Car.java:64: error: cannot find symbol this.vehiclColour = newVehicleColour; ^ symbol: variable newVehicleColour location: class Car Car.java:69: error: incomparable types: int and <null> if (newNumberOfSeats == null) ^ Car.java:78: error: missing method body, or declare abstract public void setEngineCapacity (int newEngineCapacity); ^ Car.java:80: error: cannot find symbol if (newEngineCapacity == null) ^ symbol: variable newEngineCapacity location: class Car Car.java:86: error: cannot find symbol this.engineCapacity = newEngineCapacity; ^ symbol: variable newEngineCapacity location: class Car 13 errors ```
2013/12/06
[ "https://Stackoverflow.com/questions/20426086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3074723/" ]
You have to implement `getPassengerCapacity()` method in your `Car` class or Mark your `Car` class as `abstract`. You cannot extend an abstract class and leave a method without implementing the body. If you don't want to implement that method, then this class needs to be marked as `abstract` as well.
The existing answers are good - but just to add, if you use the @override annotation where you implement the abstract methods then you will immediately get an error at that point if you get something wrong in the method signature.
34,752,085
How can I simplify those three simple if conditions? ``` if(v.x < 0) { v.x *= -1; } if(v.y < 0) { v.y *= -1; } if(v.z < 0) { v.z *= -1; } ```
2016/01/12
[ "https://Stackoverflow.com/questions/34752085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5586664/" ]
``` #include <stdlib.h> ... v.x = abs(v.x); v.y = abs(v.y); v.z = abs(v.z); ``` Or `labs`, `llabs`, `fabs` (`<math.h>`), etc. depending of type of your numbers.
You can do something like this : ``` v.x = (v.x < 0) ? (v.x * -1) : (v.x) ; v.y = (v.y < 0) ? (v.y * -1) : (v.y) ; v.z = (v.z < 0) ? (v.z * -1) : (v.z) ; ``` This uses the C [ternary operator](https://en.wikipedia.org/wiki/%3F:).
1,166,250
I have Ubuntu 19.04 dual booted alongside Windows 10. I had not used my PC for a month. The last time I used my PC, Ubuntu was working great. Today (after a month), when I turned on my PC, the boot process got stuck on a black screen with some text written on it. I don't understand what is written (too much technical terms). And at last line "intramfs" is written and I can type and enter any command into it (just like in the terminal). [![black screen](https://i.stack.imgur.com/ka1UI.jpg)](https://i.stack.imgur.com/ka1UI.jpg)
2019/08/16
[ "https://askubuntu.com/questions/1166250", "https://askubuntu.com", "https://askubuntu.com/users/851736/" ]
we can find the solution in this part of the error: ``` /dev/sda10: UNEXPECTED INCONSISTENCY: RUN fsck MANUALLY. (i.e., without -a or -p options) fsck exited with status code 4 The root filesystem on /dev/sda10 requires a manual fsck Busybox v1.227.2 (Ubuntu 1:1.27.2-2ubuntu7) built in shell (ash) Enter 'help' for a list of built-in commands. (initramfs) _ ``` so i did some digging for you and your question is already answered: same problem as yours dual boot with windows os [fsck error on boot: /dev/sda6: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY](https://askubuntu.com/questions/697190/fsck-error-on-boot-dev-sda6-unexpected-inconsistency-run-fsck-manually) [Root file system requires manual fsck](https://askubuntu.com/questions/885062/root-file-system-requires-manual-fsck) if that wasnt helpful search `UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY` there is a lot of discussion about it because of low reputation i couldnt flag the question or comment below it so sorry
Run the following command to try to fix the error: ``` sudo fsck -fy /dev/sda10 ```
39,418,627
Actually, i have a list with image URIs. Inside a foreach-loop i create Image objects from these URIs like this: ``` foreach (Uri imageUri in uriList) { BitmapImage bmi = new BitmapImage(new Uri(imageUri)); Image image = new Image(); image.source = bmi; flipView.Items.Add(image); } ``` Now the problem is, if there are many Images (100-200), then the RAM usage is very high, when swiping fast through the FlipView. What i have seen also is, that every image, will be "cached" or something, so if i go back in the FlipView, no more internet traffic will be generated. So my question is, is this the right way to do that, ore are there better ways to get a "Image Gallery" from Web Images? Best Regards
2016/09/09
[ "https://Stackoverflow.com/questions/39418627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5990549/" ]
Actually working ================ If you want to extract text: * import Presentation from pptx (pip install python-pptx) * for each file in the directory (using glob module) * look in every slides and in every shape in each slide * if there is a shape with text attribute, print the shape.text --- ``` from pptx import Presentation import glob for eachfile in glob.glob("*.pptx"): prs = Presentation(eachfile) print(eachfile) print("----------------------") for slide in prs.slides: for shape in slide.shapes: if hasattr(shape, "text"): print(shape.text) ```
`python-pptx` can be used to do what you propose. Just at a high level, you would do something like this (not working code, just and idea of overall approach): ``` from pptx import Presentation for pptx_filename in directory: prs = Presentation(pptx_filename) for slide in prs.slides: for shape in slide.shapes: print shape.text ``` You'd need to add the bits about searching shape text for key strings and adding them to a CSV file or whatever, but this general approach should work just fine. I'll leave it to you to work out the finer points :)
39,418,627
Actually, i have a list with image URIs. Inside a foreach-loop i create Image objects from these URIs like this: ``` foreach (Uri imageUri in uriList) { BitmapImage bmi = new BitmapImage(new Uri(imageUri)); Image image = new Image(); image.source = bmi; flipView.Items.Add(image); } ``` Now the problem is, if there are many Images (100-200), then the RAM usage is very high, when swiping fast through the FlipView. What i have seen also is, that every image, will be "cached" or something, so if i go back in the FlipView, no more internet traffic will be generated. So my question is, is this the right way to do that, ore are there better ways to get a "Image Gallery" from Web Images? Best Regards
2016/09/09
[ "https://Stackoverflow.com/questions/39418627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5990549/" ]
**tika-python** A Python port of the Apache Tika library, According to the documentation Apache tika supports text extraction from over 1500 file formats. **Note:** It also works charmingly with **pyinstaller** Install with pip : ``` pip install tika ``` **Sample:** ``` #!/usr/bin/env python from tika import parser parsed = parser.from_file('/path/to/file') print(parsed["metadata"]) #To get the meta data of the file print(parsed["content"]) # To get the content of the file ``` Link to official [GitHub](https://github.com/chrismattmann/tika-python)
`python-pptx` can be used to do what you propose. Just at a high level, you would do something like this (not working code, just and idea of overall approach): ``` from pptx import Presentation for pptx_filename in directory: prs = Presentation(pptx_filename) for slide in prs.slides: for shape in slide.shapes: print shape.text ``` You'd need to add the bits about searching shape text for key strings and adding them to a CSV file or whatever, but this general approach should work just fine. I'll leave it to you to work out the finer points :)
39,418,627
Actually, i have a list with image URIs. Inside a foreach-loop i create Image objects from these URIs like this: ``` foreach (Uri imageUri in uriList) { BitmapImage bmi = new BitmapImage(new Uri(imageUri)); Image image = new Image(); image.source = bmi; flipView.Items.Add(image); } ``` Now the problem is, if there are many Images (100-200), then the RAM usage is very high, when swiping fast through the FlipView. What i have seen also is, that every image, will be "cached" or something, so if i go back in the FlipView, no more internet traffic will be generated. So my question is, is this the right way to do that, ore are there better ways to get a "Image Gallery" from Web Images? Best Regards
2016/09/09
[ "https://Stackoverflow.com/questions/39418627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5990549/" ]
`python-pptx` can be used to do what you propose. Just at a high level, you would do something like this (not working code, just and idea of overall approach): ``` from pptx import Presentation for pptx_filename in directory: prs = Presentation(pptx_filename) for slide in prs.slides: for shape in slide.shapes: print shape.text ``` You'd need to add the bits about searching shape text for key strings and adding them to a CSV file or whatever, but this general approach should work just fine. I'll leave it to you to work out the finer points :)
**Textract-Plus** Use textract-plus which can extract text from most of the document extensions including pptx and pptm. [refer docs](https://textract-plus.readthedocs.io/en/latest/index.html) Install- ``` pip install textract-plus ``` Sample- ``` import textractplus as tp text=tp.process('path/to/yourfile.pptx') ``` for your case- ``` import os import pandas as pd import textractplus as tp files_csv=[] your_dir='.' for f in os.listdir(your_dir): if f.endswith('pptx') or f.endswith('pptm'): text=tp.process(os.join(your_dir,f)) files_csv.append([f,text]) pd.Dataframe(files_csv,columns=['filename','text']).to_csv('your_csv.csv') ``` this code will fetch all the pptx and pptm files from directory and create a csv with first column as filename and second as text extracted from that file
39,418,627
Actually, i have a list with image URIs. Inside a foreach-loop i create Image objects from these URIs like this: ``` foreach (Uri imageUri in uriList) { BitmapImage bmi = new BitmapImage(new Uri(imageUri)); Image image = new Image(); image.source = bmi; flipView.Items.Add(image); } ``` Now the problem is, if there are many Images (100-200), then the RAM usage is very high, when swiping fast through the FlipView. What i have seen also is, that every image, will be "cached" or something, so if i go back in the FlipView, no more internet traffic will be generated. So my question is, is this the right way to do that, ore are there better ways to get a "Image Gallery" from Web Images? Best Regards
2016/09/09
[ "https://Stackoverflow.com/questions/39418627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5990549/" ]
`python-pptx` can be used to do what you propose. Just at a high level, you would do something like this (not working code, just and idea of overall approach): ``` from pptx import Presentation for pptx_filename in directory: prs = Presentation(pptx_filename) for slide in prs.slides: for shape in slide.shapes: print shape.text ``` You'd need to add the bits about searching shape text for key strings and adding them to a CSV file or whatever, but this general approach should work just fine. I'll leave it to you to work out the finer points :)
``` import os import textract files_csv = [] your_dir = '.' for f in os.listdir(your_dir): if f.endswith('pptx') or f.endswith('pptm'): text = tp.process(os.path.join('sample.pptx')) print(text) ```
39,418,627
Actually, i have a list with image URIs. Inside a foreach-loop i create Image objects from these URIs like this: ``` foreach (Uri imageUri in uriList) { BitmapImage bmi = new BitmapImage(new Uri(imageUri)); Image image = new Image(); image.source = bmi; flipView.Items.Add(image); } ``` Now the problem is, if there are many Images (100-200), then the RAM usage is very high, when swiping fast through the FlipView. What i have seen also is, that every image, will be "cached" or something, so if i go back in the FlipView, no more internet traffic will be generated. So my question is, is this the right way to do that, ore are there better ways to get a "Image Gallery" from Web Images? Best Regards
2016/09/09
[ "https://Stackoverflow.com/questions/39418627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5990549/" ]
Actually working ================ If you want to extract text: * import Presentation from pptx (pip install python-pptx) * for each file in the directory (using glob module) * look in every slides and in every shape in each slide * if there is a shape with text attribute, print the shape.text --- ``` from pptx import Presentation import glob for eachfile in glob.glob("*.pptx"): prs = Presentation(eachfile) print(eachfile) print("----------------------") for slide in prs.slides: for shape in slide.shapes: if hasattr(shape, "text"): print(shape.text) ```
**tika-python** A Python port of the Apache Tika library, According to the documentation Apache tika supports text extraction from over 1500 file formats. **Note:** It also works charmingly with **pyinstaller** Install with pip : ``` pip install tika ``` **Sample:** ``` #!/usr/bin/env python from tika import parser parsed = parser.from_file('/path/to/file') print(parsed["metadata"]) #To get the meta data of the file print(parsed["content"]) # To get the content of the file ``` Link to official [GitHub](https://github.com/chrismattmann/tika-python)
39,418,627
Actually, i have a list with image URIs. Inside a foreach-loop i create Image objects from these URIs like this: ``` foreach (Uri imageUri in uriList) { BitmapImage bmi = new BitmapImage(new Uri(imageUri)); Image image = new Image(); image.source = bmi; flipView.Items.Add(image); } ``` Now the problem is, if there are many Images (100-200), then the RAM usage is very high, when swiping fast through the FlipView. What i have seen also is, that every image, will be "cached" or something, so if i go back in the FlipView, no more internet traffic will be generated. So my question is, is this the right way to do that, ore are there better ways to get a "Image Gallery" from Web Images? Best Regards
2016/09/09
[ "https://Stackoverflow.com/questions/39418627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5990549/" ]
Actually working ================ If you want to extract text: * import Presentation from pptx (pip install python-pptx) * for each file in the directory (using glob module) * look in every slides and in every shape in each slide * if there is a shape with text attribute, print the shape.text --- ``` from pptx import Presentation import glob for eachfile in glob.glob("*.pptx"): prs = Presentation(eachfile) print(eachfile) print("----------------------") for slide in prs.slides: for shape in slide.shapes: if hasattr(shape, "text"): print(shape.text) ```
**Textract-Plus** Use textract-plus which can extract text from most of the document extensions including pptx and pptm. [refer docs](https://textract-plus.readthedocs.io/en/latest/index.html) Install- ``` pip install textract-plus ``` Sample- ``` import textractplus as tp text=tp.process('path/to/yourfile.pptx') ``` for your case- ``` import os import pandas as pd import textractplus as tp files_csv=[] your_dir='.' for f in os.listdir(your_dir): if f.endswith('pptx') or f.endswith('pptm'): text=tp.process(os.join(your_dir,f)) files_csv.append([f,text]) pd.Dataframe(files_csv,columns=['filename','text']).to_csv('your_csv.csv') ``` this code will fetch all the pptx and pptm files from directory and create a csv with first column as filename and second as text extracted from that file
39,418,627
Actually, i have a list with image URIs. Inside a foreach-loop i create Image objects from these URIs like this: ``` foreach (Uri imageUri in uriList) { BitmapImage bmi = new BitmapImage(new Uri(imageUri)); Image image = new Image(); image.source = bmi; flipView.Items.Add(image); } ``` Now the problem is, if there are many Images (100-200), then the RAM usage is very high, when swiping fast through the FlipView. What i have seen also is, that every image, will be "cached" or something, so if i go back in the FlipView, no more internet traffic will be generated. So my question is, is this the right way to do that, ore are there better ways to get a "Image Gallery" from Web Images? Best Regards
2016/09/09
[ "https://Stackoverflow.com/questions/39418627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5990549/" ]
Actually working ================ If you want to extract text: * import Presentation from pptx (pip install python-pptx) * for each file in the directory (using glob module) * look in every slides and in every shape in each slide * if there is a shape with text attribute, print the shape.text --- ``` from pptx import Presentation import glob for eachfile in glob.glob("*.pptx"): prs = Presentation(eachfile) print(eachfile) print("----------------------") for slide in prs.slides: for shape in slide.shapes: if hasattr(shape, "text"): print(shape.text) ```
``` import os import textract files_csv = [] your_dir = '.' for f in os.listdir(your_dir): if f.endswith('pptx') or f.endswith('pptm'): text = tp.process(os.path.join('sample.pptx')) print(text) ```
39,418,627
Actually, i have a list with image URIs. Inside a foreach-loop i create Image objects from these URIs like this: ``` foreach (Uri imageUri in uriList) { BitmapImage bmi = new BitmapImage(new Uri(imageUri)); Image image = new Image(); image.source = bmi; flipView.Items.Add(image); } ``` Now the problem is, if there are many Images (100-200), then the RAM usage is very high, when swiping fast through the FlipView. What i have seen also is, that every image, will be "cached" or something, so if i go back in the FlipView, no more internet traffic will be generated. So my question is, is this the right way to do that, ore are there better ways to get a "Image Gallery" from Web Images? Best Regards
2016/09/09
[ "https://Stackoverflow.com/questions/39418627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5990549/" ]
**tika-python** A Python port of the Apache Tika library, According to the documentation Apache tika supports text extraction from over 1500 file formats. **Note:** It also works charmingly with **pyinstaller** Install with pip : ``` pip install tika ``` **Sample:** ``` #!/usr/bin/env python from tika import parser parsed = parser.from_file('/path/to/file') print(parsed["metadata"]) #To get the meta data of the file print(parsed["content"]) # To get the content of the file ``` Link to official [GitHub](https://github.com/chrismattmann/tika-python)
**Textract-Plus** Use textract-plus which can extract text from most of the document extensions including pptx and pptm. [refer docs](https://textract-plus.readthedocs.io/en/latest/index.html) Install- ``` pip install textract-plus ``` Sample- ``` import textractplus as tp text=tp.process('path/to/yourfile.pptx') ``` for your case- ``` import os import pandas as pd import textractplus as tp files_csv=[] your_dir='.' for f in os.listdir(your_dir): if f.endswith('pptx') or f.endswith('pptm'): text=tp.process(os.join(your_dir,f)) files_csv.append([f,text]) pd.Dataframe(files_csv,columns=['filename','text']).to_csv('your_csv.csv') ``` this code will fetch all the pptx and pptm files from directory and create a csv with first column as filename and second as text extracted from that file
39,418,627
Actually, i have a list with image URIs. Inside a foreach-loop i create Image objects from these URIs like this: ``` foreach (Uri imageUri in uriList) { BitmapImage bmi = new BitmapImage(new Uri(imageUri)); Image image = new Image(); image.source = bmi; flipView.Items.Add(image); } ``` Now the problem is, if there are many Images (100-200), then the RAM usage is very high, when swiping fast through the FlipView. What i have seen also is, that every image, will be "cached" or something, so if i go back in the FlipView, no more internet traffic will be generated. So my question is, is this the right way to do that, ore are there better ways to get a "Image Gallery" from Web Images? Best Regards
2016/09/09
[ "https://Stackoverflow.com/questions/39418627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5990549/" ]
**tika-python** A Python port of the Apache Tika library, According to the documentation Apache tika supports text extraction from over 1500 file formats. **Note:** It also works charmingly with **pyinstaller** Install with pip : ``` pip install tika ``` **Sample:** ``` #!/usr/bin/env python from tika import parser parsed = parser.from_file('/path/to/file') print(parsed["metadata"]) #To get the meta data of the file print(parsed["content"]) # To get the content of the file ``` Link to official [GitHub](https://github.com/chrismattmann/tika-python)
``` import os import textract files_csv = [] your_dir = '.' for f in os.listdir(your_dir): if f.endswith('pptx') or f.endswith('pptm'): text = tp.process(os.path.join('sample.pptx')) print(text) ```
54,318,041
I am trying to add some Open Graph tags to each Article of my blog that is hosted in Wordpress. This code is working when I run "npm run dev", but when I run "npm run generate && firebase deploy" is not doing the same. This is the code that I am using: ``` head() { return { title: 'This', meta: [ { hid: `og:description`, name: 'og:description', content: 'title' }, { hid: `og:title`, name: 'og:title', content: 'title' } ] } ``` In my nuxt.config.js I have configured the following in the head ``` head() { return { title: 'That', meta: [ { hid: `og:description`, name: 'og:description', content: '3' }, { hid: `og:title`, name: 'og:title', content: '4' } ] } ``` In the article, the title that is showing is "This" but, the meta is showing the content in nuxt.config.js ("3","4") instead of ("title", "title") What I would like to obtain is the meta tag of the article one in the with the SSR.
2019/01/22
[ "https://Stackoverflow.com/questions/54318041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7657911/" ]
My problem was using `spa` (single page application) mode instead of `universal`. My working settings in `nuxt.config.js`: ```js export default { mode: 'universal', // changed from mode: 'spa' ... } ```
I would try using the [nuxt-seo](https://www.npmjs.com/package/nuxt-seo) package. It adds full support for setting the most common social media tags, including auto generating canonical tags for each of your articles/pages. You can [checkout the docs](https://nuxt-seo.frostbutter.com) site, which has a full [nuxt blog example](https://nuxt-seo.frostbutter.com/examples/blog/). After installing the `nuxt-seo` package in your project, add it to your `nuxt-config.js` file: ``` { modules: [ 'nuxt-seo' ], seo: { // Module Options } } ``` Then on each article/page, you can set the page specific title, description, and pretty much any other meta tag: ``` <template> <h1>Hello World</h1> </template> <script> export default { head({ $seo }) { return $seo({ title: 'Home Page', description: 'Hello World Page', keywords: 'hello, world, home', }) } } </script> ``` PS: I am the maintainer of the `nuxt-seo` package.
840,741
I have some Delphi code that did this needs to be re-coded in C#: ``` procedure TDocSearchX.Decompress; var BlobStream:TBlobStream; DecompressionStream:TDecompressionStream; FileStream:TFileStream; Buffer:array[0..2047] of byte; count:integer; begin BlobStream:=TBlobStream.Create(DocQueryDATA,bmRead); DecompressionStream:=TDecompressionStream.Create(BlobStream); FileStream:=TFileStream.Create(FDocFile,fmCreate); while True do begin Count := DecompressionStream.Read(Buffer, 2048); if Count <> 0 then FileStream.Write(Buffer, Count) else Break; end; Blobstream.Free; DecompressionStream.Free; FileStream.Free; end; ``` The contractor that wrote this is leaving and I need to decompress the image (that is currently stored in the database). I have been able to extract the image to a file but have no idea how to decompress it using C#?
2009/05/08
[ "https://Stackoverflow.com/questions/840741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It looks like `TDecompressionStream` probably uses ZLib. Here is a .NET library for ZLIB: <http://www.componentace.com/zlib_.NET.htm>
To my knowledge there is no .Net Framework equivalent to the TDecompressionStream class. Are you able to write a small converter app in Delphi that decompresses the image? Then you are free to use whatever compression library (e.g. SharpZipLib) supporting .Net within your C# code.
840,741
I have some Delphi code that did this needs to be re-coded in C#: ``` procedure TDocSearchX.Decompress; var BlobStream:TBlobStream; DecompressionStream:TDecompressionStream; FileStream:TFileStream; Buffer:array[0..2047] of byte; count:integer; begin BlobStream:=TBlobStream.Create(DocQueryDATA,bmRead); DecompressionStream:=TDecompressionStream.Create(BlobStream); FileStream:=TFileStream.Create(FDocFile,fmCreate); while True do begin Count := DecompressionStream.Read(Buffer, 2048); if Count <> 0 then FileStream.Write(Buffer, Count) else Break; end; Blobstream.Free; DecompressionStream.Free; FileStream.Free; end; ``` The contractor that wrote this is leaving and I need to decompress the image (that is currently stored in the database). I have been able to extract the image to a file but have no idea how to decompress it using C#?
2009/05/08
[ "https://Stackoverflow.com/questions/840741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
To my knowledge there is no .Net Framework equivalent to the TDecompressionStream class. Are you able to write a small converter app in Delphi that decompresses the image? Then you are free to use whatever compression library (e.g. SharpZipLib) supporting .Net within your C# code.
If you have to keep the same compression already used, roll the Delphi decompression routine into a DLL and use it from C# using PInvoke. If you want to replace the compression, write a batch process to extract the Delphi compressed images, decompress them to their original format and re-compress them with your favourite C# library.
840,741
I have some Delphi code that did this needs to be re-coded in C#: ``` procedure TDocSearchX.Decompress; var BlobStream:TBlobStream; DecompressionStream:TDecompressionStream; FileStream:TFileStream; Buffer:array[0..2047] of byte; count:integer; begin BlobStream:=TBlobStream.Create(DocQueryDATA,bmRead); DecompressionStream:=TDecompressionStream.Create(BlobStream); FileStream:=TFileStream.Create(FDocFile,fmCreate); while True do begin Count := DecompressionStream.Read(Buffer, 2048); if Count <> 0 then FileStream.Write(Buffer, Count) else Break; end; Blobstream.Free; DecompressionStream.Free; FileStream.Free; end; ``` The contractor that wrote this is leaving and I need to decompress the image (that is currently stored in the database). I have been able to extract the image to a file but have no idea how to decompress it using C#?
2009/05/08
[ "https://Stackoverflow.com/questions/840741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It looks like `TDecompressionStream` probably uses ZLib. Here is a .NET library for ZLIB: <http://www.componentace.com/zlib_.NET.htm>
If you have to keep the same compression already used, roll the Delphi decompression routine into a DLL and use it from C# using PInvoke. If you want to replace the compression, write a batch process to extract the Delphi compressed images, decompress them to their original format and re-compress them with your favourite C# library.
22,908,653
I have a async function, which can recurse into itself. I'm adding jQuery deferreds to an array each time the function runs, an use `$.when()` to check if all promises have resolved. My issue is that I can't seem to do this without an arbitary timeout, as I simply don't know when the function stops recursing and adding new promises. * Here's a [JSBin demonstration](http://jsbin.com/wulin/5/edit?js,console). * And here's the [real world example](https://github.com/silverwind/droppy/blob/master/src/client.js#L1561).
2014/04/07
[ "https://Stackoverflow.com/questions/22908653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/808699/" ]
Do push to `promises` only synchronously, so that you know when you are finished. Since your function is recursive and returns a promise, you can just use the result promises of the recursive calls for this. Use `$.when()` only for the results of the *current* recursion level, not for all promises in the call stack. Also check my answers to [Understanding promises in node.js for recursive function](https://stackoverflow.com/q/18904745/1048572) and [Is there an example of using raw Q promise library with node to recursively traverse a directory asynchronously?](https://stackoverflow.com/q/19362009/1048572) - even though they're not using jQuery's implementation, they should give you an idea of how to do it.
Just to add to what Bergi said, and to clarify the underlying issue: There is no way to know when no more promises will be chained to a promise with `.then`. Just like there is no way to know from a function where it returns: ``` myPromise().then(function(vale){ // I have no easy way to know when handlers will no longer be added to myPromise // from myPromise itself }); ``` Is just like: ``` function mySynchronousFunction(){ // I can't easily tell from here where this code returns or how many time it will // be called in the entire program lifecycle. }; ``` How would you solve that problem with synchronous code? You probably wouldn't have it in the first place. You'd know better than to rely on global program state and the caller inside a function :) It's similar to promises. You don't rely on when the last handler was added in promise code. Instead, what you want to do is call `$.when` on the inner promises inside the `.forEach` in your practical example which would give you a hook on when they're all done, and only resolve them in turn when their inner promises resolve - which is just returning them really since promises unwrap recursively. In addition to Bergi's samples which are all good - see [Petka's implementation](https://github.com/petkaantonov/bluebird/wiki/Snippets#reading-directory-and-sub-directory-contents-recursively) which should give you the general idea :) Good luck. --- As a side note - you're not really using promises as promise at all. You're more using them as callbacks. If you want a promise to wait for another promise to complete, you can use `.then`: ``` promiseReturning1().then(promiseReturning2).then(promiseReturning3).then(function(lastResult){ // all done here }); ``` Instead of implementing your own asynchronous queue.
5,241,915
When using simple-xml, is there a way to let it ignore the nodes it does not recognize?
2011/03/09
[ "https://Stackoverflow.com/questions/5241915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496949/" ]
Yes. If you annotate your class with `@Root(strict=false)` it will ignore any elements that are not mapped. See the documentation for additional details: <http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#loosemap> On a related note, you can also handle optional elements using `@Element(required=false)`. <http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#optional>
Discliamer: If simple-xml means anything but a [simple XML](http://en.wikipedia.org/wiki/Simple_XML) then the following answer is irrelevant First, look at: <http://www.w3.org/TR/xmlschema-1/#element-any> An example schema allowing such any elements is: ``` <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:element name="Root"> <xs:complexType> <xs:all> <xs:element name="Element"> <xs:complexType> <xs:sequence minOccurs="0"> <xs:any processContents="lax" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:all> </xs:complexType> </xs:element> </xs:schema> ``` And an example xml validating to the above is: ``` <?xml version="1.0" encoding="UTF-8"?> <Root xsi:noNamespaceSchemaLocation="Any.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Element> <Root> <Element><Node1><SubElement/></Node1><Node2/></Element> </Root> </Element> </Root> ```
2,242,333
I have tried to substitute $\tan (x)$ and $\cot (x)$ with sine and cosine and it got really messy $$1-\frac{\sin^2x}{1+\cot(x)}-\frac{\cos^2x}{1+\tan x}=?$$ **a)** $1$ **b)** $\sin^2x$ **c)** $\sin (x)+\cos (x)$ **d)** $\sin (x)\cdot \cos (x)$
2017/04/19
[ "https://math.stackexchange.com/questions/2242333", "https://math.stackexchange.com", "https://math.stackexchange.com/users/411175/" ]
We can write this as : here I put $$\cot x= \frac{\cos x}{\sin x}$$ and $$\tan x= \frac{\sin x}{\cos x}$$ $$\sin^2x+\cos^2x-\frac{\sin^3x}{\sin x+\cos x}-\frac{\cos^3x}{\sin x+\cos x}$$ Now take take the $\operatorname{lcm}$ and you'll get something like this: $$\frac {\sin^3x+\cos^3x+ \sin x\cos^2x+\cos x \sin^2x-\sin^3x-\cos^3x}{\sin x+\cos x}$$ then $$\frac{\sin x\cos x(\sin x+\cos x)}{\sin x +\cos x}$$ hence final asnwer is d) $\sin x.\cos x$
note that $$\cot(x)=\frac{\cos(x)}{\sin(x)}$$ and $$\tan(x)=\frac{\sin(x)}{\cos(x)}$$ the result is $$\sin(x)\cos(x)$$ we have $$\frac{(1+\cot(x))(1+\tan(x))-\sin^2(x)(1+\tan(x))-\cos^2(x)(1+\cot(x))}{(1+\cot(x))(1+\tan(x))}$$ multiplying out and we otain $$\frac{1+\frac{\cos(x)}{\sin(x)}+\frac{\sin(x)}{\cos(x)}-\frac{\sin^3(x)}{\cos(x)}-\frac{\cos(x)^3}{\sin(x)}}{(1+\cot(x))(1+\tan(x))}$$ and this is $$\frac{1+\frac{\cos(x)(1-\cos^2(x))}{\sin(x)}+\frac{\sin(x)(1-\sin^2(x))}{\cos(x)}}{(1+\cot(x))(1+\tan(x))}$$ we will work further: $$\frac{1+2\sin(x)\cos(x)}{2+\frac{\cos(x)}{\sin(x)}+\frac{\sin(x)}{\cos(x)}}$$ and this is $$\frac{(1+2\sin(x)\cos(x))\sin(x)\cos(x)}{2\sin(x)\cos(x)+1}=\sin(x)\cos(x)$$
184,305
Which one is grammatically correct or better to use? About before pronoun: > > I haven’t listened to the album about which you were talking. > > > About after verb: > > I haven’t listened to the album which you were talking about. > > >
2018/10/31
[ "https://ell.stackexchange.com/questions/184305", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/6341/" ]
They're both technically correct. I would personally prefer the second one, though, as it sounds more natural. Students of English used to be taught that it was bad grammar to end a sentence with a preposition (like "about"). Following this rule produces sentences like your first example ("about which you were talking"). However, this "rule" is derived from Latin grammar, and English isn't Latin. This "rule" has been falling out of favor since the beginning of the 20th century, because it can produce sentences that don't sound natural. You *can* end a sentence with a preposition, but you don't *have* to. There are many, many articles about this; [here's one from Mirriam-Webster](https://www.merriam-webster.com/words-at-play/prepositions-ending-a-sentence-with).
Ah, well, this gets into the ["ending a sentence with a preposition" debate](https://www.merriam-webster.com/words-at-play/prepositions-ending-a-sentence-with). Some people think it's fine, others don't like it. Personally, I'm in the middle and avoid doing it if possible -- unless the alternative is even more awkward. So, in this case I would say it's fine to have "about" at the end: > > I haven't listened to that album you told me **about**. > > > Or use a different verb: > > I haven't listened to that album you **mentioned**. > > >
16,498
We upgrade to web 8 and upgraded an existing .NET DD4T 1.31 website to .NET DD4T 2.0. We have made necessary changes to compile the Website with latest DD4T 2.0 DLL and web 8 DLLs and JAR files successfully. While Most of the websites works few of the Page templates which uses RenderComponentPresentationsByView is giving empty result. When verified using Tridion Delivery API we are getting correct output. When checked in the below post, it is mentioned to use @Html.Render(cp) while using DD4T View Models. [DD4T good practice: how to render component presentations based on ViewModels](https://tridion.stackexchange.com/questions/14820/dd4t-good-practice-how-to-render-component-presentations-based-on-viewmodels) We are using DD4T View Models, but Since it will take long time to change the code, can you please suggest how can we make RenderComponentPresentationsByView works in DD4T 2.0 Other issue we are facing to call render(cp) function is when we use below syntax we are getting null exception while trying to check component template metadata. ``` @foreach (var cp in Model.ComponentPresentations) { if (CP.ComponentTemplate.MetadataFields["view"].Value =="GenericBannerImage") { @Html.Render(cp) } } ``` Any help would be appreciated. Syntax used : ``` @Html.RenderComponentPresentationsByView("GenericBannerImage") ```
2017/02/11
[ "https://tridion.stackexchange.com/questions/16498", "https://tridion.stackexchange.com", "https://tridion.stackexchange.com/users/1222/" ]
I've found the issues with the DD4T 2.x Core. It happens when using Dynamic Component Presentations. The 1.x Templates don't render Component Template data for the Dynamic Component Presentations, only the Component data. However, the Component Template data is still in the Page. I've made a small fix for this and tested it on my local system. I will submit a bugfix later today, so it can be part of release 2.2. **Update:** The fix is merged and now available in a pre-release: DD4T.Core 2.1.1.145-alpha
Have you checked your logs - ultimately RenderComponentPresentationsByView() calls into the DefaultComponentPresentationRenderer (unless you've provided you own IComponentPresentationRenderer implementation)? Where DefaultComponentPresentationRenderer [checks if the template of the presentation uses a view](https://github.com/dd4t/DD4T.MVC/blob/develop/source/DD4T.Mvc/Html/DefaultComponentPresentationRenderer.cs) you might see a "view for GenericBannerImage not set" - which would suggest you haven't added the view name "GenericBannerImage" into the metadata view field of the component template. You can also call RenderComponentPresentationsByView with a TCM ID too.
597,675
In the datasheet of the "MC33887 5.0 A H-bridge with load current feedback" there is a section on "Output avalanche protection", in which it is explained that an inductive flyback event, namely when the outputs are suddenly disabled and V+ is lost, could result in electrical overstress of the drivers. To prevent this, the V+ input to the 33887 should not exceed the maximum rating during a flyback condition. This may be done with either a Zener clamp and/or an appropriately valued input capacitor with sufficiently low ESR (as in the attached image.) If the Zener diode is used and the V+ voltage must be 24V (VPWR in the attached image), what type of Zener diode could be used and with which breakdown voltage value? [![MC33887 Output avalanche protection](https://i.stack.imgur.com/FGSHX.png)](https://i.stack.imgur.com/FGSHX.png)
2021/12/03
[ "https://electronics.stackexchange.com/questions/597675", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/301342/" ]
The TC is just like an ordinary transformer, but it doesn't have an iron core. At the time NT hadn't a HF power source, so he used a rotary spark to load the capacitor that caused the primary L and C to start oscillating at HF. Then he used the secondary circuit that has a matched resonating frequency. Since the impedance of a series LC circuit as a minimum value at resonance, the current is maximal at that point, so the power. > > does it work same as a normal magnetic field, or is it different from > the normal magnetic field? > > > It can't work any different.
> > We know that the Tesla coil has a low coupling coefficient so most of the energy is transferred by using electric resonance. > > > It has a large spacing between the primary and the high voltage end of the secondary for electrical insulation. This spacing means that the coupling coefficient ends up in the 0.1 to 0.2 region, rather than nearly 1.00 as in conventional cored transformers. It's not 'transferred using electric resonance' as such, it's transferred using standard electromagnetism. However, resonance is necessary to transfer all the energy over a number of cycles. > > How exactly does it transfer the energy? When the oscillating magnetic field induces in the primary, does it work same as a normal magnetic field, or is it different from the normal magnetic field? > > > What is the exact use of an oscillating magnetic field? > > > Qualitatively the same way as in a normal transformer. The change in magnetic field threading the secondary induces a voltage in it. The low coupling is another way of saying that only effectively 10% to 20% of the primary magnetic field threads the secondary. The difference between a close-coupled cored transformer and a loose one like a Tesla Coil is like the difference between moving a swing with your feet on the ground, and 'pumping it up' by sitting on it. With your feet on the ground, you can get hold of the swing and move it to anywhere you want. You and the swing frame are anchored to the ground, and you can apply as much force as you want. This is 100% coupling. On the other hand, 'pumping it up' by sitting on it and moving your centre of gravity about is very weak coupling. Your movement from one position to the next will move the swing by at most a hand-span. You have to repeat this movement again and again at the right times to gradually build up the oscillation of the swing. Resonance allows this to happen, storing the energy from previous movements. The Tesla primary is made resonant to give regularly spaced alternations in the magnetic field (pushes to the secondary). The secondary is tuned to resonate at the same frequency so that its amplitude can build up over a number of cycles.
597,675
In the datasheet of the "MC33887 5.0 A H-bridge with load current feedback" there is a section on "Output avalanche protection", in which it is explained that an inductive flyback event, namely when the outputs are suddenly disabled and V+ is lost, could result in electrical overstress of the drivers. To prevent this, the V+ input to the 33887 should not exceed the maximum rating during a flyback condition. This may be done with either a Zener clamp and/or an appropriately valued input capacitor with sufficiently low ESR (as in the attached image.) If the Zener diode is used and the V+ voltage must be 24V (VPWR in the attached image), what type of Zener diode could be used and with which breakdown voltage value? [![MC33887 Output avalanche protection](https://i.stack.imgur.com/FGSHX.png)](https://i.stack.imgur.com/FGSHX.png)
2021/12/03
[ "https://electronics.stackexchange.com/questions/597675", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/301342/" ]
> > *How exactly does it transfer the energy?* > > > It transfers energy using magnetic induction. The fact that the coupling is small serves only to limit the energy transferred. And, the fact that the coupling is small allows the primary and secondary coils to have rather large resonant peaks at the same frequency.
> > We know that the Tesla coil has a low coupling coefficient so most of the energy is transferred by using electric resonance. > > > It has a large spacing between the primary and the high voltage end of the secondary for electrical insulation. This spacing means that the coupling coefficient ends up in the 0.1 to 0.2 region, rather than nearly 1.00 as in conventional cored transformers. It's not 'transferred using electric resonance' as such, it's transferred using standard electromagnetism. However, resonance is necessary to transfer all the energy over a number of cycles. > > How exactly does it transfer the energy? When the oscillating magnetic field induces in the primary, does it work same as a normal magnetic field, or is it different from the normal magnetic field? > > > What is the exact use of an oscillating magnetic field? > > > Qualitatively the same way as in a normal transformer. The change in magnetic field threading the secondary induces a voltage in it. The low coupling is another way of saying that only effectively 10% to 20% of the primary magnetic field threads the secondary. The difference between a close-coupled cored transformer and a loose one like a Tesla Coil is like the difference between moving a swing with your feet on the ground, and 'pumping it up' by sitting on it. With your feet on the ground, you can get hold of the swing and move it to anywhere you want. You and the swing frame are anchored to the ground, and you can apply as much force as you want. This is 100% coupling. On the other hand, 'pumping it up' by sitting on it and moving your centre of gravity about is very weak coupling. Your movement from one position to the next will move the swing by at most a hand-span. You have to repeat this movement again and again at the right times to gradually build up the oscillation of the swing. Resonance allows this to happen, storing the energy from previous movements. The Tesla primary is made resonant to give regularly spaced alternations in the magnetic field (pushes to the secondary). The secondary is tuned to resonate at the same frequency so that its amplitude can build up over a number of cycles.
6,840,579
I am using tabcontainer control of Ajaxtoolkit.I want to load aspx page for each of the tabs asynchronously i.e when i click on tab at that time an aspx page should be loaded
2011/07/27
[ "https://Stackoverflow.com/questions/6840579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367339/" ]
Valid from Symfony v2.1 through v6.0+ If you want the base URL to a Symfony application, you should use `getSchemeAndHttpHost()` concatenated together with `getBaseUrl()`, similar to how `getUri()` works, except without the router path and query string. ``` {{ app.request.schemeAndHttpHost ~ app.request.baseUrl }} ``` For example, if your Symfony website URL lives at `https://www.stackoverflow.com/webapp/`, then these two methods return these values: **getSchemeAndHttpHost** ``` https://www.stackoverflow.com ``` **getBaseUrl** ``` /webapp ``` *Note: `getBaseUrl()` includes the script filename (ie `/app.php`) if it's in your URL.*
Also for js/css/image urls there's handy function asset() ``` <img src="{{ asset('image/logo.png') }}"/> ``` This creates an absolute url starting with `/`.
6,840,579
I am using tabcontainer control of Ajaxtoolkit.I want to load aspx page for each of the tabs asynchronously i.e when i click on tab at that time an aspx page should be loaded
2011/07/27
[ "https://Stackoverflow.com/questions/6840579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367339/" ]
Base url is defined inside `Symfony\Component\Routing\RequestContext`. It can be fetched from controller like this: ``` $this->container->get('router')->getContext()->getBaseUrl() ```
Instead of passing variable to template globally, you can define a base template and render the 'global part' in it. The base template can be inherited. Example of rendering template From the symfony Documentation: ``` <div id="sidebar"> {% render "AcmeArticleBundle:Article:recentArticles" with {'max': 3} %} </div> ```
6,840,579
I am using tabcontainer control of Ajaxtoolkit.I want to load aspx page for each of the tabs asynchronously i.e when i click on tab at that time an aspx page should be loaded
2011/07/27
[ "https://Stackoverflow.com/questions/6840579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367339/" ]
In Symfony 5 and in the common situation of a controller method use the injected *Request* object: ``` public function controllerFunction(Request $request, LoggerInterface $logger) ... $scheme = $request->getSchemeAndHttpHost(); $logger->info('Domain is: ' . $scheme); ... //prepare to render $retarray = array( ... 'scheme' => $scheme, ... ); return $this->render('Template.html.twig', $retarray); } ```
In one situation involving a multi-domain application, `app.request.getHttpHost` helped me out. It returns something like `example.com` or `subdomain.example.com` (or `example.com:8000` when the port is not standard). This was in Symfony 3.4.
6,840,579
I am using tabcontainer control of Ajaxtoolkit.I want to load aspx page for each of the tabs asynchronously i.e when i click on tab at that time an aspx page should be loaded
2011/07/27
[ "https://Stackoverflow.com/questions/6840579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367339/" ]
Why do you need to get this root url ? Can't you generate directly absolute URL's ? ``` {{ url('_demo_hello', { 'name': 'Thomas' }) }} ``` This Twig code will generate the full http:// url to the \_demo\_hello route. In fact, getting the base url of the website is only getting the full url of the homepage route : ``` {{ url('homepage') }} ``` (*homepage*, or whatever you call it in your routing file).
For Symfony 2.3+, to get the base url in a controller should be ``` $this->get('request')->getSchemeAndHttpHost(); ```
6,840,579
I am using tabcontainer control of Ajaxtoolkit.I want to load aspx page for each of the tabs asynchronously i.e when i click on tab at that time an aspx page should be loaded
2011/07/27
[ "https://Stackoverflow.com/questions/6840579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367339/" ]
Valid from Symfony v2.1 through v6.0+ If you want the base URL to a Symfony application, you should use `getSchemeAndHttpHost()` concatenated together with `getBaseUrl()`, similar to how `getUri()` works, except without the router path and query string. ``` {{ app.request.schemeAndHttpHost ~ app.request.baseUrl }} ``` For example, if your Symfony website URL lives at `https://www.stackoverflow.com/webapp/`, then these two methods return these values: **getSchemeAndHttpHost** ``` https://www.stackoverflow.com ``` **getBaseUrl** ``` /webapp ``` *Note: `getBaseUrl()` includes the script filename (ie `/app.php`) if it's in your URL.*
For current Symfony version (as of writing this answer it's Symfony 4.1) do not directly access the service container as done in some of the other answers. Instead (unless you don't use the standard services configuration), inject the request object by type-hinting. ``` <?php namespace App\Service; use Symfony\Component\HttpFoundation\RequestStack; /** * The YourService class provides a method for retrieving the base URL. * * @package App\Service */ class YourService { /** * @var string */ protected $baseUrl; /** * YourService constructor. * * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack */ public function __construct(RequestStack $requestStack) { $this->baseUrl = $requestStack->getCurrentRequest()->getSchemeAndHttpHost(); } /** * Returns the current base URL. * * @return string */ public function getBaseUrl(): string { return $this->baseUrl; } } ``` See also official Symfony docs about [how to retrieve the current request object](https://symfony.com/doc/current/service_container/request.html).
6,840,579
I am using tabcontainer control of Ajaxtoolkit.I want to load aspx page for each of the tabs asynchronously i.e when i click on tab at that time an aspx page should be loaded
2011/07/27
[ "https://Stackoverflow.com/questions/6840579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367339/" ]
Why do you need to get this root url ? Can't you generate directly absolute URL's ? ``` {{ url('_demo_hello', { 'name': 'Thomas' }) }} ``` This Twig code will generate the full http:// url to the \_demo\_hello route. In fact, getting the base url of the website is only getting the full url of the homepage route : ``` {{ url('homepage') }} ``` (*homepage*, or whatever you call it in your routing file).
This is now available for free in twig templates (tested on sf2 version 2.0.14) ``` {{ app.request.getBaseURL() }} ``` In later Symfony versions (tested on 2.5), try : ``` {{ app.request.getSchemeAndHttpHost() }} ```
6,840,579
I am using tabcontainer control of Ajaxtoolkit.I want to load aspx page for each of the tabs asynchronously i.e when i click on tab at that time an aspx page should be loaded
2011/07/27
[ "https://Stackoverflow.com/questions/6840579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367339/" ]
You can use the new request method `getSchemeAndHttpHost()`: ``` {{ app.request.getSchemeAndHttpHost() }} ```
In one situation involving a multi-domain application, `app.request.getHttpHost` helped me out. It returns something like `example.com` or `subdomain.example.com` (or `example.com:8000` when the port is not standard). This was in Symfony 3.4.
6,840,579
I am using tabcontainer control of Ajaxtoolkit.I want to load aspx page for each of the tabs asynchronously i.e when i click on tab at that time an aspx page should be loaded
2011/07/27
[ "https://Stackoverflow.com/questions/6840579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367339/" ]
Also for js/css/image urls there's handy function asset() ``` <img src="{{ asset('image/logo.png') }}"/> ``` This creates an absolute url starting with `/`.
In Symfony 5 and in the common situation of a controller method use the injected *Request* object: ``` public function controllerFunction(Request $request, LoggerInterface $logger) ... $scheme = $request->getSchemeAndHttpHost(); $logger->info('Domain is: ' . $scheme); ... //prepare to render $retarray = array( ... 'scheme' => $scheme, ... ); return $this->render('Template.html.twig', $retarray); } ```
6,840,579
I am using tabcontainer control of Ajaxtoolkit.I want to load aspx page for each of the tabs asynchronously i.e when i click on tab at that time an aspx page should be loaded
2011/07/27
[ "https://Stackoverflow.com/questions/6840579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367339/" ]
For current Symfony version (as of writing this answer it's Symfony 4.1) do not directly access the service container as done in some of the other answers. Instead (unless you don't use the standard services configuration), inject the request object by type-hinting. ``` <?php namespace App\Service; use Symfony\Component\HttpFoundation\RequestStack; /** * The YourService class provides a method for retrieving the base URL. * * @package App\Service */ class YourService { /** * @var string */ protected $baseUrl; /** * YourService constructor. * * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack */ public function __construct(RequestStack $requestStack) { $this->baseUrl = $requestStack->getCurrentRequest()->getSchemeAndHttpHost(); } /** * Returns the current base URL. * * @return string */ public function getBaseUrl(): string { return $this->baseUrl; } } ``` See also official Symfony docs about [how to retrieve the current request object](https://symfony.com/doc/current/service_container/request.html).
In one situation involving a multi-domain application, `app.request.getHttpHost` helped me out. It returns something like `example.com` or `subdomain.example.com` (or `example.com:8000` when the port is not standard). This was in Symfony 3.4.
6,840,579
I am using tabcontainer control of Ajaxtoolkit.I want to load aspx page for each of the tabs asynchronously i.e when i click on tab at that time an aspx page should be loaded
2011/07/27
[ "https://Stackoverflow.com/questions/6840579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367339/" ]
Valid from Symfony v2.1 through v6.0+ If you want the base URL to a Symfony application, you should use `getSchemeAndHttpHost()` concatenated together with `getBaseUrl()`, similar to how `getUri()` works, except without the router path and query string. ``` {{ app.request.schemeAndHttpHost ~ app.request.baseUrl }} ``` For example, if your Symfony website URL lives at `https://www.stackoverflow.com/webapp/`, then these two methods return these values: **getSchemeAndHttpHost** ``` https://www.stackoverflow.com ``` **getBaseUrl** ``` /webapp ``` *Note: `getBaseUrl()` includes the script filename (ie `/app.php`) if it's in your URL.*
``` <base href="{{ app.request.getSchemeAndHttpHost() }}"/> ``` or from controller ``` $this->container->get('router')->getContext()->getSchemeAndHttpHost() ```
33,587,676
Trying to call Dropbox API v2. ``` Dim client = New RestClient("https://api.dropboxapi.com/2/") Dim request = New RestRequest("files/search", Method.POST) request.AddHeader("Authorization", "Bearer " & MYTOKEN) request.AddHeader("Content-Type", "application/json") 'request.RequestFormat = DataFormat.Json 'request.JsonSerializer.ContentType = "application/json; charset=utf-8;" 'request.AddParameter("Content-Type", "application/json") request.AddParameter("path", "") request.AddParameter("query", "my file") request.AddParameter("start", "0") request.AddParameter("max_results", "1") request.AddParameter("mode", "filename") Dim res = client.Execute(request) ``` Always return ``` Error in call to API function "files/search": Bad HTTP "Content-Type" header: "application/x-www-form-urlencoded". Expecting one of "application/json", "application/json; charset=utf-8", "text/plain; charset=dropbox-cors-hack" ``` Tried the commented code lines but still the same response. Any clue?
2015/11/07
[ "https://Stackoverflow.com/questions/33587676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2105488/" ]
If my guesses are right, and this is Visual Basic code using RestSharp, then I think you need something like this (apologies if it's not quite right; I don't know VB syntax): ``` Dim client = New RestClient("https://api.dropboxapi.com/2/") Dim request = New RestRequest("files/search", Method.POST) request.AddHeader("Authorization", "Bearer " & MYTOKEN) request.RequestFormat = DataFormat.Json request.AddBody(New With { .path = "", .query = "my file", .start = 0, .max_results = 1, .mode = "filename" }) Dim res = client.Execute(request) ```
Solved it like this. There could be better ways to do it but this works for now. ``` Dim client = New RestClient("https://api.dropboxapi.com/2/") Dim request = New RestRequest("files/search", Method.POST) request.AddHeader("Authorization", "Bearer " & MYTOKEN) request.AddHeader("Content-Type", "application/json") '---> this line still doesn't seem to do anything Dim json As New JObject(New JProperty("path", ""), New JProperty("query", "my file"), New JProperty("max_results", 1), New JProperty("mode", "filename")) request.AddParameter("application/json", json, ParameterType.RequestBody) Dim res = client.Execute(request) ``` Dropbox API appears to be very sensitive as for example, the object in AddParameter cannot be a json string, it must be json object. And "1" say in max\_results doesn't work, it must be 1 without the quotes. A lot of trial and error but finally worked.
259,410
If I have multiple downloads I can have them all download simultaneously or pause one and let the other download and then when the 1st is done I manually pause it and have the second download, afterward I let both seed for a while. But How can I set it so that the 2nd torrent will start downloading only after the 1st has finished. And is it possible to have the 1st pause seeding after it has finished downloading. I have nothing against seeding but I want to wait till all my downloads are done before sole seeding. If these things aren't possible in uTorrent is there another client that handles these things?
2011/03/18
[ "https://superuser.com/questions/259410", "https://superuser.com", "https://superuser.com/users/72413/" ]
For your first question: Options → Preferences → Queuing → Max. number of active downloads = 1 ![enter image description here](https://i.stack.imgur.com/uS83a.png) For the second one, under seeding goals, keep it as zero and if required, put a limit on the upload rate.
Go to Options>Preferences>Queuing You can set it there.
69,252,723
appols if this is a repeat, but I couldn't find a similar issue anywhere. I've a number of select and input elements wihtin td elements as part of a table that I want to collect the values of for some validation within Javascript. I was hoping to use getElementsByName javascript to collect said data, but it appears as if these elements that are within the table are 'not' collected (all node lists are empty lists).... however, getElementById does appear to work for these element values. Is this a known scenario where getElementsByName cannot be used? Extract of my code below (i've made it a shorted version, since actual table is a log larger, but made it easier to read: ``` `fc = document.getElementsByName('forwarding_class'); min_bw = document.getElementsByName('min_bw'); exact = document.getElementsByName('exact'); //Do some validation on node list fc etc..... <form action="#" method="post" class="form-horizontal"> <div class="row"> <div class="col-sm-10"> <table id="cos_policy" name="cos_policy" class="display table table-hover table-bordered table-striped"> <thead> <tr style="background-color: #7E0305; color: white;"> <th style="width: 10%; text-align:center;">Forwarding Class</th> <th style="width: 10%; text-align:center;">Min BW(%)</th> <th style="width: 10%; text-align:center;">Exact</th> </tr> </thead> <tbody id="cos_policy_table_body"> <tr> <td hidden=""><input name="class_table[]" id="class_table0" value="GWR"></td> <td hidden=""><input name="id[]" value="" hidden="" id="id0"></td> <td><select name="forwarding_class[]" id="forwarding_class0" class="form-control"> <option value="">Select One</option> <option value="VF-Premium">VF-Premium</option> <option value="VF-Enhanced1">VF-Enhanced1</option> </select></td> <td><input class="form-control" id="min_bw0" name="min_bw[]" style="width: 100%;" value=""></td> <td><select name="exact[]" id="exact0" class="form-control" style="width: 100%;"> <option value="">Select One</option><option value="True">True</option> <option value="False">False</option> </select></td> </tr><tbody> </form>` ```
2021/09/20
[ "https://Stackoverflow.com/questions/69252723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14764338/" ]
### Fixing the indices The range of your indices is inconsistent with the way you use them in the loop. You can use either of the following two possible loops, but don't mix them: ```py for n in range(1, N+1): x[n] = r**n * x[0] ``` ```py for n in range(0, N): x[n+1] = r**(n+1) * x[0] ``` ### Optimization: multiplications instead of exponentiations Note that computing an exponent `**` is always more costly than computing a multiplication `*`; you can slightly optimize your code by using a recurrence formula: ```py for n in range(1, N+1): x[n] = r * x[n-1] ``` ```py for n in range(0, N): x[n+1] = r * x[n] ``` ### Using library functions: `itertools`, `numpy` or `pandas` What you are asking for is called a **geometric progression**. Python provides several ways of computing geometric progressions without writing the loop yourself. * [Documentation: numpy.geomspace](https://numpy.org/doc/stable/reference/generated/numpy.geomspace.html) * [Documentation: itertools.accumulate](https://docs.python.org/3/library/itertools.html#itertools.accumulate) * [Question: Geometric progression using Python / Pandas / Numpy](https://stackoverflow.com/questions/20903865/geometric-progression-using-python-pandas-numpy-without-loop-and-using-recu) * [Question: python geometric sequence](https://stackoverflow.com/questions/15061704/python-geometric-sequence) * [Question: Generate a geometric progression using list comprehension](https://stackoverflow.com/questions/38235829/python-generate-a-geometric-progression-using-list-comprehension) * [Question: Making a list of a geometric progression when the ratio and range are given](https://stackoverflow.com/questions/55654286/making-a-list-of-a-geometric-progression-when-the-ratio-and-range-are-given) * [Question: Writing python code to calculate a Geometric progression](https://stackoverflow.com/questions/18800804/writing-python-code-to-calculate-a-geometric-progression) For instance: ```py import itertools # accumulate, repeat import operator # mul def geometric_progression(x0, r, N): return list(itertools.accumulate(itertools.repeat(r,N), operator.mul, initial=x0)) print(geometric_progression(1000, 1.2, 10)) # [1000, 1200.0, 1440.0, 1728.0, 2073.6, 2488.3199999999997, 2985.9839999999995, 3583.180799999999, 4299.816959999999, 5159.780351999999, 6191.736422399998] ```
The length of your array is 11, which means the last element is accessed by `x[10]`. But in the loop, the value being called when n is 10 is `x[11]` which makes it go out of range. I'm not sure about the constraints of your problem, but if you want to access `x[11]`, change the total size of the array to `x = (N+2)*[0]`. **Output** ``` x[1] = 1040.4 x[2] = 1061.208 x[3] = 1082.43216 x[4] = 1104.0808032 x[5] = 1126.1624192640002 x[6] = 1148.68566764928 x[7] = 1171.6593810022657 x[8] = 1195.092568622311 x[9] = 1218.9944199947574 x[10] = 1243.3743083946524 ```
69,252,723
appols if this is a repeat, but I couldn't find a similar issue anywhere. I've a number of select and input elements wihtin td elements as part of a table that I want to collect the values of for some validation within Javascript. I was hoping to use getElementsByName javascript to collect said data, but it appears as if these elements that are within the table are 'not' collected (all node lists are empty lists).... however, getElementById does appear to work for these element values. Is this a known scenario where getElementsByName cannot be used? Extract of my code below (i've made it a shorted version, since actual table is a log larger, but made it easier to read: ``` `fc = document.getElementsByName('forwarding_class'); min_bw = document.getElementsByName('min_bw'); exact = document.getElementsByName('exact'); //Do some validation on node list fc etc..... <form action="#" method="post" class="form-horizontal"> <div class="row"> <div class="col-sm-10"> <table id="cos_policy" name="cos_policy" class="display table table-hover table-bordered table-striped"> <thead> <tr style="background-color: #7E0305; color: white;"> <th style="width: 10%; text-align:center;">Forwarding Class</th> <th style="width: 10%; text-align:center;">Min BW(%)</th> <th style="width: 10%; text-align:center;">Exact</th> </tr> </thead> <tbody id="cos_policy_table_body"> <tr> <td hidden=""><input name="class_table[]" id="class_table0" value="GWR"></td> <td hidden=""><input name="id[]" value="" hidden="" id="id0"></td> <td><select name="forwarding_class[]" id="forwarding_class0" class="form-control"> <option value="">Select One</option> <option value="VF-Premium">VF-Premium</option> <option value="VF-Enhanced1">VF-Enhanced1</option> </select></td> <td><input class="form-control" id="min_bw0" name="min_bw[]" style="width: 100%;" value=""></td> <td><select name="exact[]" id="exact0" class="form-control" style="width: 100%;"> <option value="">Select One</option><option value="True">True</option> <option value="False">False</option> </select></td> </tr><tbody> </form>` ```
2021/09/20
[ "https://Stackoverflow.com/questions/69252723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14764338/" ]
I think your problem that you should remember the index of any element in the `list` starting from **zero** and the index of the last element is `N - 1` where `N` is the count of the elements in the `list`. So you should make this change in your `for` loop: ``` for n in range(0, N): ``` Also, your using of `print` should be a reflection to the data in your `list`. So you should fix the argument of your `print` function to the following: ``` print(f"x[{n+1}] = {x[n+1]}") ``` After making these changes, you will get this result: ``` x[1] = 1020.0 x[2] = 1040.4 x[3] = 1061.208 x[4] = 1082.43216 x[5] = 1104.0808032 x[6] = 1126.1624192640002 x[7] = 1148.68566764928 x[8] = 1171.6593810022657 x[9] = 1195.092568622311 x[10] = 1218.9944199947574 ``` Please, Note you have `N + 1` elements **not** `N` elements in your `list` because of this line of your code ``` x = (N+1)*[0] ``` Hope this help.
The length of your array is 11, which means the last element is accessed by `x[10]`. But in the loop, the value being called when n is 10 is `x[11]` which makes it go out of range. I'm not sure about the constraints of your problem, but if you want to access `x[11]`, change the total size of the array to `x = (N+2)*[0]`. **Output** ``` x[1] = 1040.4 x[2] = 1061.208 x[3] = 1082.43216 x[4] = 1104.0808032 x[5] = 1126.1624192640002 x[6] = 1148.68566764928 x[7] = 1171.6593810022657 x[8] = 1195.092568622311 x[9] = 1218.9944199947574 x[10] = 1243.3743083946524 ```
69,252,723
appols if this is a repeat, but I couldn't find a similar issue anywhere. I've a number of select and input elements wihtin td elements as part of a table that I want to collect the values of for some validation within Javascript. I was hoping to use getElementsByName javascript to collect said data, but it appears as if these elements that are within the table are 'not' collected (all node lists are empty lists).... however, getElementById does appear to work for these element values. Is this a known scenario where getElementsByName cannot be used? Extract of my code below (i've made it a shorted version, since actual table is a log larger, but made it easier to read: ``` `fc = document.getElementsByName('forwarding_class'); min_bw = document.getElementsByName('min_bw'); exact = document.getElementsByName('exact'); //Do some validation on node list fc etc..... <form action="#" method="post" class="form-horizontal"> <div class="row"> <div class="col-sm-10"> <table id="cos_policy" name="cos_policy" class="display table table-hover table-bordered table-striped"> <thead> <tr style="background-color: #7E0305; color: white;"> <th style="width: 10%; text-align:center;">Forwarding Class</th> <th style="width: 10%; text-align:center;">Min BW(%)</th> <th style="width: 10%; text-align:center;">Exact</th> </tr> </thead> <tbody id="cos_policy_table_body"> <tr> <td hidden=""><input name="class_table[]" id="class_table0" value="GWR"></td> <td hidden=""><input name="id[]" value="" hidden="" id="id0"></td> <td><select name="forwarding_class[]" id="forwarding_class0" class="form-control"> <option value="">Select One</option> <option value="VF-Premium">VF-Premium</option> <option value="VF-Enhanced1">VF-Enhanced1</option> </select></td> <td><input class="form-control" id="min_bw0" name="min_bw[]" style="width: 100%;" value=""></td> <td><select name="exact[]" id="exact0" class="form-control" style="width: 100%;"> <option value="">Select One</option><option value="True">True</option> <option value="False">False</option> </select></td> </tr><tbody> </form>` ```
2021/09/20
[ "https://Stackoverflow.com/questions/69252723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14764338/" ]
### Fixing the indices The range of your indices is inconsistent with the way you use them in the loop. You can use either of the following two possible loops, but don't mix them: ```py for n in range(1, N+1): x[n] = r**n * x[0] ``` ```py for n in range(0, N): x[n+1] = r**(n+1) * x[0] ``` ### Optimization: multiplications instead of exponentiations Note that computing an exponent `**` is always more costly than computing a multiplication `*`; you can slightly optimize your code by using a recurrence formula: ```py for n in range(1, N+1): x[n] = r * x[n-1] ``` ```py for n in range(0, N): x[n+1] = r * x[n] ``` ### Using library functions: `itertools`, `numpy` or `pandas` What you are asking for is called a **geometric progression**. Python provides several ways of computing geometric progressions without writing the loop yourself. * [Documentation: numpy.geomspace](https://numpy.org/doc/stable/reference/generated/numpy.geomspace.html) * [Documentation: itertools.accumulate](https://docs.python.org/3/library/itertools.html#itertools.accumulate) * [Question: Geometric progression using Python / Pandas / Numpy](https://stackoverflow.com/questions/20903865/geometric-progression-using-python-pandas-numpy-without-loop-and-using-recu) * [Question: python geometric sequence](https://stackoverflow.com/questions/15061704/python-geometric-sequence) * [Question: Generate a geometric progression using list comprehension](https://stackoverflow.com/questions/38235829/python-generate-a-geometric-progression-using-list-comprehension) * [Question: Making a list of a geometric progression when the ratio and range are given](https://stackoverflow.com/questions/55654286/making-a-list-of-a-geometric-progression-when-the-ratio-and-range-are-given) * [Question: Writing python code to calculate a Geometric progression](https://stackoverflow.com/questions/18800804/writing-python-code-to-calculate-a-geometric-progression) For instance: ```py import itertools # accumulate, repeat import operator # mul def geometric_progression(x0, r, N): return list(itertools.accumulate(itertools.repeat(r,N), operator.mul, initial=x0)) print(geometric_progression(1000, 1.2, 10)) # [1000, 1200.0, 1440.0, 1728.0, 2073.6, 2488.3199999999997, 2985.9839999999995, 3583.180799999999, 4299.816959999999, 5159.780351999999, 6191.736422399998] ```
I think your problem that you should remember the index of any element in the `list` starting from **zero** and the index of the last element is `N - 1` where `N` is the count of the elements in the `list`. So you should make this change in your `for` loop: ``` for n in range(0, N): ``` Also, your using of `print` should be a reflection to the data in your `list`. So you should fix the argument of your `print` function to the following: ``` print(f"x[{n+1}] = {x[n+1]}") ``` After making these changes, you will get this result: ``` x[1] = 1020.0 x[2] = 1040.4 x[3] = 1061.208 x[4] = 1082.43216 x[5] = 1104.0808032 x[6] = 1126.1624192640002 x[7] = 1148.68566764928 x[8] = 1171.6593810022657 x[9] = 1195.092568622311 x[10] = 1218.9944199947574 ``` Please, Note you have `N + 1` elements **not** `N` elements in your `list` because of this line of your code ``` x = (N+1)*[0] ``` Hope this help.
454,414
Noise-canceling headphones can reduce a lot of ambient sound, but they are not 100% perfect. (Especially in the human vocal range.) 1. Is there any physical principle preventing the creation of perfect sound-canceling headphones? In other words, headphones that can cancel or block 100% of all external sound before it reaches my ears. (I realize that I would still hear internal body sounds, of course.) 2. Now, instead of headphones, how about a device that can cancel all the sound in the room for all the listeners in the room?
2019/01/15
[ "https://physics.stackexchange.com/questions/454414", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/134671/" ]
Light waves in a linear medium such as the vacuum do not interact with each other at all, so the answer is "no".
No, photons create pressure when they interact with electrons in matter. Photon waves travel right through each other, similar to water waves, they do superimpose but only temporarily and then continue on their way.
454,414
Noise-canceling headphones can reduce a lot of ambient sound, but they are not 100% perfect. (Especially in the human vocal range.) 1. Is there any physical principle preventing the creation of perfect sound-canceling headphones? In other words, headphones that can cancel or block 100% of all external sound before it reaches my ears. (I realize that I would still hear internal body sounds, of course.) 2. Now, instead of headphones, how about a device that can cancel all the sound in the room for all the listeners in the room?
2019/01/15
[ "https://physics.stackexchange.com/questions/454414", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/134671/" ]
The scattering of light by light is a very tiny quantum effect that was first observed in 2016 with high-energy photons at the Large Hadron Collider. <https://en.wikipedia.org/wiki/Two-photon_physics> Most of the time, photons do not interact with each other. When they occasionally do, they do not do so directly but instead indirectly through virtual electrons and positrons, or, even more rarely, through other charged particle-antiparticle pairs. [![enter image description here](https://i.stack.imgur.com/0JKdE.png)](https://i.stack.imgur.com/0JKdE.png) (Picture from Wikipedia.) The cross section for this scattering process, in the zero-total-momentum frame, averaged over the polarization of the photons, can be calculated and is $$\sigma(\gamma\gamma\rightarrow\gamma\gamma)=\frac{973\alpha^4\omega^6}{10125\pi m^8}$$ where $\alpha$ is the fine-structure constant, $\omega$ is the angular frequency of each of the two photons in the zero-total-momentum frame, and $m$ is the mass of the electron. This formula applies when $\omega$ is small compared to $m$ and is in natural units where $\hbar=c=1$. <https://arxiv.org/abs/1111.6126> For example, the cross section for green light with frequency 600 THz is $1.7\times10^{-67}\;\text{m}^2$. In other words, green photons behave as if they have a "radius" of about $2\times10^{-19}$ fermi. By contrast, the radius of a proton is about 0.9 fermi, so this shows how fantastically small the cross section is and how unlikely visible photons are to scatter off of each other. The effect is only observable with very high-energy photons.
Light waves in a linear medium such as the vacuum do not interact with each other at all, so the answer is "no".
454,414
Noise-canceling headphones can reduce a lot of ambient sound, but they are not 100% perfect. (Especially in the human vocal range.) 1. Is there any physical principle preventing the creation of perfect sound-canceling headphones? In other words, headphones that can cancel or block 100% of all external sound before it reaches my ears. (I realize that I would still hear internal body sounds, of course.) 2. Now, instead of headphones, how about a device that can cancel all the sound in the room for all the listeners in the room?
2019/01/15
[ "https://physics.stackexchange.com/questions/454414", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/134671/" ]
Light waves in a linear medium such as the vacuum do not interact with each other at all, so the answer is "no".
TLDR: no, photons do not normally react with each other. All of the answers above are technically correct (*the best kind of correct*), but I'm not sure they really explain what's going on if I'm reading your post correctly. I'll try using a toy model to illustrate some of the main features. Particles with electrical charge, like the electron, produce a "sea" of "virtual photon"s around them. We'll skip the details of this for now, they're ultimately not important to this discussion. What is important is this: for every virtual photon, there is, over time, the exact opposite photon. So for instance, if the electron "releases" a photon going left with energy 1, it will also release one going right with energy 1. When you sum up all of this, you get zero. That makes sense, otherwise the electron would evaporate. Now another important point is that the spectrum of these virtual photons is very specific - there is a relationship between their energy and the time before they are zeroed out again. So high-energy photons exist, but only for short times, and vice versa. When you add in this wrinkle you get something *very* interesting; the energy density of the overall "sea" (or "cloud", what have you) drops off **almost exactly like the classical electric field.** Ok, so how does this cause a force? Well consider what happens when one of these things hits another electron. It is absorbed. So that second electron has now picked up the momentum from the virtual photon, and that makes it move away from the original electron. But even more interesting: since that electron was absorbed, the original electron now has a partner virtual electron that no longer has its partner. And that one had the exact opposite momentum, so that means the original electron starts moving away from the second. **Just like classical electric force.** So what does all of this have to do with your original question? Well, photons are *not* electrically charged. That means they *don't* (normally) give off these virtual photons. That means they don't have an field, and that means, basically, **they ignore each other completely**. Now the caveat to that statement is outlined by G. Smith above - at very very high energies other things start to occur that mean that two photons may indeed recoil from each other, but I don't think that's what you're asking about.
454,414
Noise-canceling headphones can reduce a lot of ambient sound, but they are not 100% perfect. (Especially in the human vocal range.) 1. Is there any physical principle preventing the creation of perfect sound-canceling headphones? In other words, headphones that can cancel or block 100% of all external sound before it reaches my ears. (I realize that I would still hear internal body sounds, of course.) 2. Now, instead of headphones, how about a device that can cancel all the sound in the room for all the listeners in the room?
2019/01/15
[ "https://physics.stackexchange.com/questions/454414", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/134671/" ]
The scattering of light by light is a very tiny quantum effect that was first observed in 2016 with high-energy photons at the Large Hadron Collider. <https://en.wikipedia.org/wiki/Two-photon_physics> Most of the time, photons do not interact with each other. When they occasionally do, they do not do so directly but instead indirectly through virtual electrons and positrons, or, even more rarely, through other charged particle-antiparticle pairs. [![enter image description here](https://i.stack.imgur.com/0JKdE.png)](https://i.stack.imgur.com/0JKdE.png) (Picture from Wikipedia.) The cross section for this scattering process, in the zero-total-momentum frame, averaged over the polarization of the photons, can be calculated and is $$\sigma(\gamma\gamma\rightarrow\gamma\gamma)=\frac{973\alpha^4\omega^6}{10125\pi m^8}$$ where $\alpha$ is the fine-structure constant, $\omega$ is the angular frequency of each of the two photons in the zero-total-momentum frame, and $m$ is the mass of the electron. This formula applies when $\omega$ is small compared to $m$ and is in natural units where $\hbar=c=1$. <https://arxiv.org/abs/1111.6126> For example, the cross section for green light with frequency 600 THz is $1.7\times10^{-67}\;\text{m}^2$. In other words, green photons behave as if they have a "radius" of about $2\times10^{-19}$ fermi. By contrast, the radius of a proton is about 0.9 fermi, so this shows how fantastically small the cross section is and how unlikely visible photons are to scatter off of each other. The effect is only observable with very high-energy photons.
No, photons create pressure when they interact with electrons in matter. Photon waves travel right through each other, similar to water waves, they do superimpose but only temporarily and then continue on their way.