qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
6,123,544 |
In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
```
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
```
2.
```
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
```
Which is more preferable and why?
|
2011/05/25
|
['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']
|
I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.
|
I'd go for the first one.
Reason: If you ever want to change the guard name (say, `SOME_CLASS` to `SOMECLASS`), you don't have to scroll all the way down to the end of file to change it too.
|
6,123,544 |
In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
```
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
```
2.
```
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
```
Which is more preferable and why?
|
2011/05/25
|
['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']
|
I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.
|
The best option is to use `#pragma once`. With `#define` you must be very careful when using multiple libraries as the guard name may not be unique.
|
6,123,544 |
In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
```
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
```
2.
```
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
```
Which is more preferable and why?
|
2011/05/25
|
['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']
|
I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.
|
I prefer the first option. Suppose you include more files, and these files in turn include the file containing `#ifndef SOME_CLASS`.
I think it's fairly easy to spot include errors, if the `#define SOME_CLASS` isn't adjacent to `#ifndef SOME_CLASS`.
```
// SomeClass.h
#ifndef SOME_CLASS
#include "OtherFile.h" // will eventually lead to #include "SomeClass.h"
#define SOME_CLASS
... boat load of code here...
#endif // SOME_CLASS
```
|
6,123,544 |
In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
```
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
```
2.
```
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
```
Which is more preferable and why?
|
2011/05/25
|
['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']
|
I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.
|
The first option is commonly optimized by compilers to behave like the non-standard `#pragma once`.
It is also safer in case of recursive includes. If, in the `//code...` part, you include another header which includes .... which includes the header you're currently editing, then the second version won't work.
|
6,123,544 |
In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
```
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
```
2.
```
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
```
Which is more preferable and why?
|
2011/05/25
|
['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']
|
I'd go for the first one.
Reason: If you ever want to change the guard name (say, `SOME_CLASS` to `SOMECLASS`), you don't have to scroll all the way down to the end of file to change it too.
|
The best option is to use `#pragma once`. With `#define` you must be very careful when using multiple libraries as the guard name may not be unique.
|
6,123,544 |
In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
```
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
```
2.
```
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
```
Which is more preferable and why?
|
2011/05/25
|
['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']
|
I'd go for the first one.
Reason: If you ever want to change the guard name (say, `SOME_CLASS` to `SOMECLASS`), you don't have to scroll all the way down to the end of file to change it too.
|
I prefer the first option. Suppose you include more files, and these files in turn include the file containing `#ifndef SOME_CLASS`.
I think it's fairly easy to spot include errors, if the `#define SOME_CLASS` isn't adjacent to `#ifndef SOME_CLASS`.
```
// SomeClass.h
#ifndef SOME_CLASS
#include "OtherFile.h" // will eventually lead to #include "SomeClass.h"
#define SOME_CLASS
... boat load of code here...
#endif // SOME_CLASS
```
|
6,123,544 |
In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
```
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
```
2.
```
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
```
Which is more preferable and why?
|
2011/05/25
|
['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']
|
The best option is to use `#pragma once`. With `#define` you must be very careful when using multiple libraries as the guard name may not be unique.
|
I prefer the first option. Suppose you include more files, and these files in turn include the file containing `#ifndef SOME_CLASS`.
I think it's fairly easy to spot include errors, if the `#define SOME_CLASS` isn't adjacent to `#ifndef SOME_CLASS`.
```
// SomeClass.h
#ifndef SOME_CLASS
#include "OtherFile.h" // will eventually lead to #include "SomeClass.h"
#define SOME_CLASS
... boat load of code here...
#endif // SOME_CLASS
```
|
6,123,544 |
In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
```
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
```
2.
```
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
```
Which is more preferable and why?
|
2011/05/25
|
['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']
|
The first option is commonly optimized by compilers to behave like the non-standard `#pragma once`.
It is also safer in case of recursive includes. If, in the `//code...` part, you include another header which includes .... which includes the header you're currently editing, then the second version won't work.
|
The best option is to use `#pragma once`. With `#define` you must be very careful when using multiple libraries as the guard name may not be unique.
|
6,123,544 |
In header files I've seen two main ways for defining macro to avoid including the file more than once.
1.
```
#ifndef SOME_CLASS
#define SOME_CLASS
//code ...
#endif
```
2.
```
#ifndef SOME_CLASS
//code...
#define SOME_CLASS
#endif
```
Which is more preferable and why?
|
2011/05/25
|
['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']
|
The first option is commonly optimized by compilers to behave like the non-standard `#pragma once`.
It is also safer in case of recursive includes. If, in the `//code...` part, you include another header which includes .... which includes the header you're currently editing, then the second version won't work.
|
I prefer the first option. Suppose you include more files, and these files in turn include the file containing `#ifndef SOME_CLASS`.
I think it's fairly easy to spot include errors, if the `#define SOME_CLASS` isn't adjacent to `#ifndef SOME_CLASS`.
```
// SomeClass.h
#ifndef SOME_CLASS
#include "OtherFile.h" // will eventually lead to #include "SomeClass.h"
#define SOME_CLASS
... boat load of code here...
#endif // SOME_CLASS
```
|
255,287 |
>
> If $n\_p=1$, then the $p$-Sylow subgroup is normal.
>
>
>
I've used this fact several times, and it's about time I knew why it's true.
|
2012/12/10
|
['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']
|
Let $N$ be a p-sylow subgroup.
For all $x$ ,$xNx^{-1}$ is a conjugate of $N$. If the set of groups conjugate to $N$ has size $1$ we find that $xNx^{-1}=N$ for all $x$.
|
Well, $n\_p$ is the number of $p$-Sylow subgroups. The conjugates of $p$-Sylow subgroup are precisely the other $p$-Sylow sugroups. So if $n\_p=1$ then the $p$-Sylow subgroup is conjugate only to itself, i.e. it is normal.
|
255,287 |
>
> If $n\_p=1$, then the $p$-Sylow subgroup is normal.
>
>
>
I've used this fact several times, and it's about time I knew why it's true.
|
2012/12/10
|
['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']
|
Let $N$ be a p-sylow subgroup.
For all $x$ ,$xNx^{-1}$ is a conjugate of $N$. If the set of groups conjugate to $N$ has size $1$ we find that $xNx^{-1}=N$ for all $x$.
|
Let $N$ be the single Sylow $p$-group. Suppose it is not normal. Then conjugation by some element $g$ gives a group $gNg^{-1}$ different from $N$ with the same number of elements as $N$. This is another Sylow $p$-group, distinct from the first, a contradiction.
|
255,287 |
>
> If $n\_p=1$, then the $p$-Sylow subgroup is normal.
>
>
>
I've used this fact several times, and it's about time I knew why it's true.
|
2012/12/10
|
['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']
|
Let $N$ be a p-sylow subgroup.
For all $x$ ,$xNx^{-1}$ is a conjugate of $N$. If the set of groups conjugate to $N$ has size $1$ we find that $xNx^{-1}=N$ for all $x$.
|
I don't want to add something different here, but good to know that $n\_p=[G:N\_G(P)]$ when $P$ is a $p$- sylow of $G$. So if $n\_p=1$ then $N\_G(P)=G$ so $P$ is normal in $G$.
|
255,287 |
>
> If $n\_p=1$, then the $p$-Sylow subgroup is normal.
>
>
>
I've used this fact several times, and it's about time I knew why it's true.
|
2012/12/10
|
['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']
|
Let $N$ be a p-sylow subgroup.
For all $x$ ,$xNx^{-1}$ is a conjugate of $N$. If the set of groups conjugate to $N$ has size $1$ we find that $xNx^{-1}=N$ for all $x$.
|
If I may add something.
The following statement is true:
Let $U\leq G$ be a subgroup such that there is no other subgroup that has the same order. Then $U$ is a characteristic subgroup. That is, *every automorphism* of $G$ maps $U$ to itself.
|
255,287 |
>
> If $n\_p=1$, then the $p$-Sylow subgroup is normal.
>
>
>
I've used this fact several times, and it's about time I knew why it's true.
|
2012/12/10
|
['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']
|
I don't want to add something different here, but good to know that $n\_p=[G:N\_G(P)]$ when $P$ is a $p$- sylow of $G$. So if $n\_p=1$ then $N\_G(P)=G$ so $P$ is normal in $G$.
|
Well, $n\_p$ is the number of $p$-Sylow subgroups. The conjugates of $p$-Sylow subgroup are precisely the other $p$-Sylow sugroups. So if $n\_p=1$ then the $p$-Sylow subgroup is conjugate only to itself, i.e. it is normal.
|
255,287 |
>
> If $n\_p=1$, then the $p$-Sylow subgroup is normal.
>
>
>
I've used this fact several times, and it's about time I knew why it's true.
|
2012/12/10
|
['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']
|
I don't want to add something different here, but good to know that $n\_p=[G:N\_G(P)]$ when $P$ is a $p$- sylow of $G$. So if $n\_p=1$ then $N\_G(P)=G$ so $P$ is normal in $G$.
|
Let $N$ be the single Sylow $p$-group. Suppose it is not normal. Then conjugation by some element $g$ gives a group $gNg^{-1}$ different from $N$ with the same number of elements as $N$. This is another Sylow $p$-group, distinct from the first, a contradiction.
|
255,287 |
>
> If $n\_p=1$, then the $p$-Sylow subgroup is normal.
>
>
>
I've used this fact several times, and it's about time I knew why it's true.
|
2012/12/10
|
['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']
|
I don't want to add something different here, but good to know that $n\_p=[G:N\_G(P)]$ when $P$ is a $p$- sylow of $G$. So if $n\_p=1$ then $N\_G(P)=G$ so $P$ is normal in $G$.
|
If I may add something.
The following statement is true:
Let $U\leq G$ be a subgroup such that there is no other subgroup that has the same order. Then $U$ is a characteristic subgroup. That is, *every automorphism* of $G$ maps $U$ to itself.
|
70,968,102 |
What I want is to define an array of Strings in Ada.
I'm trying to execute this code:
```
type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
And the compiler says:
```
warning:wrong length for array of subtype of "String" defined at line 42
```
My line 42 is this:
```
type lexicon is array(1..7) of String(1..20);
```
But compailer says the warning is in line 43 and 44: what are these:
```
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
Can somebody help me with that?
|
2022/02/03
|
['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']
|
You declared your array to hold Strings of length 20. The String literals you give are less than 20 Characters long. Hence the error.
You seem to be looking for a string type that contains a *maximum* of 20 characters. This is provided in `Ada.Strings.Bounded`:
```vhdl
package Max_20_String is new Ada.Strings.Bounded.Generic_Bounded_Length (20);
use Max_20_String;
type Lexicon is array (1..7) of Bounded_String; -- from Max_20_String
nomFumadors : Lexicon := (To_Bounded_String ("Macia"),
To_Bounded_String ("Xisco"),
To_Bounded_String ("Toni"),
To_Bounded_String ("Laura"),
To_Bounded_String ("Rocky"),
To_Bounded_String ("Paz"));
```
To get back a String from a Bounded\_String, use e.g. `To_String (Lexicon (2))`.
|
Another solution is to use String, truncate long strings, and pad short strings:
```
Max : constant := 20;
subtype S20 is String (1 .. Max);
type Lexicon is array (1 .. 7) of S20;
function To20 (S : in String) return S20 is
(if S'Length >= Max then S (S'First .. S'First + Max - 1)
else S & (S'Length + 1 .. Max => ' ') );
V : Lexicon := (To20 (""), To20 ("Hello"), To20 ("1234567890123456789012345"), ...
```
|
70,968,102 |
What I want is to define an array of Strings in Ada.
I'm trying to execute this code:
```
type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
And the compiler says:
```
warning:wrong length for array of subtype of "String" defined at line 42
```
My line 42 is this:
```
type lexicon is array(1..7) of String(1..20);
```
But compailer says the warning is in line 43 and 44: what are these:
```
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
Can somebody help me with that?
|
2022/02/03
|
['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']
|
Another solution is to use String, truncate long strings, and pad short strings:
```
Max : constant := 20;
subtype S20 is String (1 .. Max);
type Lexicon is array (1 .. 7) of S20;
function To20 (S : in String) return S20 is
(if S'Length >= Max then S (S'First .. S'First + Max - 1)
else S & (S'Length + 1 .. Max => ' ') );
V : Lexicon := (To20 (""), To20 ("Hello"), To20 ("1234567890123456789012345"), ...
```
|
Building upon the solution by Mark, but simplifying thanks to the operations from [`Ada.Strings.Fixed`](https://en.wikibooks.org/wiki/Ada_Programming/Libraries/Ada.Strings.Fixed).
```ada
with Ada.Strings.Fixed;
with Ada.Text_IO;
procedure Main is
subtype Lexicon_Data is String (1 .. 20);
type Lexicon is array (1 .. 7) of Lexicon_Data;
function To_Lexicon_Data
(Value : in String)
return Lexicon_Data
is
begin
return Ada.Strings.Fixed.Head (Value, Lexicon_Data'Length);
end To_Lexicon_Data;
nomFumadors : constant Lexicon :=
(To_Lexicon_Data ("Macia"),
To_Lexicon_Data ("Xisco"),
To_Lexicon_Data ("Toni"),
To_Lexicon_Data ("Laura"),
To_Lexicon_Data ("Rocky"),
To_Lexicon_Data ("Paz"),
To_Lexicon_Data ("Mark"));
begin
for Item of nomFumadors loop
Ada.Text_IO.Put_Line (Ada.Strings.Fixed.Trim (Item, Ada.Strings.Both));
end loop;
end Main;
```
|
70,968,102 |
What I want is to define an array of Strings in Ada.
I'm trying to execute this code:
```
type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
And the compiler says:
```
warning:wrong length for array of subtype of "String" defined at line 42
```
My line 42 is this:
```
type lexicon is array(1..7) of String(1..20);
```
But compailer says the warning is in line 43 and 44: what are these:
```
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
Can somebody help me with that?
|
2022/02/03
|
['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']
|
Others have mentioned bounded and unbounded strings. You can also use Indefinite\_Vectors. You can use the "&" operator to initialize them (as opposed to the initializer list though the next version of Ada is adding initializer lists to containers). You can use a vector just like an array by passing indexes in plus you get a lot of other additional functionality.
```ada
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Indefinite_Vectors;
procedure Hello is
package Vectors is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive,
Element_Type => String);
use type Vectors.Vector;
nomFumadors : Vectors.Vector
:= Vectors.Empty_Vector
& "Macia"
& "Xisco"
& "Toni"
& "Laura"
& "Rocky"
& "Paz";
nomNoFumadors : Vectors.Vector
:= Vectors.Empty_Vector
& "Marina"
& "Marta"
& "Joan"
& "Africa"
& "America";
begin
Put_Line("Hello, world!");
-- Loop through Elements
for Name of nomFumadors loop
Put_Line(Name);
end loop;
-- Loop by index
for Index in nomNoFumadors.Iterate loop
Put_Line(nomNoFumadors(Index));
end loop;
end Hello;
```
|
Another solution is to use String, truncate long strings, and pad short strings:
```
Max : constant := 20;
subtype S20 is String (1 .. Max);
type Lexicon is array (1 .. 7) of S20;
function To20 (S : in String) return S20 is
(if S'Length >= Max then S (S'First .. S'First + Max - 1)
else S & (S'Length + 1 .. Max => ' ') );
V : Lexicon := (To20 (""), To20 ("Hello"), To20 ("1234567890123456789012345"), ...
```
|
70,968,102 |
What I want is to define an array of Strings in Ada.
I'm trying to execute this code:
```
type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
And the compiler says:
```
warning:wrong length for array of subtype of "String" defined at line 42
```
My line 42 is this:
```
type lexicon is array(1..7) of String(1..20);
```
But compailer says the warning is in line 43 and 44: what are these:
```
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
Can somebody help me with that?
|
2022/02/03
|
['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']
|
You declared your array to hold Strings of length 20. The String literals you give are less than 20 Characters long. Hence the error.
You seem to be looking for a string type that contains a *maximum* of 20 characters. This is provided in `Ada.Strings.Bounded`:
```vhdl
package Max_20_String is new Ada.Strings.Bounded.Generic_Bounded_Length (20);
use Max_20_String;
type Lexicon is array (1..7) of Bounded_String; -- from Max_20_String
nomFumadors : Lexicon := (To_Bounded_String ("Macia"),
To_Bounded_String ("Xisco"),
To_Bounded_String ("Toni"),
To_Bounded_String ("Laura"),
To_Bounded_String ("Rocky"),
To_Bounded_String ("Paz"));
```
To get back a String from a Bounded\_String, use e.g. `To_String (Lexicon (2))`.
|
Similar to Jeff Carter's answer, but using a function to coerce any string into a fixed string ...
```
procedure Main is
subtype Lexicon_Data is String (1 .. 20);
type Lexicon is array (1 .. 7) of Lexicon_Data;
function To_Lexicon_Data
(Value : in String)
return Lexicon_Data
is
Result : Lexicon_Data;
begin
if Value'Length < 1 then
-- Empty string returns a bunch of spaces
Result := (others => ' ');
else
declare
Offset : constant Natural :=
Value'First - Lexicon_Data'First;
begin
if Value'Length > Lexicon_Data'Length then
-- Length exceeds range, so truncate
Result (Lexicon_Data'Range) := Lexicon_Data
(Value (Offset + 1 .. Offset + Lexicon_Data'Length));
else
-- Copy into result, and pad right with spaces
Result := (others => ' ');
Result (Lexicon_Data'First .. Value'Length) :=
(Value (Offset + 1 .. Offset + Value'Length));
end if;
end;
end if;
return Result;
end To_Lexicon_Data;
nomFumadors : constant Lexicon :=
(To_Lexicon_Data ("Macia"),
To_Lexicon_Data ("Xisco"),
To_Lexicon_Data ("Toni"),
To_Lexicon_Data ("Laura"),
To_Lexicon_Data ("Rocky"),
To_Lexicon_Data ("Paz"),
To_Lexicon_Data ("Mark"));
begin
-- Insert code here.
null;
end Main;
```
If you wanted to prove AoRTE (ie SparkAda) then the declaration for Result in the function becomes
```
Result : Lexicon_Data
with Relaxed_Initialization;
```
.. and the function To\_Lexicon\_Data is proved as being runtime error free.
Note the extra item for Lexicon, Mark, since you need seven items for the Lexicon declaration to be valid.
|
70,968,102 |
What I want is to define an array of Strings in Ada.
I'm trying to execute this code:
```
type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
And the compiler says:
```
warning:wrong length for array of subtype of "String" defined at line 42
```
My line 42 is this:
```
type lexicon is array(1..7) of String(1..20);
```
But compailer says the warning is in line 43 and 44: what are these:
```
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
Can somebody help me with that?
|
2022/02/03
|
['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']
|
Others have mentioned bounded and unbounded strings. You can also use Indefinite\_Vectors. You can use the "&" operator to initialize them (as opposed to the initializer list though the next version of Ada is adding initializer lists to containers). You can use a vector just like an array by passing indexes in plus you get a lot of other additional functionality.
```ada
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Indefinite_Vectors;
procedure Hello is
package Vectors is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive,
Element_Type => String);
use type Vectors.Vector;
nomFumadors : Vectors.Vector
:= Vectors.Empty_Vector
& "Macia"
& "Xisco"
& "Toni"
& "Laura"
& "Rocky"
& "Paz";
nomNoFumadors : Vectors.Vector
:= Vectors.Empty_Vector
& "Marina"
& "Marta"
& "Joan"
& "Africa"
& "America";
begin
Put_Line("Hello, world!");
-- Loop through Elements
for Name of nomFumadors loop
Put_Line(Name);
end loop;
-- Loop by index
for Index in nomNoFumadors.Iterate loop
Put_Line(nomNoFumadors(Index));
end loop;
end Hello;
```
|
Building upon the solution by Mark, but simplifying thanks to the operations from [`Ada.Strings.Fixed`](https://en.wikibooks.org/wiki/Ada_Programming/Libraries/Ada.Strings.Fixed).
```ada
with Ada.Strings.Fixed;
with Ada.Text_IO;
procedure Main is
subtype Lexicon_Data is String (1 .. 20);
type Lexicon is array (1 .. 7) of Lexicon_Data;
function To_Lexicon_Data
(Value : in String)
return Lexicon_Data
is
begin
return Ada.Strings.Fixed.Head (Value, Lexicon_Data'Length);
end To_Lexicon_Data;
nomFumadors : constant Lexicon :=
(To_Lexicon_Data ("Macia"),
To_Lexicon_Data ("Xisco"),
To_Lexicon_Data ("Toni"),
To_Lexicon_Data ("Laura"),
To_Lexicon_Data ("Rocky"),
To_Lexicon_Data ("Paz"),
To_Lexicon_Data ("Mark"));
begin
for Item of nomFumadors loop
Ada.Text_IO.Put_Line (Ada.Strings.Fixed.Trim (Item, Ada.Strings.Both));
end loop;
end Main;
```
|
70,968,102 |
What I want is to define an array of Strings in Ada.
I'm trying to execute this code:
```
type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
And the compiler says:
```
warning:wrong length for array of subtype of "String" defined at line 42
```
My line 42 is this:
```
type lexicon is array(1..7) of String(1..20);
```
But compailer says the warning is in line 43 and 44: what are these:
```
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
Can somebody help me with that?
|
2022/02/03
|
['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']
|
Others have mentioned bounded and unbounded strings. You can also use Indefinite\_Vectors. You can use the "&" operator to initialize them (as opposed to the initializer list though the next version of Ada is adding initializer lists to containers). You can use a vector just like an array by passing indexes in plus you get a lot of other additional functionality.
```ada
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Indefinite_Vectors;
procedure Hello is
package Vectors is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive,
Element_Type => String);
use type Vectors.Vector;
nomFumadors : Vectors.Vector
:= Vectors.Empty_Vector
& "Macia"
& "Xisco"
& "Toni"
& "Laura"
& "Rocky"
& "Paz";
nomNoFumadors : Vectors.Vector
:= Vectors.Empty_Vector
& "Marina"
& "Marta"
& "Joan"
& "Africa"
& "America";
begin
Put_Line("Hello, world!");
-- Loop through Elements
for Name of nomFumadors loop
Put_Line(Name);
end loop;
-- Loop by index
for Index in nomNoFumadors.Iterate loop
Put_Line(nomNoFumadors(Index));
end loop;
end Hello;
```
|
Similar to Jeff Carter's answer, but using a function to coerce any string into a fixed string ...
```
procedure Main is
subtype Lexicon_Data is String (1 .. 20);
type Lexicon is array (1 .. 7) of Lexicon_Data;
function To_Lexicon_Data
(Value : in String)
return Lexicon_Data
is
Result : Lexicon_Data;
begin
if Value'Length < 1 then
-- Empty string returns a bunch of spaces
Result := (others => ' ');
else
declare
Offset : constant Natural :=
Value'First - Lexicon_Data'First;
begin
if Value'Length > Lexicon_Data'Length then
-- Length exceeds range, so truncate
Result (Lexicon_Data'Range) := Lexicon_Data
(Value (Offset + 1 .. Offset + Lexicon_Data'Length));
else
-- Copy into result, and pad right with spaces
Result := (others => ' ');
Result (Lexicon_Data'First .. Value'Length) :=
(Value (Offset + 1 .. Offset + Value'Length));
end if;
end;
end if;
return Result;
end To_Lexicon_Data;
nomFumadors : constant Lexicon :=
(To_Lexicon_Data ("Macia"),
To_Lexicon_Data ("Xisco"),
To_Lexicon_Data ("Toni"),
To_Lexicon_Data ("Laura"),
To_Lexicon_Data ("Rocky"),
To_Lexicon_Data ("Paz"),
To_Lexicon_Data ("Mark"));
begin
-- Insert code here.
null;
end Main;
```
If you wanted to prove AoRTE (ie SparkAda) then the declaration for Result in the function becomes
```
Result : Lexicon_Data
with Relaxed_Initialization;
```
.. and the function To\_Lexicon\_Data is proved as being runtime error free.
Note the extra item for Lexicon, Mark, since you need seven items for the Lexicon declaration to be valid.
|
70,968,102 |
What I want is to define an array of Strings in Ada.
I'm trying to execute this code:
```
type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
And the compiler says:
```
warning:wrong length for array of subtype of "String" defined at line 42
```
My line 42 is this:
```
type lexicon is array(1..7) of String(1..20);
```
But compailer says the warning is in line 43 and 44: what are these:
```
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
Can somebody help me with that?
|
2022/02/03
|
['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']
|
Another option is `Unbounded_String` (as its name suggests, length is variable and unlimited):
```
with Ada.Strings.Unbounded;
procedure Fumador is
use Ada.Strings.Unbounded;
subtype VString is Unbounded_String;
function "+" (Source : in String) return VString renames To_Unbounded_String;
type Lexicon is array (Integer range <>) of VString; -- Unknown number of people.
nomFumadors : Lexicon := (+"Macia", +"Xisco", +"Toni", +"Laura", +"Rocky", +"Paz");
nomNoFumadors : Lexicon := (+"Marina", +"Marta", +"Joan", +"Africa", +"America");
begin
null;
end;
```
|
Similar to Jeff Carter's answer, but using a function to coerce any string into a fixed string ...
```
procedure Main is
subtype Lexicon_Data is String (1 .. 20);
type Lexicon is array (1 .. 7) of Lexicon_Data;
function To_Lexicon_Data
(Value : in String)
return Lexicon_Data
is
Result : Lexicon_Data;
begin
if Value'Length < 1 then
-- Empty string returns a bunch of spaces
Result := (others => ' ');
else
declare
Offset : constant Natural :=
Value'First - Lexicon_Data'First;
begin
if Value'Length > Lexicon_Data'Length then
-- Length exceeds range, so truncate
Result (Lexicon_Data'Range) := Lexicon_Data
(Value (Offset + 1 .. Offset + Lexicon_Data'Length));
else
-- Copy into result, and pad right with spaces
Result := (others => ' ');
Result (Lexicon_Data'First .. Value'Length) :=
(Value (Offset + 1 .. Offset + Value'Length));
end if;
end;
end if;
return Result;
end To_Lexicon_Data;
nomFumadors : constant Lexicon :=
(To_Lexicon_Data ("Macia"),
To_Lexicon_Data ("Xisco"),
To_Lexicon_Data ("Toni"),
To_Lexicon_Data ("Laura"),
To_Lexicon_Data ("Rocky"),
To_Lexicon_Data ("Paz"),
To_Lexicon_Data ("Mark"));
begin
-- Insert code here.
null;
end Main;
```
If you wanted to prove AoRTE (ie SparkAda) then the declaration for Result in the function becomes
```
Result : Lexicon_Data
with Relaxed_Initialization;
```
.. and the function To\_Lexicon\_Data is proved as being runtime error free.
Note the extra item for Lexicon, Mark, since you need seven items for the Lexicon declaration to be valid.
|
70,968,102 |
What I want is to define an array of Strings in Ada.
I'm trying to execute this code:
```
type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
And the compiler says:
```
warning:wrong length for array of subtype of "String" defined at line 42
```
My line 42 is this:
```
type lexicon is array(1..7) of String(1..20);
```
But compailer says the warning is in line 43 and 44: what are these:
```
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
Can somebody help me with that?
|
2022/02/03
|
['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']
|
Another option is `Unbounded_String` (as its name suggests, length is variable and unlimited):
```
with Ada.Strings.Unbounded;
procedure Fumador is
use Ada.Strings.Unbounded;
subtype VString is Unbounded_String;
function "+" (Source : in String) return VString renames To_Unbounded_String;
type Lexicon is array (Integer range <>) of VString; -- Unknown number of people.
nomFumadors : Lexicon := (+"Macia", +"Xisco", +"Toni", +"Laura", +"Rocky", +"Paz");
nomNoFumadors : Lexicon := (+"Marina", +"Marta", +"Joan", +"Africa", +"America");
begin
null;
end;
```
|
Another solution is to use String, truncate long strings, and pad short strings:
```
Max : constant := 20;
subtype S20 is String (1 .. Max);
type Lexicon is array (1 .. 7) of S20;
function To20 (S : in String) return S20 is
(if S'Length >= Max then S (S'First .. S'First + Max - 1)
else S & (S'Length + 1 .. Max => ' ') );
V : Lexicon := (To20 (""), To20 ("Hello"), To20 ("1234567890123456789012345"), ...
```
|
70,968,102 |
What I want is to define an array of Strings in Ada.
I'm trying to execute this code:
```
type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
And the compiler says:
```
warning:wrong length for array of subtype of "String" defined at line 42
```
My line 42 is this:
```
type lexicon is array(1..7) of String(1..20);
```
But compailer says the warning is in line 43 and 44: what are these:
```
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
Can somebody help me with that?
|
2022/02/03
|
['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']
|
Another option is `Unbounded_String` (as its name suggests, length is variable and unlimited):
```
with Ada.Strings.Unbounded;
procedure Fumador is
use Ada.Strings.Unbounded;
subtype VString is Unbounded_String;
function "+" (Source : in String) return VString renames To_Unbounded_String;
type Lexicon is array (Integer range <>) of VString; -- Unknown number of people.
nomFumadors : Lexicon := (+"Macia", +"Xisco", +"Toni", +"Laura", +"Rocky", +"Paz");
nomNoFumadors : Lexicon := (+"Marina", +"Marta", +"Joan", +"Africa", +"America");
begin
null;
end;
```
|
Building upon the solution by Mark, but simplifying thanks to the operations from [`Ada.Strings.Fixed`](https://en.wikibooks.org/wiki/Ada_Programming/Libraries/Ada.Strings.Fixed).
```ada
with Ada.Strings.Fixed;
with Ada.Text_IO;
procedure Main is
subtype Lexicon_Data is String (1 .. 20);
type Lexicon is array (1 .. 7) of Lexicon_Data;
function To_Lexicon_Data
(Value : in String)
return Lexicon_Data
is
begin
return Ada.Strings.Fixed.Head (Value, Lexicon_Data'Length);
end To_Lexicon_Data;
nomFumadors : constant Lexicon :=
(To_Lexicon_Data ("Macia"),
To_Lexicon_Data ("Xisco"),
To_Lexicon_Data ("Toni"),
To_Lexicon_Data ("Laura"),
To_Lexicon_Data ("Rocky"),
To_Lexicon_Data ("Paz"),
To_Lexicon_Data ("Mark"));
begin
for Item of nomFumadors loop
Ada.Text_IO.Put_Line (Ada.Strings.Fixed.Trim (Item, Ada.Strings.Both));
end loop;
end Main;
```
|
70,968,102 |
What I want is to define an array of Strings in Ada.
I'm trying to execute this code:
```
type String is array (Positive range <>) of Character;
type lexicon is array(1..7) of String(1..20);
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
And the compiler says:
```
warning:wrong length for array of subtype of "String" defined at line 42
```
My line 42 is this:
```
type lexicon is array(1..7) of String(1..20);
```
But compailer says the warning is in line 43 and 44: what are these:
```
nomFumadors : lexicon := ("Macia","Xisco","Toni","Laura","Rocky","Paz");
nomNoFumadors : lexicon := ("Marina","Marta","Joan","Africa","America");
```
Can somebody help me with that?
|
2022/02/03
|
['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']
|
You declared your array to hold Strings of length 20. The String literals you give are less than 20 Characters long. Hence the error.
You seem to be looking for a string type that contains a *maximum* of 20 characters. This is provided in `Ada.Strings.Bounded`:
```vhdl
package Max_20_String is new Ada.Strings.Bounded.Generic_Bounded_Length (20);
use Max_20_String;
type Lexicon is array (1..7) of Bounded_String; -- from Max_20_String
nomFumadors : Lexicon := (To_Bounded_String ("Macia"),
To_Bounded_String ("Xisco"),
To_Bounded_String ("Toni"),
To_Bounded_String ("Laura"),
To_Bounded_String ("Rocky"),
To_Bounded_String ("Paz"));
```
To get back a String from a Bounded\_String, use e.g. `To_String (Lexicon (2))`.
|
Building upon the solution by Mark, but simplifying thanks to the operations from [`Ada.Strings.Fixed`](https://en.wikibooks.org/wiki/Ada_Programming/Libraries/Ada.Strings.Fixed).
```ada
with Ada.Strings.Fixed;
with Ada.Text_IO;
procedure Main is
subtype Lexicon_Data is String (1 .. 20);
type Lexicon is array (1 .. 7) of Lexicon_Data;
function To_Lexicon_Data
(Value : in String)
return Lexicon_Data
is
begin
return Ada.Strings.Fixed.Head (Value, Lexicon_Data'Length);
end To_Lexicon_Data;
nomFumadors : constant Lexicon :=
(To_Lexicon_Data ("Macia"),
To_Lexicon_Data ("Xisco"),
To_Lexicon_Data ("Toni"),
To_Lexicon_Data ("Laura"),
To_Lexicon_Data ("Rocky"),
To_Lexicon_Data ("Paz"),
To_Lexicon_Data ("Mark"));
begin
for Item of nomFumadors loop
Ada.Text_IO.Put_Line (Ada.Strings.Fixed.Trim (Item, Ada.Strings.Both));
end loop;
end Main;
```
|
19,576,214 |
I have two click functions: one targets td.default and the second td.clicked. Both changes the class attribute to either 'clicked' or 'default' (and updates the text in the cell). The classes are getting changed from the first click function but the second click function that looks for td.click doesn't find it's target.
```
$("td.default").click(function() {
$(this).attr('class','clicked');
$(this).text("monkey");
$("#ouput").append("td.default clicked<br/>"); //reporting message
});
$("td.clicked").click(function() {
$(this).attr('class','default');
$(this).text("empty");
$("#ouput").append("td.clicked clicked<br/>"); //reporting message
});
```
|
2013/10/24
|
['https://Stackoverflow.com/questions/19576214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2237565/']
|
Use delegation instead
```
$("table").on("click", "td.default", function() {
$(this).attr('class','clicked');
$(this).text("monkey");
$("#ouput").append("td.default clicked<br/>"); //reporting message
});
$("table").on("click", "td.clicked", function() {
$(this).attr('class','default');
$(this).text("empty");
$("#ouput").append("td.clicked clicked<br/>"); //reporting message
});
```
Delegation would handle the dynamic changes on the nodes v/s `.click()`, which would not rebind dynamically modified nodes. [Read more on delegation using `on` here](http://api.jquery.com/on/)
|
That seems like a lot of work, would it be easier to do it this way?
```
$('td.default,td.clicked').on('click', function() {
$(this).toggleClass('default').toggleClass('clicked').text(
$(this).text() === 'empty' ? 'monkey' : 'empty'
);
});
```
made a fiddle: <http://jsfiddle.net/filever10/PdjMX/>
|
19,576,214 |
I have two click functions: one targets td.default and the second td.clicked. Both changes the class attribute to either 'clicked' or 'default' (and updates the text in the cell). The classes are getting changed from the first click function but the second click function that looks for td.click doesn't find it's target.
```
$("td.default").click(function() {
$(this).attr('class','clicked');
$(this).text("monkey");
$("#ouput").append("td.default clicked<br/>"); //reporting message
});
$("td.clicked").click(function() {
$(this).attr('class','default');
$(this).text("empty");
$("#ouput").append("td.clicked clicked<br/>"); //reporting message
});
```
|
2013/10/24
|
['https://Stackoverflow.com/questions/19576214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2237565/']
|
When you bind a click handler, you are binding to the element. Changing the class of the element doesn't change that handler that you've bound to it. If you want that behavior, you'll need to use `on()` with event delegation. See [`on()`](http://api.jquery.com/on/), especially the section about "direct and delegated events".
[**Demo Click Here**](http://jsfiddle.net/hEQMe/) :
```
$(document).on('click', "td.default", function() {
$(this).attr('class','clicked');
$(this).text("monkey");
$("#ouput").append("td.default clicked<br/>"); //reporting message
});
$(document).on('click', "td.clicked", function() {
$(this).attr('class','default');
$(this).text("empty");
$("#ouput").append("td.clicked clicked<br/>"); //reporting message
});
```
|
That seems like a lot of work, would it be easier to do it this way?
```
$('td.default,td.clicked').on('click', function() {
$(this).toggleClass('default').toggleClass('clicked').text(
$(this).text() === 'empty' ? 'monkey' : 'empty'
);
});
```
made a fiddle: <http://jsfiddle.net/filever10/PdjMX/>
|
296,482 |
I just landed at LAX and the flight attendant (who had a slight Latino accent, but was a native or near-native English speaker) gave the last announcement:
>
> "As we prepare to land please have cups and other items ready to throw away, as we're going to make one last pass through the cabin *at which time*." Full stop.
>
>
>
There were several such utterances during the flight which ended with "at which time," each of which was clearly meant to signify "at this time." Is this a common usage in a variety of English I'm unfamiliar with, or is it more likely to be this one speaker's quirk?
|
2015/12/28
|
['https://english.stackexchange.com/questions/296482', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/-1/']
|
In this context, the word "suppose" means "believe"; see [Merriam-Webster](http://www.merriam-webster.com/dictionary/suppose):
>
> b (1) : to hold as an opinion : believe [they *supposed* they were early]
>
>
> (2) : to think probable or in keeping with the facts [seems reasonable to *suppose* that he would profit]
>
>
>
So the key phrase:
>
> "...the proudest of men, the philosopher, supposes that he sees on all sides the eyes of the universe telescopically focused upon his action and thought."
>
>
>
...may be treated as:
>
> "...the philosopher supposes (believes) that he sees (on all sides) the eyes of the universe."
>
>
>
Note that the philosopher *is* the "proudest of men" in this sentence; they are the same person.
So, yes, the "proudest of men" believes that the whole universe is fixated on him.
|
You are pretty correct in your assumption of what this sentence means. The author is comparing the proud to porters, saying that everyone wants an admirer. Nietzsche goes a step further to say outright that philosophers are the proudest men, and that they want the universe to admire them.
Onward, to definitions. To *suppose* something is to assume it as truth. Nietzsche here is saying that philosophers (the proudest men) already assume the universe admires them.
As for "all sides", the philosopher sees all sides around him looking on. Going back to that pride (a pretty common motif for Nietzsche), the philosopher sees himself at the center, and all sides around that center are focused on him.
|
296,482 |
I just landed at LAX and the flight attendant (who had a slight Latino accent, but was a native or near-native English speaker) gave the last announcement:
>
> "As we prepare to land please have cups and other items ready to throw away, as we're going to make one last pass through the cabin *at which time*." Full stop.
>
>
>
There were several such utterances during the flight which ended with "at which time," each of which was clearly meant to signify "at this time." Is this a common usage in a variety of English I'm unfamiliar with, or is it more likely to be this one speaker's quirk?
|
2015/12/28
|
['https://english.stackexchange.com/questions/296482', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/-1/']
|
>
> "And just as every porter wants to have an admirer, so even the proudest of men, the philosopher, supposes that he sees on all sides the eyes of the universe telescopically focused upon his action and thought."
>
>
>
I may be wrong, but Nietzsche seems to be saying that just as the supposedly humblest of men (viz., the porter, or [a person employed to carry burdens, especially an attendant who carries travelers' baggage at a hotel or transportation station](http://www.thefreedictionary.com/porter)) wants to be seen and admired, so too does the proudest man want to be seen and admired.
The difference between the desire of the humble man and the desire of the proud man is a matter of degree. While the humble man is satisfied in knowing at least one person sees him and admires him (for whatever reason, perhaps for the professional way in which he carries someone's baggage), the proud person, on the other hand, is satisfied only when many, many people see him and admire him.
Moreover, he doesn't need just an admiring glance, but he needs continually the admiring and focused attention of all kinds of people, whether his peers, whether those whom he considers to be his "inferiors," or whether anyone, really.
For the humble man, his desire is really a search for dignity. For the proud man, his desire is not for dignity, which he has in truckloads, but for the feeling of superiority.
Whether Nietzsche's "take" on philosophers is accurate or not, all people, regardless of their station in life want to be noticed and admired for something. In other words, we all long for significance. That longing takes an ugly turn, however, when it morphs into a superiority complex, complete with delusions of grandeur!
In Christian circles, the saying goes, "The ground is level at the cross." I like that, and I think it speaks volumes to the blatently narcissistic age in which we live.
|
You are pretty correct in your assumption of what this sentence means. The author is comparing the proud to porters, saying that everyone wants an admirer. Nietzsche goes a step further to say outright that philosophers are the proudest men, and that they want the universe to admire them.
Onward, to definitions. To *suppose* something is to assume it as truth. Nietzsche here is saying that philosophers (the proudest men) already assume the universe admires them.
As for "all sides", the philosopher sees all sides around him looking on. Going back to that pride (a pretty common motif for Nietzsche), the philosopher sees himself at the center, and all sides around that center are focused on him.
|
296,482 |
I just landed at LAX and the flight attendant (who had a slight Latino accent, but was a native or near-native English speaker) gave the last announcement:
>
> "As we prepare to land please have cups and other items ready to throw away, as we're going to make one last pass through the cabin *at which time*." Full stop.
>
>
>
There were several such utterances during the flight which ended with "at which time," each of which was clearly meant to signify "at this time." Is this a common usage in a variety of English I'm unfamiliar with, or is it more likely to be this one speaker's quirk?
|
2015/12/28
|
['https://english.stackexchange.com/questions/296482', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/-1/']
|
In this context, the word "suppose" means "believe"; see [Merriam-Webster](http://www.merriam-webster.com/dictionary/suppose):
>
> b (1) : to hold as an opinion : believe [they *supposed* they were early]
>
>
> (2) : to think probable or in keeping with the facts [seems reasonable to *suppose* that he would profit]
>
>
>
So the key phrase:
>
> "...the proudest of men, the philosopher, supposes that he sees on all sides the eyes of the universe telescopically focused upon his action and thought."
>
>
>
...may be treated as:
>
> "...the philosopher supposes (believes) that he sees (on all sides) the eyes of the universe."
>
>
>
Note that the philosopher *is* the "proudest of men" in this sentence; they are the same person.
So, yes, the "proudest of men" believes that the whole universe is fixated on him.
|
>
> "And just as every porter wants to have an admirer, so even the proudest of men, the philosopher, supposes that he sees on all sides the eyes of the universe telescopically focused upon his action and thought."
>
>
>
I may be wrong, but Nietzsche seems to be saying that just as the supposedly humblest of men (viz., the porter, or [a person employed to carry burdens, especially an attendant who carries travelers' baggage at a hotel or transportation station](http://www.thefreedictionary.com/porter)) wants to be seen and admired, so too does the proudest man want to be seen and admired.
The difference between the desire of the humble man and the desire of the proud man is a matter of degree. While the humble man is satisfied in knowing at least one person sees him and admires him (for whatever reason, perhaps for the professional way in which he carries someone's baggage), the proud person, on the other hand, is satisfied only when many, many people see him and admire him.
Moreover, he doesn't need just an admiring glance, but he needs continually the admiring and focused attention of all kinds of people, whether his peers, whether those whom he considers to be his "inferiors," or whether anyone, really.
For the humble man, his desire is really a search for dignity. For the proud man, his desire is not for dignity, which he has in truckloads, but for the feeling of superiority.
Whether Nietzsche's "take" on philosophers is accurate or not, all people, regardless of their station in life want to be noticed and admired for something. In other words, we all long for significance. That longing takes an ugly turn, however, when it morphs into a superiority complex, complete with delusions of grandeur!
In Christian circles, the saying goes, "The ground is level at the cross." I like that, and I think it speaks volumes to the blatently narcissistic age in which we live.
|
48,884,451 |
I am comparing two files in my script. using the command
```
comm -3 123.txt 321.txt"
```
These two files 123 and 321 has only numeric content.
Also I use
```
diff -ibw abc.txt cba.txt
```
These files abc and cba has alphanumeric content
If there is no mismatch no output is printed can you help me how to write a condition as below.
If there is no difference I need to print `files match`
If there is a difference I want to print `mismatch found` along with the mismatched output.
|
2018/02/20
|
['https://Stackoverflow.com/questions/48884451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9054895/']
|
```
- (void)collectionView:(UICollectionView *)collectionView
willDisplayCell:(UICollectionViewCell *)cell
forItemAtIndexPath:(NSIndexPath *)indexPath{
CGFloat collectionHeight = self.CollectionView.bounds.size.height;
CGFloat contentOffsetY = self.CollectionView.contentOffset.y;
CGFloat contentSizeHeight = self.CollectionView.contentSize.height;
CGFloat height = 0.0;
if(isCollectionViewScrollUp && contentOffsetY + self.CollectionView.frame.size.height < contentSizeHeight) {
int index = (int)indexPath.row + 1;
if (index % 3 == 1){
height = collectionHeight + 300;
}else if(index % 3 == 2){
height = collectionHeight + 300 * 2;
}else{
height = collectionHeight + 300 * 3;
}
cell.transform = CGAffineTransformMakeTranslation(0, height);
}else if(!isCollectionViewScrollUp && contentOffsetY > 0.0){
int index = (int)indexPath.row + 1;
if(index % 3 == 1){
height = collectionHeight + 300 * 3;
}else if(index % 3 == 2){
height = collectionHeight + 300 * 2;
}else{
height = collectionHeight + 300;
}
cell.transform = CGAffineTransformMakeTranslation(0, -height);
}
[UIView animateWithDuration:1 delay:0.03 usingSpringWithDamping:0.8 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
cell.transform = CGAffineTransformMakeTranslation(0, 0);
} completion:nil];
}
-(void) scrollViewDidScroll:(UIScrollView *)scrollView {
CGPoint scrollVelocity = [CollectionView.panGestureRecognizer velocityInView:CollectionView.superview];
if (scrollVelocity.y > 0.0) { //ScrollDown
isCollectionViewScrollUp = NO;
} else if (scrollVelocity.y < 0.0 ){ //ScrollUp
isCollectionViewScrollUp = YES;
}
}
```
|
Try This:
```
var isCollectionViewScrollUp: Bool = true
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let collectionHeight: CGFloat = self.collectionView!.bounds.size.height
let contentOffsetY: CGFloat = self.collectionView.contentOffset.y
let contentSizeHeight: CGFloat = self.collectionView.contentSize.height
var height:CGFloat = 0.0//collectionHeight * CGFloat(indexPath.row)
if isCollectionViewScrollUp && (contentOffsetY + self.collectionView.frame.size.height) < contentSizeHeight {
let index = Int(indexPath.row) + Int(1)
if index % 3 == 1 {
height = collectionHeight + 300
}
else if index % 3 == 2 {
height = collectionHeight + 300 * 2
}
else {
height = collectionHeight + 300 * 3
}
cell.transform = CGAffineTransform(translationX: 0, y: height)
} else if !isCollectionViewScrollUp && contentOffsetY > 0.0 {
let index = Int(indexPath.row) + Int(1)
if index % 3 == 1 {
height = collectionHeight + 300 * 3
}
else if index % 3 == 2 {
height = collectionHeight + 300 * 2
}
else {
height = collectionHeight + 300
}
cell.transform = CGAffineTransform(translationX: 0, y: -height)
}
UIView.animate(withDuration: 1, delay: 0.03, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
cell.transform = CGAffineTransform(translationX: 0, y: 0);
}, completion: nil)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let scrollVelocity:CGPoint = self.collectionView.panGestureRecognizer.velocity(in: self.collectionView?.superview)
if scrollVelocity.y > 0.0 { //ScrollDown
isCollectionViewScrollUp = false
} else if scrollVelocity.y < 0.0 { //ScrollUp
isCollectionViewScrollUp = true
}
}
```
|
1,103,899 |
One of my friends is a real Linux fan, so I decided to try Ubuntu on a VM. I mostly enjoyed the experience, but it was very slow, which I assume is the fault VirtualBox, as my laptop has 16 gigs of ram and an i7 6500u. Partly out of a desire to make sure it works for me, and partly out of thinking "this would be cool," I downloaded the Windows subsystem for Linux. It has official support from Microsoft, and it is specialized for just one OS, so I figured that it would be faster and closer to the performance I can expect were it my primary OS. However, it is only the terminal, not the full DE. Anyway, I had some fun with text-based programs like Lynx, but wanted more. With a few guides from the internet, I downloaded an X server to Windows, and got Ubuntu to use that. Now I can run Ubuntu apps mostly natively, interacting with other windows just like regular programs. However, this still is not how I would use Ubuntu; I want a desktop environment. I ran
`sudo apt install ubuntu-desktop` and then `startx`,
but that didn't work, throwing the error "Fatal server error:
xf86OpenConsole: Switching VT failed." Can anyone help?
P.S. I know I could run both OS's partitioned, but putting that aside, it would be very cool to run Linux apps inside Windows.
|
2018/12/22
|
['https://askubuntu.com/questions/1103899', 'https://askubuntu.com', 'https://askubuntu.com/users/906713/']
|
I would suggest that you install a lighter desktop than ubuntu in WSL. XFCE seems to work fine with WSL.
```
sudo apt update
sudo apt install xfce4
startxfce4
```
|
If you only want to try Ubuntu I suggest running Ubuntu from USB stick (Ubuntu Live)
* <https://unetbootin.github.io/> - You can try this tool to prepare USB stick.
There also other options:
* <https://tutorials.ubuntu.com/tutorial/tutorial-create-a-usb-stick-on-ubuntu#0>
* <https://tutorials.ubuntu.com/tutorial/tutorial-create-a-usb-stick-on-windows#0>
There You can try it without installing it on HDD. If You like it you can divide your drive into two partitions and on first install Windows, on second Linux and you can use both system on your computer.
|
37,833,775 |
I wanted to find how many times 1 number appears in provided another number. I've found a solution for finding 2-digit numbers in another number, but what I wanted to do is to find 1-digit, 2-digit, ..., n-digit numbers in provided number. I dont want to create another case in switch instruction, so my question how can I avoid doing switch to make it work. Code below:
```
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Provide number:");
int number1 = sc.nextInt();
System.out.println("Provide number you want to find in number1:");
int number2 = sc.nextInt();
int counter = 0;
int digit = 1;
int a = 10;
while(number2/a>0){
digit++;
a = a*10;
}
switch(digit){
case 1:{
while(number1 > 0 ){
if(number1 % 10 == number2){
counter++;
}
number1 = number1/10;
}
}
case 2:{
while(number1 > 0){
if(number1 % 100 == number2){
counter++;
}
number1 = number1/10;
}
}
}
System.out.println(counter);
}
```
Thanks for your help.
|
2016/06/15
|
['https://Stackoverflow.com/questions/37833775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6469057/']
|
You have declared `i` inside of the `for` loop:
```
for(int i=0;i<t;i++)
```
Therefore, `i`'s scope is limited to that `for` loop. `i` does not exist outside of that `for` loop.
So, when you try to reuse that `i` in the next `for` loop
```
for(i=0;i<t;i++)
```
you get an error. You have to declare `i` again:
```
for(int i=0;i<t;i++)
```
Same thing in your last `for` loop. It would also be very helpful if you indented your code correctly.
---
```
#include<iostream>
using namespace std;
int main()
{
int temp,t,a[10];
cin>>t;
for(int i=0;i<t;i++)
{
cin>>a[i];
}
for(int i=0;i<t;i++)
{
int j=i+1;
for( ;j<t;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int i=0;i<t;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
```
|
You only declare the variable i in the first for-loop. The declaration of the variable is only local for that loop, which means that the i will not exists outside the loop.
Instead of:
```
for(i=0;i<t;i++)
```
Try
```
for(int i=0;i<t;i++)
```
|
37,833,775 |
I wanted to find how many times 1 number appears in provided another number. I've found a solution for finding 2-digit numbers in another number, but what I wanted to do is to find 1-digit, 2-digit, ..., n-digit numbers in provided number. I dont want to create another case in switch instruction, so my question how can I avoid doing switch to make it work. Code below:
```
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Provide number:");
int number1 = sc.nextInt();
System.out.println("Provide number you want to find in number1:");
int number2 = sc.nextInt();
int counter = 0;
int digit = 1;
int a = 10;
while(number2/a>0){
digit++;
a = a*10;
}
switch(digit){
case 1:{
while(number1 > 0 ){
if(number1 % 10 == number2){
counter++;
}
number1 = number1/10;
}
}
case 2:{
while(number1 > 0){
if(number1 % 100 == number2){
counter++;
}
number1 = number1/10;
}
}
}
System.out.println(counter);
}
```
Thanks for your help.
|
2016/06/15
|
['https://Stackoverflow.com/questions/37833775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6469057/']
|
You have declared `i` inside of the `for` loop:
```
for(int i=0;i<t;i++)
```
Therefore, `i`'s scope is limited to that `for` loop. `i` does not exist outside of that `for` loop.
So, when you try to reuse that `i` in the next `for` loop
```
for(i=0;i<t;i++)
```
you get an error. You have to declare `i` again:
```
for(int i=0;i<t;i++)
```
Same thing in your last `for` loop. It would also be very helpful if you indented your code correctly.
---
```
#include<iostream>
using namespace std;
int main()
{
int temp,t,a[10];
cin>>t;
for(int i=0;i<t;i++)
{
cin>>a[i];
}
for(int i=0;i<t;i++)
{
int j=i+1;
for( ;j<t;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int i=0;i<t;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
```
|
The problem is with your 'i' variables.
Nowadays variables declared in a 'for' statement are only useable in the 'for' block, not outside the 'for' block.
|
37,833,775 |
I wanted to find how many times 1 number appears in provided another number. I've found a solution for finding 2-digit numbers in another number, but what I wanted to do is to find 1-digit, 2-digit, ..., n-digit numbers in provided number. I dont want to create another case in switch instruction, so my question how can I avoid doing switch to make it work. Code below:
```
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Provide number:");
int number1 = sc.nextInt();
System.out.println("Provide number you want to find in number1:");
int number2 = sc.nextInt();
int counter = 0;
int digit = 1;
int a = 10;
while(number2/a>0){
digit++;
a = a*10;
}
switch(digit){
case 1:{
while(number1 > 0 ){
if(number1 % 10 == number2){
counter++;
}
number1 = number1/10;
}
}
case 2:{
while(number1 > 0){
if(number1 % 100 == number2){
counter++;
}
number1 = number1/10;
}
}
}
System.out.println(counter);
}
```
Thanks for your help.
|
2016/06/15
|
['https://Stackoverflow.com/questions/37833775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6469057/']
|
You have declared `i` inside of the `for` loop:
```
for(int i=0;i<t;i++)
```
Therefore, `i`'s scope is limited to that `for` loop. `i` does not exist outside of that `for` loop.
So, when you try to reuse that `i` in the next `for` loop
```
for(i=0;i<t;i++)
```
you get an error. You have to declare `i` again:
```
for(int i=0;i<t;i++)
```
Same thing in your last `for` loop. It would also be very helpful if you indented your code correctly.
---
```
#include<iostream>
using namespace std;
int main()
{
int temp,t,a[10];
cin>>t;
for(int i=0;i<t;i++)
{
cin>>a[i];
}
for(int i=0;i<t;i++)
{
int j=i+1;
for( ;j<t;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int i=0;i<t;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
```
|
You have forgot to declare all your variables in the begining. So this way the variables are declared as a local integer and cannot be used outside the `for loop`. I tried declaring them outside the function `int main()` and it worked
The right code:
```
#include<iostream>
using namespace std;
int i = 0;
int a[10];
int temp = a[i];
int t;
int main()
{
cin>>t;
for(int i=0;i<t;i++)
{
cin>>a[i];
}
for(i=0;i<t;i++)
{
int j=i+1;
for( ;j<t;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(i=0;i<t;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
```
|
37,833,775 |
I wanted to find how many times 1 number appears in provided another number. I've found a solution for finding 2-digit numbers in another number, but what I wanted to do is to find 1-digit, 2-digit, ..., n-digit numbers in provided number. I dont want to create another case in switch instruction, so my question how can I avoid doing switch to make it work. Code below:
```
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Provide number:");
int number1 = sc.nextInt();
System.out.println("Provide number you want to find in number1:");
int number2 = sc.nextInt();
int counter = 0;
int digit = 1;
int a = 10;
while(number2/a>0){
digit++;
a = a*10;
}
switch(digit){
case 1:{
while(number1 > 0 ){
if(number1 % 10 == number2){
counter++;
}
number1 = number1/10;
}
}
case 2:{
while(number1 > 0){
if(number1 % 100 == number2){
counter++;
}
number1 = number1/10;
}
}
}
System.out.println(counter);
}
```
Thanks for your help.
|
2016/06/15
|
['https://Stackoverflow.com/questions/37833775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6469057/']
|
You have declared `i` inside of the `for` loop:
```
for(int i=0;i<t;i++)
```
Therefore, `i`'s scope is limited to that `for` loop. `i` does not exist outside of that `for` loop.
So, when you try to reuse that `i` in the next `for` loop
```
for(i=0;i<t;i++)
```
you get an error. You have to declare `i` again:
```
for(int i=0;i<t;i++)
```
Same thing in your last `for` loop. It would also be very helpful if you indented your code correctly.
---
```
#include<iostream>
using namespace std;
int main()
{
int temp,t,a[10];
cin>>t;
for(int i=0;i<t;i++)
{
cin>>a[i];
}
for(int i=0;i<t;i++)
{
int j=i+1;
for( ;j<t;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int i=0;i<t;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
```
|
Your problem is that you are declaring `i` inside the function scope.
You can decide if you want to declare the variable i once at the main, or each time as a local scope variable inside a the `for` scope.
```
#include<iostream>
using namespace std;
int main()
{
int temp, t, a[10];
cin >> t;
int i;
for(i=0; i<t ; i++)
{
cin >> a[i];
}
for(i=0; i<t; i++)
{
for(int j=i+1; j<t; j++)
{
if (a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(i=0; i<t; i++)
{
cout << a[i] << endl;
}
return 0;
}
```
|
26,717,000 |
Below JavaScript function is called after selecting option from `<select>` tag.
```
function function1()
{
var country=document.getElementById('id1').value;
switch(country)
{
case "India":
logo="rupee.png";
break;
case "US":
logo="dollar-logo.png";
break;
case "Britan":
logo="yen.png";
break;
}
```
Now i want to display flag of country according to selection has made..
Below is HTML file where i want to display image..
```
<td><img src="+logo+" width=30 height=30></td>
```
I also tried this one..
```
<td><img src="<%Eval(logo)%>" width=30 height=30></td>
```
|
2014/11/03
|
['https://Stackoverflow.com/questions/26717000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4147229/']
|
This is standard behavior in the Groovy shell, not peculiar to the Grails shell. You probably don't want to `def` the variable. See the following:
```
~ $ groovysh
Groovy Shell (2.3.4, JVM: 1.7.0_45)
Type ':help' or ':h' for help.
-------------------------------------------------------------------------------
groovy:000> def x = 42
===> 42
groovy:000> x
Unknown property: x
groovy:000> y = 2112
===> 2112
groovy:000> y
===> 2112
groovy:000>
```
From <http://beta.groovy-lang.org/groovysh.html>
>
> **1.3.4. Variables**
>
>
> Shell variables are **all** untyped (ie. no `def` or other type information).
>
>
> This will set a shell variable:
>
>
>
> ```
> foo = "bar"
>
> ```
>
> But, this will evaluate a local variable and will **not** be saved to the shell’s environment:
>
>
>
> ```
> def foo = "bar"
>
> ```
>
>
You can change this behaviour by enabling [interpreterMode](http://groovy-lang.org/groovysh.html#GroovyShell-InterpreterMode "interpreterMode")
```
groovy:000> := interpreterMode
groovy:000> def x = 42
===> 42
groovy:000> x
===> 42
groovy:000>
```
|
"def" are more like compiled variables in Java way (to some degree), compiled (maybe type is unknown/dynamic, but name/existence of variable / property is known).
`def xyz = 1` -> `Object xyz = 1;`
Without "def" are added to specific container Binder by name, in fully dynamic manner. Imagine this like specific Map *(sorry for simplicity)*
```
binder["xyz"] = 1;
```
My personal filling is that Groovy doc don't illustrate this (huge) difference clearly. Word "untyped" seems to weak.
Implementation of "storage" for this two is totally different.
|
11,134,610 |
I have a object A move with Velocity (v1, v2, v3) in 3D space.
Object position is (px,py,pz)
Now i want to add certain particles around object A (in radius dis) on plane which perpendicular to its Velocity direction.
I find something call "cross product" but seen that no use in this case.
Anyone can help?
I'm new to python and don't really know how to crack it.
|
2012/06/21
|
['https://Stackoverflow.com/questions/11134610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471511/']
|
The plane perpendicular to a vector ⟨A, B, C⟩ has the general equation Ax + By + Cz + K = 0.
|
Lets say we have a point p1, and we want to build a circle of points around it with radius r so that all points on the circle are orthogonal to a vector n.. here is a working example
```
p1 = np.array([-21.03181359, 4.54876345, 19.26943601])
n = np.array([-0.06592715, 0.00713031, -0.26809672])
n = n / np.linalg.norm(n) # normalise n
r = 0.5
x = np.array([1,0,0]).astype(np.float64) # take a random vector of magnitude 1
x -= x.dot(n) * n / np.linalg.norm(n)**2 # make it orthogonal to n
x /= np.linalg.norm(x) # normalize
# find first point on circle (x1).
# currently it has magnitude of 1, so we multiply it by the r
x1 = p1 + (x*r)
# vector from lumen centre to first circle point
p1x1 = x1 - p1
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
axis = axis / math.sqrt(np.dot(axis, axis))
a = math.cos(theta / 2.0)
b, c, d = -axis * math.sin(theta / 2.0)
aa, bb, cc, dd = a * a, b * b, c * c, d * d
bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d
return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],
[2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],
[2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])
# rotate the vector p1x1 around the axis n with angle theta
circle = []
for theta in range(0,360,6):
circle_i = np.dot(rotation_matrix(n, np.deg2rad(theta)), p1x1)
circle.append(circle_i+p1)
ax = axes3d.Axes3D(plt.figure(figsize=(10,10)))
ax.scatter3D(*np.array(circle).T, s=10, c='red')
ax.scatter3D(*p1.T, s=10, c='black')
ax.set_xlabel('X', size=40)
ax.set_ylabel('Y', size=40)
ax.set_zlabel('Z', size=40)
ax.set_xlim(-19,-22)
ax.set_ylim(2,5)
ax.set_zlim(18,21)
```
|
11,134,610 |
I have a object A move with Velocity (v1, v2, v3) in 3D space.
Object position is (px,py,pz)
Now i want to add certain particles around object A (in radius dis) on plane which perpendicular to its Velocity direction.
I find something call "cross product" but seen that no use in this case.
Anyone can help?
I'm new to python and don't really know how to crack it.
|
2012/06/21
|
['https://Stackoverflow.com/questions/11134610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471511/']
|
The equation of the plane is:
```
v1*(x-px) + v2*(y-py) + v3*(z-pz) = 0
```
When you know `(x,y)` you can find `z` and so on.
Example:
z = pz - (v1\*(x-px) + v2\*(y-py))/v3
|
Lets say we have a point p1, and we want to build a circle of points around it with radius r so that all points on the circle are orthogonal to a vector n.. here is a working example
```
p1 = np.array([-21.03181359, 4.54876345, 19.26943601])
n = np.array([-0.06592715, 0.00713031, -0.26809672])
n = n / np.linalg.norm(n) # normalise n
r = 0.5
x = np.array([1,0,0]).astype(np.float64) # take a random vector of magnitude 1
x -= x.dot(n) * n / np.linalg.norm(n)**2 # make it orthogonal to n
x /= np.linalg.norm(x) # normalize
# find first point on circle (x1).
# currently it has magnitude of 1, so we multiply it by the r
x1 = p1 + (x*r)
# vector from lumen centre to first circle point
p1x1 = x1 - p1
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
axis = axis / math.sqrt(np.dot(axis, axis))
a = math.cos(theta / 2.0)
b, c, d = -axis * math.sin(theta / 2.0)
aa, bb, cc, dd = a * a, b * b, c * c, d * d
bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d
return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],
[2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],
[2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]])
# rotate the vector p1x1 around the axis n with angle theta
circle = []
for theta in range(0,360,6):
circle_i = np.dot(rotation_matrix(n, np.deg2rad(theta)), p1x1)
circle.append(circle_i+p1)
ax = axes3d.Axes3D(plt.figure(figsize=(10,10)))
ax.scatter3D(*np.array(circle).T, s=10, c='red')
ax.scatter3D(*p1.T, s=10, c='black')
ax.set_xlabel('X', size=40)
ax.set_ylabel('Y', size=40)
ax.set_zlabel('Z', size=40)
ax.set_xlim(-19,-22)
ax.set_ylim(2,5)
ax.set_zlim(18,21)
```
|
37,384,772 |
I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online.
This is my code for JSON request.
```
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON)
.responseJSON { (request, response, result) in
hud.hide(true)
// Set flag to disale poor internet connection alert
weakInternet = false
print(result.error)
if (result.value != nil) {
print("API Response: \(result.value!)")
// Pass the response JSON to the completion block
completion(json: result.value!)
} else {
// Response JSON is NULL
}
}
```
When i hit the same service with particular request parameters i am getting this response.
```
{"error":"success","post_data":{"first_name":"hd","last_name":"df","email":"[email protected]","password":"himanshu","confirm_password":"himanshu","companies":["Big Rattle Technologies_Fg_yes"],"institutes":[""]},"msg":"success","data":{"_id":"5742ae1564b35e37369f0838","first_name":"hd","last_name":"df","email":"[email protected]","profile_pic":"","loc":[0,0],"locs":{"type":"Point","coordinates":[0,0]},"institutes":[],"companies":[{"comapny_id":"555b2d0a678e79ed510041ce","group_id":"556c2434678e79a1820041dd","name":"Big Rattle Technologies","designation":"Fg","is_current":"yes"}],"device_token":"","user_group":"site_user","is_verified":0,"is_disclose":1,"is_discover":1,"wallNotification":1,"messageNotification":1,"matchNotification":1,"verificationSent":0,"status":1,"mobile":"","linkedin_id":"","facebook_id":"","os":"","qblox_id":12957726,"updated_at":"2016-05-23 07:15:33","created_at":"2016-05-23 07:15:33","current_company":"Big Rattle Technologies"}}
```
Anybody knows what is the problem in my case?
|
2016/05/23
|
['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']
|
There is an issue with my web service. They are giving me the response in "text/HTML" format rather than HTML. When i printed my response on debugger then i got:
```
"Content-Type" = "text/html; charset=UTF-8";
```
Now, i updated my webservice and everything is working like a charm.
|
I am getting same error last time because there will be problem is web service returns me response in array and i am trying to convert its into dictionary and extract its value.
Check Your web service response.
|
37,384,772 |
I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online.
This is my code for JSON request.
```
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON)
.responseJSON { (request, response, result) in
hud.hide(true)
// Set flag to disale poor internet connection alert
weakInternet = false
print(result.error)
if (result.value != nil) {
print("API Response: \(result.value!)")
// Pass the response JSON to the completion block
completion(json: result.value!)
} else {
// Response JSON is NULL
}
}
```
When i hit the same service with particular request parameters i am getting this response.
```
{"error":"success","post_data":{"first_name":"hd","last_name":"df","email":"[email protected]","password":"himanshu","confirm_password":"himanshu","companies":["Big Rattle Technologies_Fg_yes"],"institutes":[""]},"msg":"success","data":{"_id":"5742ae1564b35e37369f0838","first_name":"hd","last_name":"df","email":"[email protected]","profile_pic":"","loc":[0,0],"locs":{"type":"Point","coordinates":[0,0]},"institutes":[],"companies":[{"comapny_id":"555b2d0a678e79ed510041ce","group_id":"556c2434678e79a1820041dd","name":"Big Rattle Technologies","designation":"Fg","is_current":"yes"}],"device_token":"","user_group":"site_user","is_verified":0,"is_disclose":1,"is_discover":1,"wallNotification":1,"messageNotification":1,"matchNotification":1,"verificationSent":0,"status":1,"mobile":"","linkedin_id":"","facebook_id":"","os":"","qblox_id":12957726,"updated_at":"2016-05-23 07:15:33","created_at":"2016-05-23 07:15:33","current_company":"Big Rattle Technologies"}}
```
Anybody knows what is the problem in my case?
|
2016/05/23
|
['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']
|
I am getting same error last time because there will be problem is web service returns me response in array and i am trying to convert its into dictionary and extract its value.
Check Your web service response.
|
Swift 5, Swift 4
```
var headers = HTTPHeaders()
headers = [
"Content-Type" :"text/html; charset=UTF-8",
//"Content-Type": "application/json",
//"Content-Type": "application/x-www-form-urlencoded",
//"Accept": "application/json",
"Accept": "multipart/form-data"
]
```
|
37,384,772 |
I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online.
This is my code for JSON request.
```
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON)
.responseJSON { (request, response, result) in
hud.hide(true)
// Set flag to disale poor internet connection alert
weakInternet = false
print(result.error)
if (result.value != nil) {
print("API Response: \(result.value!)")
// Pass the response JSON to the completion block
completion(json: result.value!)
} else {
// Response JSON is NULL
}
}
```
When i hit the same service with particular request parameters i am getting this response.
```
{"error":"success","post_data":{"first_name":"hd","last_name":"df","email":"[email protected]","password":"himanshu","confirm_password":"himanshu","companies":["Big Rattle Technologies_Fg_yes"],"institutes":[""]},"msg":"success","data":{"_id":"5742ae1564b35e37369f0838","first_name":"hd","last_name":"df","email":"[email protected]","profile_pic":"","loc":[0,0],"locs":{"type":"Point","coordinates":[0,0]},"institutes":[],"companies":[{"comapny_id":"555b2d0a678e79ed510041ce","group_id":"556c2434678e79a1820041dd","name":"Big Rattle Technologies","designation":"Fg","is_current":"yes"}],"device_token":"","user_group":"site_user","is_verified":0,"is_disclose":1,"is_discover":1,"wallNotification":1,"messageNotification":1,"matchNotification":1,"verificationSent":0,"status":1,"mobile":"","linkedin_id":"","facebook_id":"","os":"","qblox_id":12957726,"updated_at":"2016-05-23 07:15:33","created_at":"2016-05-23 07:15:33","current_company":"Big Rattle Technologies"}}
```
Anybody knows what is the problem in my case?
|
2016/05/23
|
['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']
|
I am getting same error last time because there will be problem is web service returns me response in array and i am trying to convert its into dictionary and extract its value.
Check Your web service response.
|
I got this error when using the **wrong** Firebase Server key to send a remote push notification.
Go to `Firebase` > `Project Overview` > `CogIcon` > `Project Settings` > `Cloud Messaging` > `Server Key`
[](https://i.stack.imgur.com/CLK8F.png)
```
guard let url = URL(string: "https://fcm.googleapis.com/fcm/send") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try?
let paramDict = [String:Any]() // this has values
JSONSerialization.data(withJSONObject: paramDict, options: [])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let serverKey = "firebase server key" // *** SERVER KEY USED HERE ***
request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
if let jsonData = data {
if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
print("jsonData Successfully Sent data: \n\(jsonDataDict))")
}
}
} catch let err as NSError {
print("jsonData Error: \(err.debugDescription)")
}
}
task.resume()
```
|
37,384,772 |
I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online.
This is my code for JSON request.
```
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON)
.responseJSON { (request, response, result) in
hud.hide(true)
// Set flag to disale poor internet connection alert
weakInternet = false
print(result.error)
if (result.value != nil) {
print("API Response: \(result.value!)")
// Pass the response JSON to the completion block
completion(json: result.value!)
} else {
// Response JSON is NULL
}
}
```
When i hit the same service with particular request parameters i am getting this response.
```
{"error":"success","post_data":{"first_name":"hd","last_name":"df","email":"[email protected]","password":"himanshu","confirm_password":"himanshu","companies":["Big Rattle Technologies_Fg_yes"],"institutes":[""]},"msg":"success","data":{"_id":"5742ae1564b35e37369f0838","first_name":"hd","last_name":"df","email":"[email protected]","profile_pic":"","loc":[0,0],"locs":{"type":"Point","coordinates":[0,0]},"institutes":[],"companies":[{"comapny_id":"555b2d0a678e79ed510041ce","group_id":"556c2434678e79a1820041dd","name":"Big Rattle Technologies","designation":"Fg","is_current":"yes"}],"device_token":"","user_group":"site_user","is_verified":0,"is_disclose":1,"is_discover":1,"wallNotification":1,"messageNotification":1,"matchNotification":1,"verificationSent":0,"status":1,"mobile":"","linkedin_id":"","facebook_id":"","os":"","qblox_id":12957726,"updated_at":"2016-05-23 07:15:33","created_at":"2016-05-23 07:15:33","current_company":"Big Rattle Technologies"}}
```
Anybody knows what is the problem in my case?
|
2016/05/23
|
['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']
|
I am getting same error last time because there will be problem is web service returns me response in array and i am trying to convert its into dictionary and extract its value.
Check Your web service response.
|
Make Sure The firewall Off from Server
|
37,384,772 |
I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online.
This is my code for JSON request.
```
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON)
.responseJSON { (request, response, result) in
hud.hide(true)
// Set flag to disale poor internet connection alert
weakInternet = false
print(result.error)
if (result.value != nil) {
print("API Response: \(result.value!)")
// Pass the response JSON to the completion block
completion(json: result.value!)
} else {
// Response JSON is NULL
}
}
```
When i hit the same service with particular request parameters i am getting this response.
```
{"error":"success","post_data":{"first_name":"hd","last_name":"df","email":"[email protected]","password":"himanshu","confirm_password":"himanshu","companies":["Big Rattle Technologies_Fg_yes"],"institutes":[""]},"msg":"success","data":{"_id":"5742ae1564b35e37369f0838","first_name":"hd","last_name":"df","email":"[email protected]","profile_pic":"","loc":[0,0],"locs":{"type":"Point","coordinates":[0,0]},"institutes":[],"companies":[{"comapny_id":"555b2d0a678e79ed510041ce","group_id":"556c2434678e79a1820041dd","name":"Big Rattle Technologies","designation":"Fg","is_current":"yes"}],"device_token":"","user_group":"site_user","is_verified":0,"is_disclose":1,"is_discover":1,"wallNotification":1,"messageNotification":1,"matchNotification":1,"verificationSent":0,"status":1,"mobile":"","linkedin_id":"","facebook_id":"","os":"","qblox_id":12957726,"updated_at":"2016-05-23 07:15:33","created_at":"2016-05-23 07:15:33","current_company":"Big Rattle Technologies"}}
```
Anybody knows what is the problem in my case?
|
2016/05/23
|
['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']
|
There is an issue with my web service. They are giving me the response in "text/HTML" format rather than HTML. When i printed my response on debugger then i got:
```
"Content-Type" = "text/html; charset=UTF-8";
```
Now, i updated my webservice and everything is working like a charm.
|
Swift 5, Swift 4
```
var headers = HTTPHeaders()
headers = [
"Content-Type" :"text/html; charset=UTF-8",
//"Content-Type": "application/json",
//"Content-Type": "application/x-www-form-urlencoded",
//"Accept": "application/json",
"Accept": "multipart/form-data"
]
```
|
37,384,772 |
I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online.
This is my code for JSON request.
```
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON)
.responseJSON { (request, response, result) in
hud.hide(true)
// Set flag to disale poor internet connection alert
weakInternet = false
print(result.error)
if (result.value != nil) {
print("API Response: \(result.value!)")
// Pass the response JSON to the completion block
completion(json: result.value!)
} else {
// Response JSON is NULL
}
}
```
When i hit the same service with particular request parameters i am getting this response.
```
{"error":"success","post_data":{"first_name":"hd","last_name":"df","email":"[email protected]","password":"himanshu","confirm_password":"himanshu","companies":["Big Rattle Technologies_Fg_yes"],"institutes":[""]},"msg":"success","data":{"_id":"5742ae1564b35e37369f0838","first_name":"hd","last_name":"df","email":"[email protected]","profile_pic":"","loc":[0,0],"locs":{"type":"Point","coordinates":[0,0]},"institutes":[],"companies":[{"comapny_id":"555b2d0a678e79ed510041ce","group_id":"556c2434678e79a1820041dd","name":"Big Rattle Technologies","designation":"Fg","is_current":"yes"}],"device_token":"","user_group":"site_user","is_verified":0,"is_disclose":1,"is_discover":1,"wallNotification":1,"messageNotification":1,"matchNotification":1,"verificationSent":0,"status":1,"mobile":"","linkedin_id":"","facebook_id":"","os":"","qblox_id":12957726,"updated_at":"2016-05-23 07:15:33","created_at":"2016-05-23 07:15:33","current_company":"Big Rattle Technologies"}}
```
Anybody knows what is the problem in my case?
|
2016/05/23
|
['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']
|
There is an issue with my web service. They are giving me the response in "text/HTML" format rather than HTML. When i printed my response on debugger then i got:
```
"Content-Type" = "text/html; charset=UTF-8";
```
Now, i updated my webservice and everything is working like a charm.
|
I got this error when using the **wrong** Firebase Server key to send a remote push notification.
Go to `Firebase` > `Project Overview` > `CogIcon` > `Project Settings` > `Cloud Messaging` > `Server Key`
[](https://i.stack.imgur.com/CLK8F.png)
```
guard let url = URL(string: "https://fcm.googleapis.com/fcm/send") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try?
let paramDict = [String:Any]() // this has values
JSONSerialization.data(withJSONObject: paramDict, options: [])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let serverKey = "firebase server key" // *** SERVER KEY USED HERE ***
request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
if let jsonData = data {
if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
print("jsonData Successfully Sent data: \n\(jsonDataDict))")
}
}
} catch let err as NSError {
print("jsonData Error: \(err.debugDescription)")
}
}
task.resume()
```
|
37,384,772 |
I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online.
This is my code for JSON request.
```
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON)
.responseJSON { (request, response, result) in
hud.hide(true)
// Set flag to disale poor internet connection alert
weakInternet = false
print(result.error)
if (result.value != nil) {
print("API Response: \(result.value!)")
// Pass the response JSON to the completion block
completion(json: result.value!)
} else {
// Response JSON is NULL
}
}
```
When i hit the same service with particular request parameters i am getting this response.
```
{"error":"success","post_data":{"first_name":"hd","last_name":"df","email":"[email protected]","password":"himanshu","confirm_password":"himanshu","companies":["Big Rattle Technologies_Fg_yes"],"institutes":[""]},"msg":"success","data":{"_id":"5742ae1564b35e37369f0838","first_name":"hd","last_name":"df","email":"[email protected]","profile_pic":"","loc":[0,0],"locs":{"type":"Point","coordinates":[0,0]},"institutes":[],"companies":[{"comapny_id":"555b2d0a678e79ed510041ce","group_id":"556c2434678e79a1820041dd","name":"Big Rattle Technologies","designation":"Fg","is_current":"yes"}],"device_token":"","user_group":"site_user","is_verified":0,"is_disclose":1,"is_discover":1,"wallNotification":1,"messageNotification":1,"matchNotification":1,"verificationSent":0,"status":1,"mobile":"","linkedin_id":"","facebook_id":"","os":"","qblox_id":12957726,"updated_at":"2016-05-23 07:15:33","created_at":"2016-05-23 07:15:33","current_company":"Big Rattle Technologies"}}
```
Anybody knows what is the problem in my case?
|
2016/05/23
|
['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']
|
There is an issue with my web service. They are giving me the response in "text/HTML" format rather than HTML. When i printed my response on debugger then i got:
```
"Content-Type" = "text/html; charset=UTF-8";
```
Now, i updated my webservice and everything is working like a charm.
|
Make Sure The firewall Off from Server
|
37,384,772 |
I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online.
This is my code for JSON request.
```
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON)
.responseJSON { (request, response, result) in
hud.hide(true)
// Set flag to disale poor internet connection alert
weakInternet = false
print(result.error)
if (result.value != nil) {
print("API Response: \(result.value!)")
// Pass the response JSON to the completion block
completion(json: result.value!)
} else {
// Response JSON is NULL
}
}
```
When i hit the same service with particular request parameters i am getting this response.
```
{"error":"success","post_data":{"first_name":"hd","last_name":"df","email":"[email protected]","password":"himanshu","confirm_password":"himanshu","companies":["Big Rattle Technologies_Fg_yes"],"institutes":[""]},"msg":"success","data":{"_id":"5742ae1564b35e37369f0838","first_name":"hd","last_name":"df","email":"[email protected]","profile_pic":"","loc":[0,0],"locs":{"type":"Point","coordinates":[0,0]},"institutes":[],"companies":[{"comapny_id":"555b2d0a678e79ed510041ce","group_id":"556c2434678e79a1820041dd","name":"Big Rattle Technologies","designation":"Fg","is_current":"yes"}],"device_token":"","user_group":"site_user","is_verified":0,"is_disclose":1,"is_discover":1,"wallNotification":1,"messageNotification":1,"matchNotification":1,"verificationSent":0,"status":1,"mobile":"","linkedin_id":"","facebook_id":"","os":"","qblox_id":12957726,"updated_at":"2016-05-23 07:15:33","created_at":"2016-05-23 07:15:33","current_company":"Big Rattle Technologies"}}
```
Anybody knows what is the problem in my case?
|
2016/05/23
|
['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']
|
Swift 5, Swift 4
```
var headers = HTTPHeaders()
headers = [
"Content-Type" :"text/html; charset=UTF-8",
//"Content-Type": "application/json",
//"Content-Type": "application/x-www-form-urlencoded",
//"Accept": "application/json",
"Accept": "multipart/form-data"
]
```
|
I got this error when using the **wrong** Firebase Server key to send a remote push notification.
Go to `Firebase` > `Project Overview` > `CogIcon` > `Project Settings` > `Cloud Messaging` > `Server Key`
[](https://i.stack.imgur.com/CLK8F.png)
```
guard let url = URL(string: "https://fcm.googleapis.com/fcm/send") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try?
let paramDict = [String:Any]() // this has values
JSONSerialization.data(withJSONObject: paramDict, options: [])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let serverKey = "firebase server key" // *** SERVER KEY USED HERE ***
request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
if let jsonData = data {
if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
print("jsonData Successfully Sent data: \n\(jsonDataDict))")
}
}
} catch let err as NSError {
print("jsonData Error: \(err.debugDescription)")
}
}
task.resume()
```
|
37,384,772 |
I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online.
This is my code for JSON request.
```
Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON)
.responseJSON { (request, response, result) in
hud.hide(true)
// Set flag to disale poor internet connection alert
weakInternet = false
print(result.error)
if (result.value != nil) {
print("API Response: \(result.value!)")
// Pass the response JSON to the completion block
completion(json: result.value!)
} else {
// Response JSON is NULL
}
}
```
When i hit the same service with particular request parameters i am getting this response.
```
{"error":"success","post_data":{"first_name":"hd","last_name":"df","email":"[email protected]","password":"himanshu","confirm_password":"himanshu","companies":["Big Rattle Technologies_Fg_yes"],"institutes":[""]},"msg":"success","data":{"_id":"5742ae1564b35e37369f0838","first_name":"hd","last_name":"df","email":"[email protected]","profile_pic":"","loc":[0,0],"locs":{"type":"Point","coordinates":[0,0]},"institutes":[],"companies":[{"comapny_id":"555b2d0a678e79ed510041ce","group_id":"556c2434678e79a1820041dd","name":"Big Rattle Technologies","designation":"Fg","is_current":"yes"}],"device_token":"","user_group":"site_user","is_verified":0,"is_disclose":1,"is_discover":1,"wallNotification":1,"messageNotification":1,"matchNotification":1,"verificationSent":0,"status":1,"mobile":"","linkedin_id":"","facebook_id":"","os":"","qblox_id":12957726,"updated_at":"2016-05-23 07:15:33","created_at":"2016-05-23 07:15:33","current_company":"Big Rattle Technologies"}}
```
Anybody knows what is the problem in my case?
|
2016/05/23
|
['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']
|
Swift 5, Swift 4
```
var headers = HTTPHeaders()
headers = [
"Content-Type" :"text/html; charset=UTF-8",
//"Content-Type": "application/json",
//"Content-Type": "application/x-www-form-urlencoded",
//"Accept": "application/json",
"Accept": "multipart/form-data"
]
```
|
Make Sure The firewall Off from Server
|
48,243 |
This is probably something I don't understand since I am used to Windows
and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software.
I mean, every application is run by a specific user, and that user will
only be able to run that applciation with his privilages, so if he has
no admin privileges, the application also won't be able to access unauthorized
directories etc.
I want most of the time to work on my PC with a non-admin user since it seems
more safe to me, most of the time I have no need for admin privileges.
and even though I know viruses in linux are uncommon I still think the best
practice is to work on the computer in a state that you yourself can't
make any changes to important files, that way viruses also can't harm any important
files, but I need to install software for programming and web-design etc.
and first of all I don't want to switch users all the time.
But also it sounds safer to me that everything being done on the PC
will be done through the non-admin user.
I'll be glad to know what misunderstanding I have here, cause
something here doesn't sound right.
|
2011/06/11
|
['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']
|
Why you're asked for a password
-------------------------------
Most software is designed to touch sensitive files, i.e. sensitive to the security of your private data or the systems integrity. This is why software installation is a potential risk and should be validated by a user who knows what he is doing. Even for open source Software you can not be sure that no bad code bits arrive with your percious new audio player until someone checked. And even then something could have been overlooked or packages could be manipulated on the way. Who knows what's hidden in the depth of the program? One user should.
Ubuntu provides a comfortable way of installing software. Software developers can rely on that comfort and make the assumption that synaptic/software center/apt enables them to access these sensitive files. Canonical checks the software repository for bugs and malicious code. But the ultimate responsibility is yours.
If the software in question does not need access to sensitive files, it can (in principle) be installed in the home folder though not in the Ubuntu way. You will for instance have to compile the source code yourself or run a custom install script. Beside the greater efforts of that it has the disadvantage of not allowing other users access to your just installed program (as they have no right to access your home-folder). They will need to installed it a second time. So this way of installation makes no sense in a large scale and in a small scale it's usually easier to type a password than to install software manually.
So that's why Synaptic aaks for a password and why it's good that it does.
---
Sudoers
-------
**If you are really in dire need of having other users install software without password**, you can add them to the sudoers list. This however will result in **a great security risk**. If that doesn't concern you, consider that there a bot networks out there with great resources to break into your computer via Internet. They do this just to add your computer to the net and use it's connection and computing power without your knowledge to do all sorts of illegal stuff. They are not even after your personal data your you for that matter. They just want to hijack your PC. Still not concerned? Really? Then look at the following answer which is a small how-to on the workings of sudoers list:
[How to make Ubuntu remember forever the password after the first time](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)
Read that carefully. You could lock yourself out of the system.
### The scare is over
So now you have the scare behind you are and taking the matter seriously, I can tell you it's really not that bad. If you trust the people working on your computer, and you don't have programs installed that allow remote access to your system (e.g. an ssh- or ftp-server), then it's really not that dangerous to disable the password stuff. Just don't do it without considering the worst case and think of your private data.
---
Overlook on the proceedings (**don't do this lightly** - see text and [link above](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)):
```
# in shell type these commands
sudo su # in case you do something stupid, you'll have a root shell open
select-editor # (optional) will allow you to select text editor
visudo # secure way to open sudoers list
```
An editor will open ADD a line like this:
```
confus confusion=(root) NOPASSWD:/usr/sbin/synaptic,/usr/bin/software-center
```
Syntax explanation: `username machine=(usernameToRunCommandAs) command1,command2,...`. So the above line allows confus to run synaptic and softwarecenter as root without password query. You will still need to start it with `sudo synaptic` or `gksudo synaptic` or put an alias `alias synaptic='sudo synaptic' in your shell profile.
|
You touched upon a BIG difference between windows and ubuntu. In Windows when you are logged in as an admin programms will be installed without asking for a password. This enables also malware to run their programs. In Ubuntu (Linux) even being logged in as an admin the system will always ask for your password when you change the system. Therefore, malware cant intrude your system easily. To sum up run Ubuntu as an admin. If you open another user account for your kids than give them only normal user rights so they cant screw up the system.
|
48,243 |
This is probably something I don't understand since I am used to Windows
and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software.
I mean, every application is run by a specific user, and that user will
only be able to run that applciation with his privilages, so if he has
no admin privileges, the application also won't be able to access unauthorized
directories etc.
I want most of the time to work on my PC with a non-admin user since it seems
more safe to me, most of the time I have no need for admin privileges.
and even though I know viruses in linux are uncommon I still think the best
practice is to work on the computer in a state that you yourself can't
make any changes to important files, that way viruses also can't harm any important
files, but I need to install software for programming and web-design etc.
and first of all I don't want to switch users all the time.
But also it sounds safer to me that everything being done on the PC
will be done through the non-admin user.
I'll be glad to know what misunderstanding I have here, cause
something here doesn't sound right.
|
2011/06/11
|
['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']
|
Why you're asked for a password
-------------------------------
Most software is designed to touch sensitive files, i.e. sensitive to the security of your private data or the systems integrity. This is why software installation is a potential risk and should be validated by a user who knows what he is doing. Even for open source Software you can not be sure that no bad code bits arrive with your percious new audio player until someone checked. And even then something could have been overlooked or packages could be manipulated on the way. Who knows what's hidden in the depth of the program? One user should.
Ubuntu provides a comfortable way of installing software. Software developers can rely on that comfort and make the assumption that synaptic/software center/apt enables them to access these sensitive files. Canonical checks the software repository for bugs and malicious code. But the ultimate responsibility is yours.
If the software in question does not need access to sensitive files, it can (in principle) be installed in the home folder though not in the Ubuntu way. You will for instance have to compile the source code yourself or run a custom install script. Beside the greater efforts of that it has the disadvantage of not allowing other users access to your just installed program (as they have no right to access your home-folder). They will need to installed it a second time. So this way of installation makes no sense in a large scale and in a small scale it's usually easier to type a password than to install software manually.
So that's why Synaptic aaks for a password and why it's good that it does.
---
Sudoers
-------
**If you are really in dire need of having other users install software without password**, you can add them to the sudoers list. This however will result in **a great security risk**. If that doesn't concern you, consider that there a bot networks out there with great resources to break into your computer via Internet. They do this just to add your computer to the net and use it's connection and computing power without your knowledge to do all sorts of illegal stuff. They are not even after your personal data your you for that matter. They just want to hijack your PC. Still not concerned? Really? Then look at the following answer which is a small how-to on the workings of sudoers list:
[How to make Ubuntu remember forever the password after the first time](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)
Read that carefully. You could lock yourself out of the system.
### The scare is over
So now you have the scare behind you are and taking the matter seriously, I can tell you it's really not that bad. If you trust the people working on your computer, and you don't have programs installed that allow remote access to your system (e.g. an ssh- or ftp-server), then it's really not that dangerous to disable the password stuff. Just don't do it without considering the worst case and think of your private data.
---
Overlook on the proceedings (**don't do this lightly** - see text and [link above](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)):
```
# in shell type these commands
sudo su # in case you do something stupid, you'll have a root shell open
select-editor # (optional) will allow you to select text editor
visudo # secure way to open sudoers list
```
An editor will open ADD a line like this:
```
confus confusion=(root) NOPASSWD:/usr/sbin/synaptic,/usr/bin/software-center
```
Syntax explanation: `username machine=(usernameToRunCommandAs) command1,command2,...`. So the above line allows confus to run synaptic and softwarecenter as root without password query. You will still need to start it with `sudo synaptic` or `gksudo synaptic` or put an alias `alias synaptic='sudo synaptic' in your shell profile.
|
In Ubuntu, the administrator has root privileges (often referred as just "root", as in "you need to be root").
Access to files can be split in three types:
* read (numeric value 4)
* write (numeric value 2)
* execute (numeric value 1)
These attributes can be set on every file or directory. Furthermore, these restrictions can be set on:
* the owner of the file
* the group of the file (users can be a member of this group)
* all other users which are not the owner nor in the group
These principles forms the basics of Linux file permissions. In windows, everything can be executed. Give it an `.cmd` or `.exe` extension for example. In Ubuntu, you need to add the execute bit explicitly, otherwise a permission error will be raised.
When an user executes a program, the program accesses files as that user and these file permissions kicks in. By default, locations where programs are installed are privileged, only the owner can write. This owner is root. All other users can only read and execute the program, not write to it. That's why you need root privileges to install programs.
Ubuntu has a special program called `sudo` (SuperUser DO ...) to run programs with root privileges. This can be used for installing software. When run, the `sudo` program asks you for your user password. Note that only members of the `admin` group can run programs as root using `sudo`.
In Windows, you would go to a website and download an installer. Ubuntu works with a software repository in which you can search for programs and install those. These programs are reviewed before added to the official repositories, so you can be sure that no harmful intentions exist in the programs.
|
48,243 |
This is probably something I don't understand since I am used to Windows
and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software.
I mean, every application is run by a specific user, and that user will
only be able to run that applciation with his privilages, so if he has
no admin privileges, the application also won't be able to access unauthorized
directories etc.
I want most of the time to work on my PC with a non-admin user since it seems
more safe to me, most of the time I have no need for admin privileges.
and even though I know viruses in linux are uncommon I still think the best
practice is to work on the computer in a state that you yourself can't
make any changes to important files, that way viruses also can't harm any important
files, but I need to install software for programming and web-design etc.
and first of all I don't want to switch users all the time.
But also it sounds safer to me that everything being done on the PC
will be done through the non-admin user.
I'll be glad to know what misunderstanding I have here, cause
something here doesn't sound right.
|
2011/06/11
|
['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']
|
Non-admin users cannot install software because the packages run as root when they're installing as they install to privileged parts of the system, run maintainer scripts, etc.
There is currently no way to tell the system "Install firefox from this .deb but in a user's home directory so that it's isolated from the rest of the system"; which is why currently it's mostly an all or nothing affair. (This is also why running third party .debs is bad, the package and it's included scripts have root access to your system)
|
You can install software as a regular, non-admin, user. Software installed by a regular user will be "owned" by that user, which means that, in effect, it is an extension of the user -- it has no more permissions than the owning user does, though it may have fewer permissions, at the user's option.
A common practice is for a user to create a 'bin' directory within their home directory. If /home/[user]/bin exists, it is added to the beginning of that user's path. You can place executable files in /home/[user]/bin, or in any other folder to which you have write and execute access, and execute the program from there.
What a regular user can't do is install a package system-wide. A regular user can't put executable files in /usr/bin, for instance, nor grant them permissions that exceed the user's own permissions. This is, obviously, for basic security reasons -- you need admin permissions to reformat a hard drive, for instance, and you don't want someone unauthorized doing that.
As far as I know, you cannot use package management software to install a software package unless you have admin permissions, as package management is done system-wide.
However, without admin permissions, you can create shell scripts, write and compile source code, download and compile "tarballs", which are packages of source code for complex applications, or download executable files, so long as these can be used with only the permissions of a regular user. Some indie games, such as World of Goo or X-Plane 9, can be installed and used in this way.
|
48,243 |
This is probably something I don't understand since I am used to Windows
and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software.
I mean, every application is run by a specific user, and that user will
only be able to run that applciation with his privilages, so if he has
no admin privileges, the application also won't be able to access unauthorized
directories etc.
I want most of the time to work on my PC with a non-admin user since it seems
more safe to me, most of the time I have no need for admin privileges.
and even though I know viruses in linux are uncommon I still think the best
practice is to work on the computer in a state that you yourself can't
make any changes to important files, that way viruses also can't harm any important
files, but I need to install software for programming and web-design etc.
and first of all I don't want to switch users all the time.
But also it sounds safer to me that everything being done on the PC
will be done through the non-admin user.
I'll be glad to know what misunderstanding I have here, cause
something here doesn't sound right.
|
2011/06/11
|
['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']
|
In Ubuntu, the administrator has root privileges (often referred as just "root", as in "you need to be root").
Access to files can be split in three types:
* read (numeric value 4)
* write (numeric value 2)
* execute (numeric value 1)
These attributes can be set on every file or directory. Furthermore, these restrictions can be set on:
* the owner of the file
* the group of the file (users can be a member of this group)
* all other users which are not the owner nor in the group
These principles forms the basics of Linux file permissions. In windows, everything can be executed. Give it an `.cmd` or `.exe` extension for example. In Ubuntu, you need to add the execute bit explicitly, otherwise a permission error will be raised.
When an user executes a program, the program accesses files as that user and these file permissions kicks in. By default, locations where programs are installed are privileged, only the owner can write. This owner is root. All other users can only read and execute the program, not write to it. That's why you need root privileges to install programs.
Ubuntu has a special program called `sudo` (SuperUser DO ...) to run programs with root privileges. This can be used for installing software. When run, the `sudo` program asks you for your user password. Note that only members of the `admin` group can run programs as root using `sudo`.
In Windows, you would go to a website and download an installer. Ubuntu works with a software repository in which you can search for programs and install those. These programs are reviewed before added to the official repositories, so you can be sure that no harmful intentions exist in the programs.
|
You can install software as a regular, non-admin, user. Software installed by a regular user will be "owned" by that user, which means that, in effect, it is an extension of the user -- it has no more permissions than the owning user does, though it may have fewer permissions, at the user's option.
A common practice is for a user to create a 'bin' directory within their home directory. If /home/[user]/bin exists, it is added to the beginning of that user's path. You can place executable files in /home/[user]/bin, or in any other folder to which you have write and execute access, and execute the program from there.
What a regular user can't do is install a package system-wide. A regular user can't put executable files in /usr/bin, for instance, nor grant them permissions that exceed the user's own permissions. This is, obviously, for basic security reasons -- you need admin permissions to reformat a hard drive, for instance, and you don't want someone unauthorized doing that.
As far as I know, you cannot use package management software to install a software package unless you have admin permissions, as package management is done system-wide.
However, without admin permissions, you can create shell scripts, write and compile source code, download and compile "tarballs", which are packages of source code for complex applications, or download executable files, so long as these can be used with only the permissions of a regular user. Some indie games, such as World of Goo or X-Plane 9, can be installed and used in this way.
|
48,243 |
This is probably something I don't understand since I am used to Windows
and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software.
I mean, every application is run by a specific user, and that user will
only be able to run that applciation with his privilages, so if he has
no admin privileges, the application also won't be able to access unauthorized
directories etc.
I want most of the time to work on my PC with a non-admin user since it seems
more safe to me, most of the time I have no need for admin privileges.
and even though I know viruses in linux are uncommon I still think the best
practice is to work on the computer in a state that you yourself can't
make any changes to important files, that way viruses also can't harm any important
files, but I need to install software for programming and web-design etc.
and first of all I don't want to switch users all the time.
But also it sounds safer to me that everything being done on the PC
will be done through the non-admin user.
I'll be glad to know what misunderstanding I have here, cause
something here doesn't sound right.
|
2011/06/11
|
['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']
|
Why you're asked for a password
-------------------------------
Most software is designed to touch sensitive files, i.e. sensitive to the security of your private data or the systems integrity. This is why software installation is a potential risk and should be validated by a user who knows what he is doing. Even for open source Software you can not be sure that no bad code bits arrive with your percious new audio player until someone checked. And even then something could have been overlooked or packages could be manipulated on the way. Who knows what's hidden in the depth of the program? One user should.
Ubuntu provides a comfortable way of installing software. Software developers can rely on that comfort and make the assumption that synaptic/software center/apt enables them to access these sensitive files. Canonical checks the software repository for bugs and malicious code. But the ultimate responsibility is yours.
If the software in question does not need access to sensitive files, it can (in principle) be installed in the home folder though not in the Ubuntu way. You will for instance have to compile the source code yourself or run a custom install script. Beside the greater efforts of that it has the disadvantage of not allowing other users access to your just installed program (as they have no right to access your home-folder). They will need to installed it a second time. So this way of installation makes no sense in a large scale and in a small scale it's usually easier to type a password than to install software manually.
So that's why Synaptic aaks for a password and why it's good that it does.
---
Sudoers
-------
**If you are really in dire need of having other users install software without password**, you can add them to the sudoers list. This however will result in **a great security risk**. If that doesn't concern you, consider that there a bot networks out there with great resources to break into your computer via Internet. They do this just to add your computer to the net and use it's connection and computing power without your knowledge to do all sorts of illegal stuff. They are not even after your personal data your you for that matter. They just want to hijack your PC. Still not concerned? Really? Then look at the following answer which is a small how-to on the workings of sudoers list:
[How to make Ubuntu remember forever the password after the first time](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)
Read that carefully. You could lock yourself out of the system.
### The scare is over
So now you have the scare behind you are and taking the matter seriously, I can tell you it's really not that bad. If you trust the people working on your computer, and you don't have programs installed that allow remote access to your system (e.g. an ssh- or ftp-server), then it's really not that dangerous to disable the password stuff. Just don't do it without considering the worst case and think of your private data.
---
Overlook on the proceedings (**don't do this lightly** - see text and [link above](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)):
```
# in shell type these commands
sudo su # in case you do something stupid, you'll have a root shell open
select-editor # (optional) will allow you to select text editor
visudo # secure way to open sudoers list
```
An editor will open ADD a line like this:
```
confus confusion=(root) NOPASSWD:/usr/sbin/synaptic,/usr/bin/software-center
```
Syntax explanation: `username machine=(usernameToRunCommandAs) command1,command2,...`. So the above line allows confus to run synaptic and softwarecenter as root without password query. You will still need to start it with `sudo synaptic` or `gksudo synaptic` or put an alias `alias synaptic='sudo synaptic' in your shell profile.
|
They can not. Here is the deal.
1. The 1st user created in Ubuntu is considered a special user: this is a user with administration permissions. This means when ever this user wants to do admin tasks he will be prompted for his admin password. Those tasks are issued by putting `sudo` in front of a command.
2. All other users (unless you change it yourself) are normal users and can not install sofware system wide unless the admin (1st user) lets them do so.
Normal user can only put things in their own home and if they want to they can mess up their home directory.
This way 1 person is responsible for the system.
You could make more than 1 user an admin (so able to install software) by adding those users to the sudoers file.
Besides that they can install software in their home but this does depend on the software: sometimes the installer wants to add it to the system and that is not allowed.
These installs tend to be from source so it is not the easiest method ;)
|
48,243 |
This is probably something I don't understand since I am used to Windows
and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software.
I mean, every application is run by a specific user, and that user will
only be able to run that applciation with his privilages, so if he has
no admin privileges, the application also won't be able to access unauthorized
directories etc.
I want most of the time to work on my PC with a non-admin user since it seems
more safe to me, most of the time I have no need for admin privileges.
and even though I know viruses in linux are uncommon I still think the best
practice is to work on the computer in a state that you yourself can't
make any changes to important files, that way viruses also can't harm any important
files, but I need to install software for programming and web-design etc.
and first of all I don't want to switch users all the time.
But also it sounds safer to me that everything being done on the PC
will be done through the non-admin user.
I'll be glad to know what misunderstanding I have here, cause
something here doesn't sound right.
|
2011/06/11
|
['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']
|
Why you're asked for a password
-------------------------------
Most software is designed to touch sensitive files, i.e. sensitive to the security of your private data or the systems integrity. This is why software installation is a potential risk and should be validated by a user who knows what he is doing. Even for open source Software you can not be sure that no bad code bits arrive with your percious new audio player until someone checked. And even then something could have been overlooked or packages could be manipulated on the way. Who knows what's hidden in the depth of the program? One user should.
Ubuntu provides a comfortable way of installing software. Software developers can rely on that comfort and make the assumption that synaptic/software center/apt enables them to access these sensitive files. Canonical checks the software repository for bugs and malicious code. But the ultimate responsibility is yours.
If the software in question does not need access to sensitive files, it can (in principle) be installed in the home folder though not in the Ubuntu way. You will for instance have to compile the source code yourself or run a custom install script. Beside the greater efforts of that it has the disadvantage of not allowing other users access to your just installed program (as they have no right to access your home-folder). They will need to installed it a second time. So this way of installation makes no sense in a large scale and in a small scale it's usually easier to type a password than to install software manually.
So that's why Synaptic aaks for a password and why it's good that it does.
---
Sudoers
-------
**If you are really in dire need of having other users install software without password**, you can add them to the sudoers list. This however will result in **a great security risk**. If that doesn't concern you, consider that there a bot networks out there with great resources to break into your computer via Internet. They do this just to add your computer to the net and use it's connection and computing power without your knowledge to do all sorts of illegal stuff. They are not even after your personal data your you for that matter. They just want to hijack your PC. Still not concerned? Really? Then look at the following answer which is a small how-to on the workings of sudoers list:
[How to make Ubuntu remember forever the password after the first time](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)
Read that carefully. You could lock yourself out of the system.
### The scare is over
So now you have the scare behind you are and taking the matter seriously, I can tell you it's really not that bad. If you trust the people working on your computer, and you don't have programs installed that allow remote access to your system (e.g. an ssh- or ftp-server), then it's really not that dangerous to disable the password stuff. Just don't do it without considering the worst case and think of your private data.
---
Overlook on the proceedings (**don't do this lightly** - see text and [link above](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)):
```
# in shell type these commands
sudo su # in case you do something stupid, you'll have a root shell open
select-editor # (optional) will allow you to select text editor
visudo # secure way to open sudoers list
```
An editor will open ADD a line like this:
```
confus confusion=(root) NOPASSWD:/usr/sbin/synaptic,/usr/bin/software-center
```
Syntax explanation: `username machine=(usernameToRunCommandAs) command1,command2,...`. So the above line allows confus to run synaptic and softwarecenter as root without password query. You will still need to start it with `sudo synaptic` or `gksudo synaptic` or put an alias `alias synaptic='sudo synaptic' in your shell profile.
|
You can install software as a regular, non-admin, user. Software installed by a regular user will be "owned" by that user, which means that, in effect, it is an extension of the user -- it has no more permissions than the owning user does, though it may have fewer permissions, at the user's option.
A common practice is for a user to create a 'bin' directory within their home directory. If /home/[user]/bin exists, it is added to the beginning of that user's path. You can place executable files in /home/[user]/bin, or in any other folder to which you have write and execute access, and execute the program from there.
What a regular user can't do is install a package system-wide. A regular user can't put executable files in /usr/bin, for instance, nor grant them permissions that exceed the user's own permissions. This is, obviously, for basic security reasons -- you need admin permissions to reformat a hard drive, for instance, and you don't want someone unauthorized doing that.
As far as I know, you cannot use package management software to install a software package unless you have admin permissions, as package management is done system-wide.
However, without admin permissions, you can create shell scripts, write and compile source code, download and compile "tarballs", which are packages of source code for complex applications, or download executable files, so long as these can be used with only the permissions of a regular user. Some indie games, such as World of Goo or X-Plane 9, can be installed and used in this way.
|
48,243 |
This is probably something I don't understand since I am used to Windows
and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software.
I mean, every application is run by a specific user, and that user will
only be able to run that applciation with his privilages, so if he has
no admin privileges, the application also won't be able to access unauthorized
directories etc.
I want most of the time to work on my PC with a non-admin user since it seems
more safe to me, most of the time I have no need for admin privileges.
and even though I know viruses in linux are uncommon I still think the best
practice is to work on the computer in a state that you yourself can't
make any changes to important files, that way viruses also can't harm any important
files, but I need to install software for programming and web-design etc.
and first of all I don't want to switch users all the time.
But also it sounds safer to me that everything being done on the PC
will be done through the non-admin user.
I'll be glad to know what misunderstanding I have here, cause
something here doesn't sound right.
|
2011/06/11
|
['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']
|
They can not. Here is the deal.
1. The 1st user created in Ubuntu is considered a special user: this is a user with administration permissions. This means when ever this user wants to do admin tasks he will be prompted for his admin password. Those tasks are issued by putting `sudo` in front of a command.
2. All other users (unless you change it yourself) are normal users and can not install sofware system wide unless the admin (1st user) lets them do so.
Normal user can only put things in their own home and if they want to they can mess up their home directory.
This way 1 person is responsible for the system.
You could make more than 1 user an admin (so able to install software) by adding those users to the sudoers file.
Besides that they can install software in their home but this does depend on the software: sometimes the installer wants to add it to the system and that is not allowed.
These installs tend to be from source so it is not the easiest method ;)
|
You can install software as a regular, non-admin, user. Software installed by a regular user will be "owned" by that user, which means that, in effect, it is an extension of the user -- it has no more permissions than the owning user does, though it may have fewer permissions, at the user's option.
A common practice is for a user to create a 'bin' directory within their home directory. If /home/[user]/bin exists, it is added to the beginning of that user's path. You can place executable files in /home/[user]/bin, or in any other folder to which you have write and execute access, and execute the program from there.
What a regular user can't do is install a package system-wide. A regular user can't put executable files in /usr/bin, for instance, nor grant them permissions that exceed the user's own permissions. This is, obviously, for basic security reasons -- you need admin permissions to reformat a hard drive, for instance, and you don't want someone unauthorized doing that.
As far as I know, you cannot use package management software to install a software package unless you have admin permissions, as package management is done system-wide.
However, without admin permissions, you can create shell scripts, write and compile source code, download and compile "tarballs", which are packages of source code for complex applications, or download executable files, so long as these can be used with only the permissions of a regular user. Some indie games, such as World of Goo or X-Plane 9, can be installed and used in this way.
|
48,243 |
This is probably something I don't understand since I am used to Windows
and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software.
I mean, every application is run by a specific user, and that user will
only be able to run that applciation with his privilages, so if he has
no admin privileges, the application also won't be able to access unauthorized
directories etc.
I want most of the time to work on my PC with a non-admin user since it seems
more safe to me, most of the time I have no need for admin privileges.
and even though I know viruses in linux are uncommon I still think the best
practice is to work on the computer in a state that you yourself can't
make any changes to important files, that way viruses also can't harm any important
files, but I need to install software for programming and web-design etc.
and first of all I don't want to switch users all the time.
But also it sounds safer to me that everything being done on the PC
will be done through the non-admin user.
I'll be glad to know what misunderstanding I have here, cause
something here doesn't sound right.
|
2011/06/11
|
['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']
|
Why you're asked for a password
-------------------------------
Most software is designed to touch sensitive files, i.e. sensitive to the security of your private data or the systems integrity. This is why software installation is a potential risk and should be validated by a user who knows what he is doing. Even for open source Software you can not be sure that no bad code bits arrive with your percious new audio player until someone checked. And even then something could have been overlooked or packages could be manipulated on the way. Who knows what's hidden in the depth of the program? One user should.
Ubuntu provides a comfortable way of installing software. Software developers can rely on that comfort and make the assumption that synaptic/software center/apt enables them to access these sensitive files. Canonical checks the software repository for bugs and malicious code. But the ultimate responsibility is yours.
If the software in question does not need access to sensitive files, it can (in principle) be installed in the home folder though not in the Ubuntu way. You will for instance have to compile the source code yourself or run a custom install script. Beside the greater efforts of that it has the disadvantage of not allowing other users access to your just installed program (as they have no right to access your home-folder). They will need to installed it a second time. So this way of installation makes no sense in a large scale and in a small scale it's usually easier to type a password than to install software manually.
So that's why Synaptic aaks for a password and why it's good that it does.
---
Sudoers
-------
**If you are really in dire need of having other users install software without password**, you can add them to the sudoers list. This however will result in **a great security risk**. If that doesn't concern you, consider that there a bot networks out there with great resources to break into your computer via Internet. They do this just to add your computer to the net and use it's connection and computing power without your knowledge to do all sorts of illegal stuff. They are not even after your personal data your you for that matter. They just want to hijack your PC. Still not concerned? Really? Then look at the following answer which is a small how-to on the workings of sudoers list:
[How to make Ubuntu remember forever the password after the first time](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)
Read that carefully. You could lock yourself out of the system.
### The scare is over
So now you have the scare behind you are and taking the matter seriously, I can tell you it's really not that bad. If you trust the people working on your computer, and you don't have programs installed that allow remote access to your system (e.g. an ssh- or ftp-server), then it's really not that dangerous to disable the password stuff. Just don't do it without considering the worst case and think of your private data.
---
Overlook on the proceedings (**don't do this lightly** - see text and [link above](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)):
```
# in shell type these commands
sudo su # in case you do something stupid, you'll have a root shell open
select-editor # (optional) will allow you to select text editor
visudo # secure way to open sudoers list
```
An editor will open ADD a line like this:
```
confus confusion=(root) NOPASSWD:/usr/sbin/synaptic,/usr/bin/software-center
```
Syntax explanation: `username machine=(usernameToRunCommandAs) command1,command2,...`. So the above line allows confus to run synaptic and softwarecenter as root without password query. You will still need to start it with `sudo synaptic` or `gksudo synaptic` or put an alias `alias synaptic='sudo synaptic' in your shell profile.
|
Non-admin users cannot install software because the packages run as root when they're installing as they install to privileged parts of the system, run maintainer scripts, etc.
There is currently no way to tell the system "Install firefox from this .deb but in a user's home directory so that it's isolated from the rest of the system"; which is why currently it's mostly an all or nothing affair. (This is also why running third party .debs is bad, the package and it's included scripts have root access to your system)
|
48,243 |
This is probably something I don't understand since I am used to Windows
and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software.
I mean, every application is run by a specific user, and that user will
only be able to run that applciation with his privilages, so if he has
no admin privileges, the application also won't be able to access unauthorized
directories etc.
I want most of the time to work on my PC with a non-admin user since it seems
more safe to me, most of the time I have no need for admin privileges.
and even though I know viruses in linux are uncommon I still think the best
practice is to work on the computer in a state that you yourself can't
make any changes to important files, that way viruses also can't harm any important
files, but I need to install software for programming and web-design etc.
and first of all I don't want to switch users all the time.
But also it sounds safer to me that everything being done on the PC
will be done through the non-admin user.
I'll be glad to know what misunderstanding I have here, cause
something here doesn't sound right.
|
2011/06/11
|
['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']
|
Non-admin users cannot install software because the packages run as root when they're installing as they install to privileged parts of the system, run maintainer scripts, etc.
There is currently no way to tell the system "Install firefox from this .deb but in a user's home directory so that it's isolated from the rest of the system"; which is why currently it's mostly an all or nothing affair. (This is also why running third party .debs is bad, the package and it's included scripts have root access to your system)
|
You touched upon a BIG difference between windows and ubuntu. In Windows when you are logged in as an admin programms will be installed without asking for a password. This enables also malware to run their programs. In Ubuntu (Linux) even being logged in as an admin the system will always ask for your password when you change the system. Therefore, malware cant intrude your system easily. To sum up run Ubuntu as an admin. If you open another user account for your kids than give them only normal user rights so they cant screw up the system.
|
48,243 |
This is probably something I don't understand since I am used to Windows
and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software.
I mean, every application is run by a specific user, and that user will
only be able to run that applciation with his privilages, so if he has
no admin privileges, the application also won't be able to access unauthorized
directories etc.
I want most of the time to work on my PC with a non-admin user since it seems
more safe to me, most of the time I have no need for admin privileges.
and even though I know viruses in linux are uncommon I still think the best
practice is to work on the computer in a state that you yourself can't
make any changes to important files, that way viruses also can't harm any important
files, but I need to install software for programming and web-design etc.
and first of all I don't want to switch users all the time.
But also it sounds safer to me that everything being done on the PC
will be done through the non-admin user.
I'll be glad to know what misunderstanding I have here, cause
something here doesn't sound right.
|
2011/06/11
|
['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']
|
In Ubuntu, the administrator has root privileges (often referred as just "root", as in "you need to be root").
Access to files can be split in three types:
* read (numeric value 4)
* write (numeric value 2)
* execute (numeric value 1)
These attributes can be set on every file or directory. Furthermore, these restrictions can be set on:
* the owner of the file
* the group of the file (users can be a member of this group)
* all other users which are not the owner nor in the group
These principles forms the basics of Linux file permissions. In windows, everything can be executed. Give it an `.cmd` or `.exe` extension for example. In Ubuntu, you need to add the execute bit explicitly, otherwise a permission error will be raised.
When an user executes a program, the program accesses files as that user and these file permissions kicks in. By default, locations where programs are installed are privileged, only the owner can write. This owner is root. All other users can only read and execute the program, not write to it. That's why you need root privileges to install programs.
Ubuntu has a special program called `sudo` (SuperUser DO ...) to run programs with root privileges. This can be used for installing software. When run, the `sudo` program asks you for your user password. Note that only members of the `admin` group can run programs as root using `sudo`.
In Windows, you would go to a website and download an installer. Ubuntu works with a software repository in which you can search for programs and install those. These programs are reviewed before added to the official repositories, so you can be sure that no harmful intentions exist in the programs.
|
You touched upon a BIG difference between windows and ubuntu. In Windows when you are logged in as an admin programms will be installed without asking for a password. This enables also malware to run their programs. In Ubuntu (Linux) even being logged in as an admin the system will always ask for your password when you change the system. Therefore, malware cant intrude your system easily. To sum up run Ubuntu as an admin. If you open another user account for your kids than give them only normal user rights so they cant screw up the system.
|
22,202,342 |
I have a calendar function, where I would like to call a column from my MySQL database. Before I am making the call for the column, I would just like to check if there is connection at all. My call goes through the servlet dataExchange.java. This servlet works fine, and I can put in information from my JSP page. In my database the format for the date is yyy-dd-mm. Therefore I have changed my JQuery calendar to have that format. That works fine and I get the alert box with the correct format, so it is the same as MySQL database. But I don't get the alert box, that the load was performed. Can anybody see why I don't get this call?
Best Regards
Mads
```
<form>
<input id="start" />
</form>
<script>
$(function(){
$("#start").datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(dateText,inst){
alert(dateText);
$.get("dataExchange.java", {start: $("#start").val()},
function( data ) {
alert("Load was performed");
});
}
});
});
</script>
```
|
2014/03/05
|
['https://Stackoverflow.com/questions/22202342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1883095/']
|
You are trying to call your java class directcly `$.get("dataExchange.java" ...` You must use your URL mapping for the servlet. You can map the servlet in the `web.xml` file or with annotations.
If you put your servlet an web.xml we can provide more help.
|
Answer:
```
$(function(){
$("#start").datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function(dateText,inst){
alert(dateText);
//Her skal du så lave din ajax kald:
$.ajax({
url: "../dataExchange",
type: "post",
data: Date,
success: function(){
alert("success");
$("#result").html('submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
}
});
});
```
|
34,315,485 |
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?
Update
------
The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).
**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.**
Example
-------
I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.
The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app.
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
tags$a(href = "#tab-4527-2")
})
}
shinyApp(ui, server)
```
|
2015/12/16
|
['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']
|
The following solution is based on the inputs I got from the comments.
Note that `updateTabsetPanel()` belongs to `shiny` while `updateTabItems()` is a function of the `shinydashboard` package. They seem to work interchangeably.
```
library(shiny)
library(shinydashboard)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
id = "panels",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2"),
actionLink("link_to_tabpanel_a", "Link to panel A")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
# observeEvent(input$link_to_tabpanel_b, {
# tags$a(href = "#tab-4527-2")
# })
observeEvent(input$link_to_tabpanel_b, {
newvalue <- "B"
updateTabItems(session, "panels", newvalue)
})
observeEvent(input$link_to_tabpanel_a, {
newvalue <- "A"
updateTabsetPanel(session, "panels", newvalue)
})
}
shinyApp(ui, server)
```
|
According to the code and logic from Rappster. It is possible to set any kind of links. Link to `TabsetPanel` can be used by `updataTabsetPanel`. Link to `Navbar` can use `updateNavbarPage(session, inputId, selected = NULL)`. These can be found by `?updateTabsetPanel` as following.
```
updateTabsetPanel(session, inputId, selected = NULL)
updateNavbarPage(session, inputId, selected = NULL)
updateNavlistPanel(session, inputId, selected = NULL)
```
Please notice `selected` is the new id that you can define for `tabsetPanel`, `Navbar`, or `NavlistPanel`.
|
34,315,485 |
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?
Update
------
The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).
**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.**
Example
-------
I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.
The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app.
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
tags$a(href = "#tab-4527-2")
})
}
shinyApp(ui, server)
```
|
2015/12/16
|
['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']
|
The following solution is based on the inputs I got from the comments.
Note that `updateTabsetPanel()` belongs to `shiny` while `updateTabItems()` is a function of the `shinydashboard` package. They seem to work interchangeably.
```
library(shiny)
library(shinydashboard)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
id = "panels",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2"),
actionLink("link_to_tabpanel_a", "Link to panel A")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
# observeEvent(input$link_to_tabpanel_b, {
# tags$a(href = "#tab-4527-2")
# })
observeEvent(input$link_to_tabpanel_b, {
newvalue <- "B"
updateTabItems(session, "panels", newvalue)
})
observeEvent(input$link_to_tabpanel_a, {
newvalue <- "A"
updateTabsetPanel(session, "panels", newvalue)
})
}
shinyApp(ui, server)
```
|
We have just released a [routing library](https://github.com/Appsilon/shiny.router), which makes linking in Shiny easy. Here's how it looks like in a nutshell.
```
make_router(
route("<your_app_url>/main", main_page_shiny_ui),
route("<your_app_url>/other", other_page_shiny_ui)
)
```
More information can be found in this [blog post](http://blog.appsilondatascience.com/rstats/2016/12/08/shiny.router.html).
|
34,315,485 |
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?
Update
------
The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).
**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.**
Example
-------
I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.
The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app.
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
tags$a(href = "#tab-4527-2")
})
}
shinyApp(ui, server)
```
|
2015/12/16
|
['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']
|
The following solution is based on the inputs I got from the comments.
Note that `updateTabsetPanel()` belongs to `shiny` while `updateTabItems()` is a function of the `shinydashboard` package. They seem to work interchangeably.
```
library(shiny)
library(shinydashboard)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
id = "panels",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2"),
actionLink("link_to_tabpanel_a", "Link to panel A")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
# observeEvent(input$link_to_tabpanel_b, {
# tags$a(href = "#tab-4527-2")
# })
observeEvent(input$link_to_tabpanel_b, {
newvalue <- "B"
updateTabItems(session, "panels", newvalue)
})
observeEvent(input$link_to_tabpanel_a, {
newvalue <- "A"
updateTabsetPanel(session, "panels", newvalue)
})
}
shinyApp(ui, server)
```
|
You can give your `tabsetPanel` an id and use `updateTabsetPanel` with your `observeEvent`
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(id = "demo",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
updateTabsetPanel(session, "demo", "B")
})
}
shinyApp(ui, server)
```
|
34,315,485 |
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?
Update
------
The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).
**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.**
Example
-------
I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.
The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app.
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
tags$a(href = "#tab-4527-2")
})
}
shinyApp(ui, server)
```
|
2015/12/16
|
['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']
|
The following solution is based on the inputs I got from the comments.
Note that `updateTabsetPanel()` belongs to `shiny` while `updateTabItems()` is a function of the `shinydashboard` package. They seem to work interchangeably.
```
library(shiny)
library(shinydashboard)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
id = "panels",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2"),
actionLink("link_to_tabpanel_a", "Link to panel A")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
# observeEvent(input$link_to_tabpanel_b, {
# tags$a(href = "#tab-4527-2")
# })
observeEvent(input$link_to_tabpanel_b, {
newvalue <- "B"
updateTabItems(session, "panels", newvalue)
})
observeEvent(input$link_to_tabpanel_a, {
newvalue <- "A"
updateTabsetPanel(session, "panels", newvalue)
})
}
shinyApp(ui, server)
```
|
I was struggling with the same issue and really wanted to link to a different tab **via the URL**. Thanks to the [simple example of thesadie](https://stackoverflow.com/a/43125357/7061057) and by using an *observe* to parse inputs from the url, for me the following worked (and made it possible to switch the tab by adding */?tab=B* to the URL, e.g. http://localhost:1234/?tab=B):
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(id = "demo",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
# Allow url parsing
observe({
query <- parseQueryString(session$clientData$url_search)
if (!is.null(query)) {
for (name in names(query)) {
if (name == "tab") {
# Change tab
try(updateTabsetPanel(session, "demo", selected = query[[name]]))
} else {
# Update inputs - this part is not really necessary if you just want to change the tabs,
# but I also needed to update other inputs from the url
try(updateTextInput(session, name, value = query[[name]]), silent = TRUE)
}
}
}
})
observeEvent(input$link_to_tabpanel_b, {
updateTabsetPanel(session, "demo", "B")
})
}
shinyApp(ui, server)
```
|
34,315,485 |
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?
Update
------
The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).
**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.**
Example
-------
I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.
The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app.
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
tags$a(href = "#tab-4527-2")
})
}
shinyApp(ui, server)
```
|
2015/12/16
|
['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']
|
We have just released a [routing library](https://github.com/Appsilon/shiny.router), which makes linking in Shiny easy. Here's how it looks like in a nutshell.
```
make_router(
route("<your_app_url>/main", main_page_shiny_ui),
route("<your_app_url>/other", other_page_shiny_ui)
)
```
More information can be found in this [blog post](http://blog.appsilondatascience.com/rstats/2016/12/08/shiny.router.html).
|
According to the code and logic from Rappster. It is possible to set any kind of links. Link to `TabsetPanel` can be used by `updataTabsetPanel`. Link to `Navbar` can use `updateNavbarPage(session, inputId, selected = NULL)`. These can be found by `?updateTabsetPanel` as following.
```
updateTabsetPanel(session, inputId, selected = NULL)
updateNavbarPage(session, inputId, selected = NULL)
updateNavlistPanel(session, inputId, selected = NULL)
```
Please notice `selected` is the new id that you can define for `tabsetPanel`, `Navbar`, or `NavlistPanel`.
|
34,315,485 |
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?
Update
------
The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).
**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.**
Example
-------
I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.
The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app.
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
tags$a(href = "#tab-4527-2")
})
}
shinyApp(ui, server)
```
|
2015/12/16
|
['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']
|
You can give your `tabsetPanel` an id and use `updateTabsetPanel` with your `observeEvent`
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(id = "demo",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
updateTabsetPanel(session, "demo", "B")
})
}
shinyApp(ui, server)
```
|
According to the code and logic from Rappster. It is possible to set any kind of links. Link to `TabsetPanel` can be used by `updataTabsetPanel`. Link to `Navbar` can use `updateNavbarPage(session, inputId, selected = NULL)`. These can be found by `?updateTabsetPanel` as following.
```
updateTabsetPanel(session, inputId, selected = NULL)
updateNavbarPage(session, inputId, selected = NULL)
updateNavlistPanel(session, inputId, selected = NULL)
```
Please notice `selected` is the new id that you can define for `tabsetPanel`, `Navbar`, or `NavlistPanel`.
|
34,315,485 |
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?
Update
------
The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).
**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.**
Example
-------
I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.
The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app.
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
tags$a(href = "#tab-4527-2")
})
}
shinyApp(ui, server)
```
|
2015/12/16
|
['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']
|
I was struggling with the same issue and really wanted to link to a different tab **via the URL**. Thanks to the [simple example of thesadie](https://stackoverflow.com/a/43125357/7061057) and by using an *observe* to parse inputs from the url, for me the following worked (and made it possible to switch the tab by adding */?tab=B* to the URL, e.g. http://localhost:1234/?tab=B):
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(id = "demo",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
# Allow url parsing
observe({
query <- parseQueryString(session$clientData$url_search)
if (!is.null(query)) {
for (name in names(query)) {
if (name == "tab") {
# Change tab
try(updateTabsetPanel(session, "demo", selected = query[[name]]))
} else {
# Update inputs - this part is not really necessary if you just want to change the tabs,
# but I also needed to update other inputs from the url
try(updateTextInput(session, name, value = query[[name]]), silent = TRUE)
}
}
}
})
observeEvent(input$link_to_tabpanel_b, {
updateTabsetPanel(session, "demo", "B")
})
}
shinyApp(ui, server)
```
|
According to the code and logic from Rappster. It is possible to set any kind of links. Link to `TabsetPanel` can be used by `updataTabsetPanel`. Link to `Navbar` can use `updateNavbarPage(session, inputId, selected = NULL)`. These can be found by `?updateTabsetPanel` as following.
```
updateTabsetPanel(session, inputId, selected = NULL)
updateNavbarPage(session, inputId, selected = NULL)
updateNavlistPanel(session, inputId, selected = NULL)
```
Please notice `selected` is the new id that you can define for `tabsetPanel`, `Navbar`, or `NavlistPanel`.
|
34,315,485 |
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?
Update
------
The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).
**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.**
Example
-------
I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.
The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app.
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
tags$a(href = "#tab-4527-2")
})
}
shinyApp(ui, server)
```
|
2015/12/16
|
['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']
|
We have just released a [routing library](https://github.com/Appsilon/shiny.router), which makes linking in Shiny easy. Here's how it looks like in a nutshell.
```
make_router(
route("<your_app_url>/main", main_page_shiny_ui),
route("<your_app_url>/other", other_page_shiny_ui)
)
```
More information can be found in this [blog post](http://blog.appsilondatascience.com/rstats/2016/12/08/shiny.router.html).
|
I was struggling with the same issue and really wanted to link to a different tab **via the URL**. Thanks to the [simple example of thesadie](https://stackoverflow.com/a/43125357/7061057) and by using an *observe* to parse inputs from the url, for me the following worked (and made it possible to switch the tab by adding */?tab=B* to the URL, e.g. http://localhost:1234/?tab=B):
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(id = "demo",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
# Allow url parsing
observe({
query <- parseQueryString(session$clientData$url_search)
if (!is.null(query)) {
for (name in names(query)) {
if (name == "tab") {
# Change tab
try(updateTabsetPanel(session, "demo", selected = query[[name]]))
} else {
# Update inputs - this part is not really necessary if you just want to change the tabs,
# but I also needed to update other inputs from the url
try(updateTextInput(session, name, value = query[[name]]), silent = TRUE)
}
}
}
})
observeEvent(input$link_to_tabpanel_b, {
updateTabsetPanel(session, "demo", "B")
})
}
shinyApp(ui, server)
```
|
34,315,485 |
How do I manage to link from a given shiny part to parts that are located on other tabs/panels?
Update
------
The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for).
**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.**
Example
-------
I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked.
The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app.
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
tags$a(href = "#tab-4527-2")
})
}
shinyApp(ui, server)
```
|
2015/12/16
|
['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']
|
You can give your `tabsetPanel` an id and use `updateTabsetPanel` with your `observeEvent`
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(id = "demo",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$link_to_tabpanel_b, {
updateTabsetPanel(session, "demo", "B")
})
}
shinyApp(ui, server)
```
|
I was struggling with the same issue and really wanted to link to a different tab **via the URL**. Thanks to the [simple example of thesadie](https://stackoverflow.com/a/43125357/7061057) and by using an *observe* to parse inputs from the url, for me the following worked (and made it possible to switch the tab by adding */?tab=B* to the URL, e.g. http://localhost:1234/?tab=B):
```
library(shiny)
# UI ---------------------------------------------------------------------
ui <- fluidPage(
tabsetPanel(id = "demo",
tabPanel(
"A",
p(),
actionLink("link_to_tabpanel_b", "Link to panel B")
),
tabPanel(
"B",
h3("Some information"),
tags$li("Item 1"),
tags$li("Item 2")
)
)
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
# Allow url parsing
observe({
query <- parseQueryString(session$clientData$url_search)
if (!is.null(query)) {
for (name in names(query)) {
if (name == "tab") {
# Change tab
try(updateTabsetPanel(session, "demo", selected = query[[name]]))
} else {
# Update inputs - this part is not really necessary if you just want to change the tabs,
# but I also needed to update other inputs from the url
try(updateTextInput(session, name, value = query[[name]]), silent = TRUE)
}
}
}
})
observeEvent(input$link_to_tabpanel_b, {
updateTabsetPanel(session, "demo", "B")
})
}
shinyApp(ui, server)
```
|
454,341 |
I built a computer for a friend with an OCZ petrol SSD. It seems to be having some problems now. Once or twice a day, it gets an error that looks like it's pointing to a disk sector and then blue screens. I booted off System Rescue CD to try and take a backup image of the disk, but it failed with an error along the lines of being unable to read a segment. The errors come totally at random, they don't seem to be associated with trying to read a certain file. The variance in uptime between faults is pretty large.
I'd like to update the drive firmware at some stage, but first I want to have a full disk backup just in case anything goes wrong (took me a long time to get the computer correctly configured in the first place!). What sort of tool will work to back up the disk, and is the problem likely to be solved by a firmware update or am I going to have to RMA the drive?
|
2012/07/27
|
['https://superuser.com/questions/454341', 'https://superuser.com', 'https://superuser.com/users/148667/']
|
According to [this article](http://alloytm.com/2010/01/05/virtualbox-regdb_e_classnotreg-error/), this can be fixed like so:
>
> 1. Open a standard command line ( Run > cmd )
> 2. Run: `cd C:\Program Files\Oracle\VirtualBox`
> 3. Run: `VBoxSVC /ReRegServer`
> 4. Run: `regsvr32 VBoxC.dll`
>
>
>
Make sure to run the Command Prompt as an Administrator.
But I find it confusing that this happens directly after installation. You may want to report this issue on the [VirtualBox Bugtracker](https://www.virtualbox.org/wiki/Bugtracker).
|
This error occurred with my win 7 64 bit too.
I came to a conclusion that this problem occurred due to installation of youwave for android on my pc.
They both have some conflicts so only any one can be installed at a time.
|
454,341 |
I built a computer for a friend with an OCZ petrol SSD. It seems to be having some problems now. Once or twice a day, it gets an error that looks like it's pointing to a disk sector and then blue screens. I booted off System Rescue CD to try and take a backup image of the disk, but it failed with an error along the lines of being unable to read a segment. The errors come totally at random, they don't seem to be associated with trying to read a certain file. The variance in uptime between faults is pretty large.
I'd like to update the drive firmware at some stage, but first I want to have a full disk backup just in case anything goes wrong (took me a long time to get the computer correctly configured in the first place!). What sort of tool will work to back up the disk, and is the problem likely to be solved by a firmware update or am I going to have to RMA the drive?
|
2012/07/27
|
['https://superuser.com/questions/454341', 'https://superuser.com', 'https://superuser.com/users/148667/']
|
According to [this article](http://alloytm.com/2010/01/05/virtualbox-regdb_e_classnotreg-error/), this can be fixed like so:
>
> 1. Open a standard command line ( Run > cmd )
> 2. Run: `cd C:\Program Files\Oracle\VirtualBox`
> 3. Run: `VBoxSVC /ReRegServer`
> 4. Run: `regsvr32 VBoxC.dll`
>
>
>
Make sure to run the Command Prompt as an Administrator.
But I find it confusing that this happens directly after installation. You may want to report this issue on the [VirtualBox Bugtracker](https://www.virtualbox.org/wiki/Bugtracker).
|
I have the same problem after de+reinstall VirtualBox.
Good hint, Oliver Salzburg! It didn't work for me under Win10, but brought me closer to the solution:
* Open start menu, right click on the `VirtualBox link`
* Click on `open file path` - explorer opens
* Right click on `VirtualBox link`, then `settings`
* Under `compatibility` click `settings for all users` button
* Check `execute program as administrator`
* ok-click all windows
'Strings' may vary due to translation.
Surprisingly (for me), `execute program as administrator` even makes a difference when using an admin account. This is also important for Oliver's solution (as I learned today after >15 years Windows experience.
|
454,341 |
I built a computer for a friend with an OCZ petrol SSD. It seems to be having some problems now. Once or twice a day, it gets an error that looks like it's pointing to a disk sector and then blue screens. I booted off System Rescue CD to try and take a backup image of the disk, but it failed with an error along the lines of being unable to read a segment. The errors come totally at random, they don't seem to be associated with trying to read a certain file. The variance in uptime between faults is pretty large.
I'd like to update the drive firmware at some stage, but first I want to have a full disk backup just in case anything goes wrong (took me a long time to get the computer correctly configured in the first place!). What sort of tool will work to back up the disk, and is the problem likely to be solved by a firmware update or am I going to have to RMA the drive?
|
2012/07/27
|
['https://superuser.com/questions/454341', 'https://superuser.com', 'https://superuser.com/users/148667/']
|
I have the same problem after de+reinstall VirtualBox.
Good hint, Oliver Salzburg! It didn't work for me under Win10, but brought me closer to the solution:
* Open start menu, right click on the `VirtualBox link`
* Click on `open file path` - explorer opens
* Right click on `VirtualBox link`, then `settings`
* Under `compatibility` click `settings for all users` button
* Check `execute program as administrator`
* ok-click all windows
'Strings' may vary due to translation.
Surprisingly (for me), `execute program as administrator` even makes a difference when using an admin account. This is also important for Oliver's solution (as I learned today after >15 years Windows experience.
|
This error occurred with my win 7 64 bit too.
I came to a conclusion that this problem occurred due to installation of youwave for android on my pc.
They both have some conflicts so only any one can be installed at a time.
|
14,160,928 |
I am trying to draw some Kaplan-Meier curves using **ggplot2** and code found at: <https://github.com/kmiddleton/rexamples/blob/master/qplot_survival.R>
I had good results with this great code in a different database. However, in this case it gives me the following error... as if I had empty rows in my dataframe:
`Error en if (nrow(layer_data) == 0) return() : argument is of length zero.`
Previous questions about this type of error don't seem to be useful for me, as types of data and functions are not the same in my case.
I am rather new to the statistical analysis using R and I don't have programming background, so I think this must be a 'dumb bug' in my data, but I can't found where it is… It definitely seems that ggplot2 can't find rows to plot. Please, could you help me in any way, with clues, suggestions.. etc?
Here are my data and the code used, sequentially, ready for the console -I tried it in a knitr script-. At the end, I've posted my sessionInfo:
```
library(splines)
library(survival)
library(abind)
library(ggplot2)
library(grid)
```
I create a data frame called **acbi30** (real data):
```
mort28day <- c(1,0,1,0,0,0,0,1,0,0,0,1,1,0,1,0,0,1,0,1,1,1,1,0,1,1,1,0,0,1)
daysurv <- c(4,29,24,29,29,29,29,19,29,29,29,3,9,29,15,29,29,11,29,5,13,20,22,29,16,21,9,29,29,15)
levo <- c(0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0)
acbi30 <- data.frame(mort28day, daysurv, levo)
save(acbi30, file="acbi30.rda")
acbi30
```
Then, I paste the following commands to create a function using ggplot2:
```
t.Surv <- Surv(acbi30$daysurv, acbi30$mort28day)
t.survfit <- survfit(t.Surv~1, data=acbi30)
#define custom function to create a survival data.frame#
createSurvivalFrame <- function(f.survfit){
#initialise frame variable#
f.frame <- NULL
#check if more then one strata#
if(length(names(f.survfit$strata)) == 0){
#create data.frame with data from survfit#
f.frame <- data.frame(time=f.survfit$time, n.risk=f.survfit$n.risk, n.event=f.survfit$n.event, n.censor = f.survfit
$n.censor, surv=f.survfit$surv, upper=f.survfit$upper, lower=f.survfit$lower)
#create first two rows (start at 1)#
f.start <- data.frame(time=c(0, f.frame$time[1]), n.risk=c(f.survfit$n, f.survfit$n), n.event=c(0,0),
n.censor=c(0,0), surv=c(1,1), upper=c(1,1), lower=c(1,1))
#add first row to dataset#
f.frame <- rbind(f.start, f.frame)
#remove temporary data#
rm(f.start)
}
else {
#create vector for strata identification#
f.strata <- NULL
for(f.i in 1:length(f.survfit$strata)){
#add vector for one strata according to number of rows of strata#
f.strata <- c(f.strata, rep(names(f.survfit$strata)[f.i], f.survfit$strata[f.i]))
}
#create data.frame with data from survfit (create column for strata)#
f.frame <- data.frame(time=f.survfit$time, n.risk=f.survfit$n.risk, n.event=f.survfit$n.event, n.censor = f.survfit
$n.censor, surv=f.survfit$surv, upper=f.survfit$upper, lower=f.survfit$lower, strata=factor(f.strata))
#remove temporary data#
rm(f.strata)
#create first two rows (start at 1) for each strata#
for(f.i in 1:length(f.survfit$strata)){
#take only subset for this strata from data#
f.subset <- subset(f.frame, strata==names(f.survfit$strata)[f.i])
#create first two rows (time: 0, time of first event)#
f.start <- data.frame(time=c(0, f.subset$time[1]), n.risk=rep(f.survfit[f.i]$n, 2), n.event=c(0,0),
n.censor=c(0,0), surv=c(1,1), upper=c(1,1), lower=c(1,1), strata=rep(names(f.survfit$strata)[f.i],
2))
#add first two rows to dataset#
f.frame <- rbind(f.start, f.frame)
#remove temporary data#
rm(f.start, f.subset)
}
#reorder data#
f.frame <- f.frame[order(f.frame$strata, f.frame$time), ]
#rename row.names#
rownames(f.frame) <- NULL
}
#return frame#
return(f.frame)
}
#define custom function to draw kaplan-meier curve with ggplot#
qplot_survival <- function(f.frame, f.CI="default", f.shape=3){
#use different plotting commands dependig whether or not strata's are given#
if("strata" %in% names(f.frame) == FALSE){
#confidence intervals are drawn if not specified otherwise#
if(f.CI=="default" | f.CI==TRUE ){
#create plot with 4 layers (first 3 layers only events, last layer only censored)#
#hint: censoring data for multiple censoring events at timepoint are overplotted#
#(unlike in plot.survfit in survival package)#
ggplot(data=f.frame) + geom_step(aes(x=time, y=surv), direction="hv") + geom_step(aes(x=time,
y=upper), directions="hv", linetype=2) + geom_step(aes(x=time,y=lower), direction="hv", linetype=2) +
geom_point(data=subset(f.frame, n.censor==1), aes(x=time, y=surv), shape=f.shape)
}
else {
#create plot without confidence intervals#
ggplot(data=f.frame) + geom_step(aes(x=time, y=surv), direction="hv") +
geom_point(data=subset(f.frame, n.censor==1), aes(x=time, y=surv), shape=f.shape)
}
}
else {
if(f.CI=="default" | f.CI==FALSE){
#without CI#
ggplot(data=f.frame, aes(group=strata, colour=strata)) + geom_step(aes(x=time, y=surv),
direction="hv") + geom_point(data=subset(f.frame, n.censor==1), aes(x=time, y=surv), shape=f.shape)
}
else {
#with CI (hint: use alpha for CI)#
ggplot(data=f.frame, aes(colour=strata, group=strata)) + geom_step(aes(x=time, y=surv),
direction="hv") + geom_step(aes(x=time, y=upper), directions="hv", linetype=2, alpha=0.5) +
geom_step(aes(x=time,y=lower), direction="hv", linetype=2, alpha=0.5) +
geom_point(data=subset(f.frame, n.censor==1), aes(x=time, y=surv), shape=f.shape)
}
}
}
```
**Plotting global survival curve (with 95% CI):**
It doesn't give any errors:
```
# Kaplan-Meier plot, global survival (with CI)
t.survfit <- survfit(t.Surv~1, data=acbi30)
t.survframe <- createSurvivalFrame(t.survfit)
t.survfit
qplot_survival(t.survframe, TRUE, 20)
```
**Plotting stratified survival curves:**
Gives the error above mentioned:
```
# Kaplan-Meier plot, stratified survival
t.survfit2 <- survfit(t.Surv~levo, data=acbi30)
t.survframe2 <- createSurvivalFrame(t.survfit2)
t.survfit2
qplot_survival(t.survframe2, TRUE, 20)
```
**Plotting the results without ggplot2:**
The structure of t.survframe2 seems OK to me, without any empty rows, so it must be a problem of qplot\_survival reading my data in *t.survframe2*. Making a simple plot doesn't return any error:
```
t.survframe2
plot(t.survfit2)
```
Where is the problem with my dataframe? The functions created work well with other datasets, but not with this one...
Thank you in advance,
Mareviv
**Session info:**
```
sessionInfo()
```
R version 2.15.2 (2012-10-26)
Platform: i386-w64-mingw32/i386 (32-bit)
```
locale:
[1] LC_COLLATE=Spanish_Spain.1252 LC_CTYPE=Spanish_Spain.1252
[3] LC_MONETARY=Spanish_Spain.1252 LC_NUMERIC=C
[5] LC_TIME=Spanish_Spain.1252
attached base packages:
[1] grid splines stats graphics grDevices utils datasets
[8] methods base
other attached packages:
[1] ggplot2_0.9.3 abind_1.4-0 survival_2.36-14 knitr_0.8
loaded via a namespace (and not attached):
[1] colorspace_1.1-1 dichromat_1.2-4 digest_0.5.2
[4] evaluate_0.4.2 formatR_0.7 gtable_0.1.2
[7] labeling_0.1 MASS_7.3-22 munsell_0.4
[10] plyr_1.8 proto_0.3-9.2 RColorBrewer_1.0-5
[13] reshape2_1.2.1 scales_0.2.3 stringr_0.6.1
[16] tools_2.15.2
```
|
2013/01/04
|
['https://Stackoverflow.com/questions/14160928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1948108/']
|
I did a little cosmetic surgery on your `qplot_survival()` function. The main problem seemed to be your subset condition in the `data =` argument of `geom_point`; in both `t.survframe` and `t.survframe2`, a table of `n.censor` yielded values 0, 3 and 12. By changing the subset condition to `n.censor > 0`, I managed to get a plot in all cases. I also didn't see the point of `f.CI = "default"`, so I set the default to TRUE and modified the if conditions accordingly.
```
qplot_survival <- function(f.frame, f.CI= TRUE, f.shape=3)
{
# use different plotting commands depending whether
# or not strata are given#
if(!("strata" %in% names(f.frame)))
{
#confidence intervals are drawn if not specified otherwise#
if( isTRUE(f.CI) )
{
# create plot with 4 layers (first 3 layers only events,
# last layer only censored)#
# hint: censoring data for multiple censoring events at
# timepoint are overplotted#
# (unlike in plot.survfit in survival package)#
ggplot(data=f.frame) +
geom_step(aes(x=time, y=surv), direction="hv") +
geom_step(aes(x=time, y=upper), direction ="hv", linetype=2) +
geom_step(aes(x=time,y=lower), direction="hv", linetype=2) +
geom_point(data=subset(f.frame, n.censor > 0),
aes(x=time, y=surv), shape=f.shape)
} else {
#create plot without confidence intervals#
ggplot(data=f.frame) +
geom_step(aes(x=time, y=surv), direction="hv") +
geom_point(data=subset(f.frame, n.censor > 0),
aes(x=time, y=surv), shape=f.shape)
}
} else {
if( !(isTRUE(f.CI)) ){
#without CI#
ggplot(data=f.frame, aes(group=strata, colour=strata)) +
geom_step(aes(x=time, y=surv), direction="hv") +
geom_point(data=subset(f.frame, n.censor > 0),
aes(x=time, y=surv), shape=f.shape)
} else {
#with CI (hint: use alpha for CI)#
ggplot(data=f.frame, aes(x = time, colour=strata, group=strata)) +
geom_step(aes(y=surv), direction="hv") +
geom_step(aes(y=upper), direction="hv",
linetype=2, alpha=0.5) +
geom_step(aes(y=lower), direction="hv",
linetype=2, alpha=0.5) +
geom_point(data=subset(f.frame, n.censor > 0),
aes(y=surv), shape=f.shape)
}
}
}
```
The following plots all worked for me after making these changes:
```
qplot_survival(t.survframe2, TRUE, 20)
qplot_survival(t.survframe2, FALSE, 20)
qplot_survival(t.survframe, TRUE, 20)
qplot_survival(t.survframe, FALSE, 20)
```
A couple of comments:
1. Subsetting inside a function can be dangerous because sometimes, as in this case, satisfying the condition returns a zero-row data frame. I'd consider whether or not the `geom_point()` layer is really necessary.
2. In a couple of places, you had `directions = "hv"` inside a `geom_step()` call. The argument is not pluralized and has been changed above.
3. This could be done a little more efficiently I think, but one way to extract the columns of interest from a `survfit` object, say `t.survfit`, is something like this:
(Expand comps when strata are present)
```
comps <- c(2:6, 8, 10);
t.fit <- as.data.frame(do.call(cbind, lapply(comps, function(j) t.survfit[[j]])))
names(t.fit) <- names(t.survfit)[comps]
```
|
Here is another version that also accounts for the case when there are no censoring points in your data (@Dennis's version still fails in that case). This could be made more efficient, probably by creating a variable that stores how many censoring points there are in the entire dataframe upfront, and re-use that, rather than testing like I do again in each case.
```
# define custom function to draw kaplan-meier curve with ggplot
qplot_survival <- function(f.frame, f.CI="default", f.shape=3){
# use different plotting commands dependig whether or not strata's are given
if("strata" %in% colnames(f.frame) == FALSE){
# confidence intervals are drawn if not specified otherwise
if(f.CI=="default" | f.CI==TRUE ){
# create plot with 4 layers (first 3 layers only events, last layer only censored)
# hint: censoring data for multiple censoring events at timepoint are overplotted
# (unlike in plot.survfit in survival package)
p <- ggplot(data=f.frame) + geom_step(aes(x=time, y=surv), direction="hv") + geom_step(aes(x=time,
y=upper), directions="hv", linetype=2) + geom_step(aes(x=time,y=lower), direction="hv", linetype=2)
if(nrow(subset(f.frame, n.censor > 0)) > 0){
p+geom_point(data=subset(f.frame, n.censor > 0), aes(x=time, y=surv), shape=f.shape)
}else{
p
}
}
else {
# create plot without confidence intervalls
p <- ggplot(data=f.frame) + geom_step(aes(x=time, y=surv), direction="hv")
if(nrow(subset(f.frame, n.censor > 0)) > 0){
p + geom_point(data=subset(f.frame, n.censor > 0), aes(x=time, y=surv), shape=f.shape)
}else{
p
}
}
}
else {
if(f.CI=="default" | f.CI==FALSE){
# without CI
p <- ggplot(data=f.frame, aes(group=strata, colour=strata)) + geom_step(aes(x=time, y=surv),
direction="hv")
if(nrow(subset(f.frame, n.censor > 0)) > 0){
p +geom_point(data=subset(f.frame, n.censor > 0), aes(x=time, y=surv), shape=f.shape)
}else{
p
}
}
else {
# with CI (hint: use alpha for CI)
p <- ggplot(data=f.frame, aes(colour=strata, group=strata)) + geom_step(aes(x=time, y=surv),
direction="hv") + geom_step(aes(x=time, y=upper), directions="hv", linetype=2, alpha=0.5) +
geom_step(aes(x=time,y=lower), direction="hv", linetype=2, alpha=0.5)
if(nrow(subset(f.frame, n.censor > 0)) > 0){
p + geom_point(data=subset(f.frame, n.censor > 0), aes(x=time, y=surv), shape=f.shape)
}else{
p
}
}
}
}
```
|
63,196,690 |
A Worker Service is the new way to write a Windows service in .NET Core 3.x. The worker class extends [`Microsoft.Extensions.Hosting.BackgroundService`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice?view=dotnet-plat-ext-3.1) and implements `ExecuteAsync`. The documentation for that method says:
>
> This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.
>
>
>
What should this method return when the work being done by the service is not a long-running operation in the usual sense, but event-driven? For example, I'm writing a service that sets up a [`FileSystemWatcher`](https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netcore-3.1). How would I encapsulate that in a `Task`? There's no `Task.Never()`, so should I just return something based on a very long `Task.Delay()` to prevent the service from shutting down?
```
private async Task DoStuffAsync(CancellationToken cancel)
{
// register events
while(!cancel.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromDays(1000000), cancel);
}
// unregister events
}
```
|
2020/07/31
|
['https://Stackoverflow.com/questions/63196690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8773089/']
|
You could also use an actual infinite delay:
```
await Task.Delay(Timeout.Infinite, cancellationToken);
```
|
I incorporated the delay into a method called `Eternity`:
```
private async Task Eternity(CancellationToken cancel)
{
while (!cancel.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromDays(1), cancel);
}
}
```
So my `ExecuteAsync` looks like:
```
protected override async Task ExecuteAsync(CancellationToken cancel)
{
using (var watcher = new FileSystemWatcher())
{
ConfigureWatcher(watcher);
await Eternity(cancel);
}
}
```
This seems to work as expected.
|
63,196,690 |
A Worker Service is the new way to write a Windows service in .NET Core 3.x. The worker class extends [`Microsoft.Extensions.Hosting.BackgroundService`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice?view=dotnet-plat-ext-3.1) and implements `ExecuteAsync`. The documentation for that method says:
>
> This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.
>
>
>
What should this method return when the work being done by the service is not a long-running operation in the usual sense, but event-driven? For example, I'm writing a service that sets up a [`FileSystemWatcher`](https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netcore-3.1). How would I encapsulate that in a `Task`? There's no `Task.Never()`, so should I just return something based on a very long `Task.Delay()` to prevent the service from shutting down?
```
private async Task DoStuffAsync(CancellationToken cancel)
{
// register events
while(!cancel.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromDays(1000000), cancel);
}
// unregister events
}
```
|
2020/07/31
|
['https://Stackoverflow.com/questions/63196690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8773089/']
|
You could also use an actual infinite delay:
```
await Task.Delay(Timeout.Infinite, cancellationToken);
```
|
If you want to call it like `await "Eternity"` or `await ("Eternity", token)` if you want cancellation support. We can use them with cancellation support thanks to value tuples.
Basically *you can await anything* with some extension methods.
Here is the code:
```
protected override async Task ExecuteAsync(CancellationToken token)
{
using (var watcher = new FileSystemWatcher())
{
ConfigureWatcher(watcher);
// Use any of these methods you'd like
await "Eternity";
await ("Eternity", token);
await TimeSpan.FromDays(1);
await (TimeSpan.FromDays(1), token);
}
}
public static class GetAwaiterExtensions
{
public static TaskAwaiter GetAwaiter(this (TimeSpan, CancellationToken) valueTuple)
{
return Task.Delay((int) valueTuple.Item1.TotalMilliseconds, valueTuple.Item2)
.GetAwaiter();
}
public static TaskAwaiter GetAwaiter(this TimeSpan timeSpan)
{
return Task.Delay((int) timeSpan.TotalMilliseconds)
.GetAwaiter();
}
public static TaskAwaiter GetAwaiter(this string value)
{
if (value == "Eternity")
{
return Task.Delay(Timeout.Infinite)
.GetAwaiter();
}
throw new ArgumentException();
}
public static TaskAwaiter GetAwaiter(this (string, CancellationToken) valueTuple)
{
if (valueTuple.Item1 == "Eternity")
{
return Task
.Delay(Timeout.Infinite, cancellationToken: valueTuple.Item2)
.GetAwaiter();
}
throw new ArgumentException();
}
}
```
|
23,298,393 |
I tried many various methods, but didn't work.. What's wrong with my code? Please explain... help. My both images is transparent, with my idea on mouseover shoud fade new image. Current my code:
[DEMO](http://jsbin.com/nipocete/1)
[DEMO2](http://jsbin.com/nipocete/1/edit)
```
<script type='text/javascript'>
$(document).ready(function(){
$("img.a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
});
});
</script>
<style>
div.fadehover
{
position: relative;
}
img.a
{
position: absolute;
left: 0;
top: 0;
z-index: 10;
}
img.b
{
position: absolute;
left: 0;
top: 0;
}
</style>
<div class="fadehover">
<a href="informacija.php"><img src="images/informacija.png" alt="Informacija" class="a"/></a>
<a href="informacija.php"><img src="images/informacija_hover.png" alt="Informacija" class="b"/></a>
</div>
```
|
2014/04/25
|
['https://Stackoverflow.com/questions/23298393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3573697/']
|
I believe to achieve your desired effect as I understand it you simply need to add a background to `img.a`. [Fiddle](http://jsfiddle.net/G8TB5/2/ "Fiddle")
```
img.a{
position: absolute;
left: 0;
top: 0;
z-index: 10;
background:#fff;
}
```
|
It seems to me you are doing the wrong thing. The img.b should have opacity 0 at :not(:hover) and opacity 1 at :hover, but all you are doing is setting the opacity of $(this) which is img.a
Here is my re-work... I didn't use hover because I get confused with the syntax
Here is my [fiddle/jsbin](http://jsbin.com/nipocete/14/edit)
**HTML**
```
<div class="fadehover">
<a href="#">
<img src="http://csrelax.lt/images/informacija.png" alt="Informacija" class="a"/>
</a>
<a href="#">
<img src="http://csrelax.lt/images/informacija_hover.png" alt="Informacija" class="b"/>
</a>
</div>
```
**CSS**
```
div.fadehover
{
position: relative;
}
img.a
{
position: absolute;
left: 0;
top: 0;
z-index: 10;
}
img.b
{
position: absolute;
left: 0;
top: 0;
opacity: 0;
}
```
**JS - using jQuery**
```
$(document).on('mouseenter', 'img.a', function() {
console.log('mouseenter');
$(this).parent().next().find('.b').animate({"opacity": "1"}, "slow");
});
$(document).on('mouseleave', 'img.a', function() {
console.log('mouseleave');
$(this).parent().next().find('.b').animate({"opacity": "0"}, "slow");
});
```
PS **ExceptionLimeCat** has found a very nice solution +1
|
23,298,393 |
I tried many various methods, but didn't work.. What's wrong with my code? Please explain... help. My both images is transparent, with my idea on mouseover shoud fade new image. Current my code:
[DEMO](http://jsbin.com/nipocete/1)
[DEMO2](http://jsbin.com/nipocete/1/edit)
```
<script type='text/javascript'>
$(document).ready(function(){
$("img.a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
});
});
</script>
<style>
div.fadehover
{
position: relative;
}
img.a
{
position: absolute;
left: 0;
top: 0;
z-index: 10;
}
img.b
{
position: absolute;
left: 0;
top: 0;
}
</style>
<div class="fadehover">
<a href="informacija.php"><img src="images/informacija.png" alt="Informacija" class="a"/></a>
<a href="informacija.php"><img src="images/informacija_hover.png" alt="Informacija" class="b"/></a>
</div>
```
|
2014/04/25
|
['https://Stackoverflow.com/questions/23298393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3573697/']
|
I believe to achieve your desired effect as I understand it you simply need to add a background to `img.a`. [Fiddle](http://jsfiddle.net/G8TB5/2/ "Fiddle")
```
img.a{
position: absolute;
left: 0;
top: 0;
z-index: 10;
background:#fff;
}
```
|
ExceptionLimeCat solutions good but only for in bright/shiny/white backgrounds.
Jaka Dirnbek way is better, because is more optimal.
Anyway.. Solved with this thing. But how this [Jaka Dirnbek](http://jsbin.com/nipocete/14/edit) jquery use on link? Example:
```
<div id="nav_virsus">
<ul>
<li><a href="#"><img src="images/pagrindinis.png" alt="Main" /></a></li>
<li><a href="#"><img src="images/forumas.png" alt="Forumas" /></a></li>
<li><a href="#"><img src="images/unban.png" alt="Atsibaninti" /></a></li>
<li><a href="#"><img src="images/banai.png" alt="Banai" /></a></li>
</ul>
</div>
```
CSS:
```
#nav_virsus {
position:absolute;
top:71px;
right:50px;
}
#nav_virsus li
{
font-family: 'Anaheim', sans-serif;
font-size:14px;
text-transform:uppercase;
float:left;
padding:20px;
}
#nav_virsus li a
{
color:#b8d9ff;
text-decoration:none;
padding:20px 5px 20px 5px;
}
#nav_virsus li a:hover
{
background:url(../images/hover.png) repeat-x;
color:#000;
text-decoration:none;
padding:21px 5px 20px 5px;
}
```
|
9,533,392 |
Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this:
```
const char* give()
{
return "Hello, World!";
}
```
Would it be save to call the function and dereference the pointer simultaneously?
Edit: Many answers. Will accept the first one who can show me the section out of the standard.
|
2012/03/02
|
['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']
|
According to the standard:
>
> C++11 1.10/3: The value of an object visible to a thread T at a particular point is the initial value of the object, a value assigned to the object by T, or a value assigned to the object by another thread, according to the rules below.
>
>
>
A string literal, like any other constant object, cannot legally be assigned to; it has static storage duration, and so is initialised before the program starts; therefore, all threads will see its initial value at all times.
Older standards had nothing to say about threads; so if your compiler doesn't support the C++11 threading model then you'll have to consult its documentation for any thread-safety guarantees. However, it's hard to imagine any implementation under which access to immutable objects were not thread-safe.
|
It is always safe to access immutable data from multiple threads. String literals are an example of immutable data (since it's illegal to modify them at run-time), so it is safe to access them from multiple threads.
|
9,533,392 |
Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this:
```
const char* give()
{
return "Hello, World!";
}
```
Would it be save to call the function and dereference the pointer simultaneously?
Edit: Many answers. Will accept the first one who can show me the section out of the standard.
|
2012/03/02
|
['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']
|
Yes, it's safe. Why wouldn't it be? It would be unsafe if you'd try to modify the string, but that's illegal anyway.
|
As long as you only read data, you can access it from as many threads as you want. When data needs to be changed, that's when it gets complicated.
|
9,533,392 |
Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this:
```
const char* give()
{
return "Hello, World!";
}
```
Would it be save to call the function and dereference the pointer simultaneously?
Edit: Many answers. Will accept the first one who can show me the section out of the standard.
|
2012/03/02
|
['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']
|
According to the standard:
>
> C++11 1.10/3: The value of an object visible to a thread T at a particular point is the initial value of the object, a value assigned to the object by T, or a value assigned to the object by another thread, according to the rules below.
>
>
>
A string literal, like any other constant object, cannot legally be assigned to; it has static storage duration, and so is initialised before the program starts; therefore, all threads will see its initial value at all times.
Older standards had nothing to say about threads; so if your compiler doesn't support the C++11 threading model then you'll have to consult its documentation for any thread-safety guarantees. However, it's hard to imagine any implementation under which access to immutable objects were not thread-safe.
|
Yes, it's safe. Why wouldn't it be? It would be unsafe if you'd try to modify the string, but that's illegal anyway.
|
9,533,392 |
Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this:
```
const char* give()
{
return "Hello, World!";
}
```
Would it be save to call the function and dereference the pointer simultaneously?
Edit: Many answers. Will accept the first one who can show me the section out of the standard.
|
2012/03/02
|
['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']
|
As long as you only read data, you can access it from as many threads as you want. When data needs to be changed, that's when it gets complicated.
|
String literals are (conceptually) stored in read only memory and initialised on loading (rather than at runtime). It's therefore safe to access them from multiple threads at any time.
Note that more complex structures might not be initialised at load time, and so multiple thread access might have the possibility of issues immediately after the creation of the object.
But string literals are completely safe.
|
9,533,392 |
Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this:
```
const char* give()
{
return "Hello, World!";
}
```
Would it be save to call the function and dereference the pointer simultaneously?
Edit: Many answers. Will accept the first one who can show me the section out of the standard.
|
2012/03/02
|
['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']
|
It is always safe to access immutable data from multiple threads. String literals are an example of immutable data (since it's illegal to modify them at run-time), so it is safe to access them from multiple threads.
|
This depends on the implementation of the C Compiler. But I do not know of an implementation where concurrent read accesses might be unsafe, so in practice this is safe.
|
9,533,392 |
Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this:
```
const char* give()
{
return "Hello, World!";
}
```
Would it be save to call the function and dereference the pointer simultaneously?
Edit: Many answers. Will accept the first one who can show me the section out of the standard.
|
2012/03/02
|
['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']
|
According to the standard:
>
> C++11 1.10/3: The value of an object visible to a thread T at a particular point is the initial value of the object, a value assigned to the object by T, or a value assigned to the object by another thread, according to the rules below.
>
>
>
A string literal, like any other constant object, cannot legally be assigned to; it has static storage duration, and so is initialised before the program starts; therefore, all threads will see its initial value at all times.
Older standards had nothing to say about threads; so if your compiler doesn't support the C++11 threading model then you'll have to consult its documentation for any thread-safety guarantees. However, it's hard to imagine any implementation under which access to immutable objects were not thread-safe.
|
This depends on the implementation of the C Compiler. But I do not know of an implementation where concurrent read accesses might be unsafe, so in practice this is safe.
|
9,533,392 |
Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this:
```
const char* give()
{
return "Hello, World!";
}
```
Would it be save to call the function and dereference the pointer simultaneously?
Edit: Many answers. Will accept the first one who can show me the section out of the standard.
|
2012/03/02
|
['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']
|
It is always safe to access immutable data from multiple threads. String literals are an example of immutable data (since it's illegal to modify them at run-time), so it is safe to access them from multiple threads.
|
As long as you only read data, you can access it from as many threads as you want. When data needs to be changed, that's when it gets complicated.
|
9,533,392 |
Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this:
```
const char* give()
{
return "Hello, World!";
}
```
Would it be save to call the function and dereference the pointer simultaneously?
Edit: Many answers. Will accept the first one who can show me the section out of the standard.
|
2012/03/02
|
['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']
|
Yes, it's safe. Why wouldn't it be? It would be unsafe if you'd try to modify the string, but that's illegal anyway.
|
String literals are (conceptually) stored in read only memory and initialised on loading (rather than at runtime). It's therefore safe to access them from multiple threads at any time.
Note that more complex structures might not be initialised at load time, and so multiple thread access might have the possibility of issues immediately after the creation of the object.
But string literals are completely safe.
|
9,533,392 |
Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this:
```
const char* give()
{
return "Hello, World!";
}
```
Would it be save to call the function and dereference the pointer simultaneously?
Edit: Many answers. Will accept the first one who can show me the section out of the standard.
|
2012/03/02
|
['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']
|
Yes, it's safe. Why wouldn't it be? It would be unsafe if you'd try to modify the string, but that's illegal anyway.
|
This depends on the implementation of the C Compiler. But I do not know of an implementation where concurrent read accesses might be unsafe, so in practice this is safe.
|
9,533,392 |
Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this:
```
const char* give()
{
return "Hello, World!";
}
```
Would it be save to call the function and dereference the pointer simultaneously?
Edit: Many answers. Will accept the first one who can show me the section out of the standard.
|
2012/03/02
|
['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']
|
According to the standard:
>
> C++11 1.10/3: The value of an object visible to a thread T at a particular point is the initial value of the object, a value assigned to the object by T, or a value assigned to the object by another thread, according to the rules below.
>
>
>
A string literal, like any other constant object, cannot legally be assigned to; it has static storage duration, and so is initialised before the program starts; therefore, all threads will see its initial value at all times.
Older standards had nothing to say about threads; so if your compiler doesn't support the C++11 threading model then you'll have to consult its documentation for any thread-safety guarantees. However, it's hard to imagine any implementation under which access to immutable objects were not thread-safe.
|
String literals are (conceptually) stored in read only memory and initialised on loading (rather than at runtime). It's therefore safe to access them from multiple threads at any time.
Note that more complex structures might not be initialised at load time, and so multiple thread access might have the possibility of issues immediately after the creation of the object.
But string literals are completely safe.
|
52,426,582 |
I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.
Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?
Below is the Code:
```
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
```
|
2018/09/20
|
['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']
|
I'm taking it that you mean that different "people" that are conducting simultaneous requests should not get the same random row? The most robust way, without testing it, in order to avoid the minute chance of the same record being selected twice in two running requests will probably be to lock the table and perform the read and update in a transaction. You would have to use a storage engine that supports this, such as InnoDB.
The way to accomplish `LOCK TABLES` and `UNLOCK TABLES` with transactional tables, such as InnoDB tables, is to begin a transaction with `SET autocommit = 0`, **not** `START TRANSACTION`, followed by `LOCK TABLES`. Then you should not call `UNLOCK TABLES` until you commit the transaction explicitly.
For example, if you need to read and write to your table in one go, you can do this:
```
SET autocommit = 0;
LOCK TABLES ad_banner_queue AS ad_banner_queue_w WRITE, ad_banner_queue AS ad_banner_queue_r READ;
... perform your select query on ad_banner_queue_r, then update that row in ad_banner_queue_w with is_sent = 1...
COMMIT;
UNLOCK TABLES;
```
The reason we lock with an alias is that you [cannot refer to a locked table multiple times in a single query using the same name](https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html). So we use aliases instead and obtain a separate lock for the table and each alias.
|
You should create a separate db table and mark ads that user received with its help. Before sending ads to user check if he has already received it.
|
52,426,582 |
I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.
Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?
Below is the Code:
```
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
```
|
2018/09/20
|
['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']
|
You may use [mutex](https://www.yiiframework.com/doc/api/2.0/yii-mutex-mutex) component to ensure that there is only one process trying to pop ad from queue.
```
$banner = [];
$key = __CLASS__ . '::generateAdQueue()' . serialize($params);
if (Yii::$app->mutex->acquire($key, 1)) {
$banner = $this->getBanner($params);
Yii::$app->mutex->release($key);
}
```
However be aware that this may greatly reduce performance, especially if you want to process multiple request at the same time. You may consider different technology for such queue, relational databases does not really fit well for such task. Using Redis-based queue and [`SPOP`](https://redis.io/commands/spop) may be much better choice.
|
You can use transactions and SELECT FOR UPDATE construction for lock data and consistent executing of queries. For instance:
```
public function getAds()
{
$db = Yii::$app->db;
$transaction = $db->beginTransaction(Transaction::REPEATABLE_READ);
try {
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where(new Expression('is_sent=0 FOR UPDATE'))
->orderBy('RAND()')
->one();
if ($ads_queue === false) {
$transaction->commit();
return null;
}
$db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
$transaction->commit();
return $ads_queue;
} catch(Exception $e) {
$transaction->rollBack();
throw $e;
}
}
public function getBanner($params)
{
$ads_queue = $this->getAds();
if (is_null($ads_queue)) {
$output = $this->generateAdQueue();
if ($output == false) {
return array();
}
$ads_queue = $this->getAds();
}
return $ads_queue;
}
```
|
52,426,582 |
I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.
Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?
Below is the Code:
```
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
```
|
2018/09/20
|
['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']
|
I'm taking it that you mean that different "people" that are conducting simultaneous requests should not get the same random row? The most robust way, without testing it, in order to avoid the minute chance of the same record being selected twice in two running requests will probably be to lock the table and perform the read and update in a transaction. You would have to use a storage engine that supports this, such as InnoDB.
The way to accomplish `LOCK TABLES` and `UNLOCK TABLES` with transactional tables, such as InnoDB tables, is to begin a transaction with `SET autocommit = 0`, **not** `START TRANSACTION`, followed by `LOCK TABLES`. Then you should not call `UNLOCK TABLES` until you commit the transaction explicitly.
For example, if you need to read and write to your table in one go, you can do this:
```
SET autocommit = 0;
LOCK TABLES ad_banner_queue AS ad_banner_queue_w WRITE, ad_banner_queue AS ad_banner_queue_r READ;
... perform your select query on ad_banner_queue_r, then update that row in ad_banner_queue_w with is_sent = 1...
COMMIT;
UNLOCK TABLES;
```
The reason we lock with an alias is that you [cannot refer to a locked table multiple times in a single query using the same name](https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html). So we use aliases instead and obtain a separate lock for the table and each alias.
|
Make your index unique or make a check that checks the data and see's if it is a duplicate.
Hope this helps. Good luck
|
52,426,582 |
I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.
Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?
Below is the Code:
```
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
```
|
2018/09/20
|
['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']
|
Although it might seem to be a trivial question it is not at all, there are several ways to handle it and each of them has its own downsides, mainly you can face this issue from three different points:
Live with it
============
Chances you can get a repeated pull are low in real life and you need to really think if you are willing to face the extra work just to make sure an ad is not shown twice in a row, you also need to think caches exist and you might break your brain making ads atomic just to find out browser/proxy/cache are serving a repeated ad :(
Handle it on database
=====================
You can handle this issue leaving the database the responsability to keep data safe and coherent(indeed it is the main task of database), there are several ways of doing it:
* **Locks and table** (as previously suggested), I personally disklike the approach of using locks with PHP and MySQL, you will suffer performance penalities and risk deadlocking but anyway it's still a solution, you just make a select for update on your queue table to be sure no-one reads again until you update. The problem in here is you will lock the whole table while this is done and you need to be careful with your DB Driver and autocommits.
* **Cursors** Cursors are database structures created basically for the duty you are willing to do, you create a cursor and safely traverse it with [its functions](https://dev.mysql.com/doc/refman/5.7/en/cursors.html). Using cursors into PHP might be very tricky due to transactions too and you need to know very well what are you doing to avoid errors.
* **Cursors and stored procedures** the best way to handle this into database is managing cursors inside the database itself, that's why stored procedures are there, just create procedures to pull a new item from your cursor and to fill it again once it's all consumed.
Handle it on PHP side
=====================
In this case you need to implement your own queue on PHP and there might be several ways to do so but the main problem might be implementing multiprocess-safe atomic operations on your app, I personally dislike using any kind of locks if you are not 100% sure of the execution flow of your app or you might end up locking it all. Anyway there are three chances in here:
* **Use sems or mutex** both included on php or third party, timeouts and locks can become a hell and they are not easy to detect so as stated above I'd avoid it.
* **[Use PHP MSG Queue](https://secure.php.net/manual/en/function.msg-get-queue.php)** I think this is the safest way as long as you run your app on a \*nix system, just send all the available ads to the message queue instead of creating a table on database, once all ads are consumed you can regenerate the queue once again, the drawback of this system is your server can not be distributed and you might lose the current queue status if you don't save it before a restart.
* **Third party queue system** depending on your app workload or interactions you might need to use a queue management system, this is a must if you want a distributed system, it might sound too serious using a msg queue system to handle this issue but this kind of approaches may be life-savers.
Summary
=======
If you can't live with it and are proficient enough with databases i'd go for stored procedures and cursors, you don't need to break your mind with concurrency, database will handle it as long as you are using an ACID compliant database (not MyISAM i.e.)
If you want to avoid conding into the database and your system is \*nix and not going to be distributed you can give a try to msg\_queues
If you think your system may be sometime distributed or do not rely on old SysV mechanisms you can give a try to a message broker like RabbitMQ, this nice things are addictive and once you start using them you start seeing new uses for them daily.
|
You may use [mutex](https://www.yiiframework.com/doc/api/2.0/yii-mutex-mutex) component to ensure that there is only one process trying to pop ad from queue.
```
$banner = [];
$key = __CLASS__ . '::generateAdQueue()' . serialize($params);
if (Yii::$app->mutex->acquire($key, 1)) {
$banner = $this->getBanner($params);
Yii::$app->mutex->release($key);
}
```
However be aware that this may greatly reduce performance, especially if you want to process multiple request at the same time. You may consider different technology for such queue, relational databases does not really fit well for such task. Using Redis-based queue and [`SPOP`](https://redis.io/commands/spop) may be much better choice.
|
52,426,582 |
I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.
Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?
Below is the Code:
```
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
```
|
2018/09/20
|
['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']
|
Presumably, the ads are presented from separate pages. HTML is "stateless", so you cannot expect one page to know what ads have previously been displayed. So, you have to either pass this info from page to page, or store it somewhere in the database associated with the individual user.
You also want some randomizing? Let's do both things at the same time.
What is the "state"? There is an "initial state", at which time you randomly pick the first ad to display. And you pass that info on to the next page (in the url or in a cookie or in the database).
The other "state" looks at the previous state and computes which ad to display next. (Eventually, you need to worry about running out of ads -- will you start over? Will you re-randomize? Etc.)
But how to avoid showing the same "random" ad twice in a row?
* You have N ads -- `SELECT COUNT(*) ...`
* You picked add number J as the first ad to display -- simple application of `RAND()`, either in SQL or in the app.
* Pick a number, M, such that M and N are "relatively prime".
* The "next" ad is number (J := (J + M) mod N). This will cycle through all the ads without duplicating until all have been shown. -- Again, this can be done in SQL or in the ap.
* Pass J and M from one page to the next.
To get the J'th row: Either have the rows uniquely *and* consecutively numbered; or use `ORDER BY ... LIMIT 1 OFFSET J`. (Caveat: it may be tricky to fill J into the SQL.)
No table locks, no mutexes, just passing info from one page to the next.
|
Make your index unique or make a check that checks the data and see's if it is a duplicate.
Hope this helps. Good luck
|
52,426,582 |
I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.
Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?
Below is the Code:
```
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
```
|
2018/09/20
|
['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']
|
I'm taking it that you mean that different "people" that are conducting simultaneous requests should not get the same random row? The most robust way, without testing it, in order to avoid the minute chance of the same record being selected twice in two running requests will probably be to lock the table and perform the read and update in a transaction. You would have to use a storage engine that supports this, such as InnoDB.
The way to accomplish `LOCK TABLES` and `UNLOCK TABLES` with transactional tables, such as InnoDB tables, is to begin a transaction with `SET autocommit = 0`, **not** `START TRANSACTION`, followed by `LOCK TABLES`. Then you should not call `UNLOCK TABLES` until you commit the transaction explicitly.
For example, if you need to read and write to your table in one go, you can do this:
```
SET autocommit = 0;
LOCK TABLES ad_banner_queue AS ad_banner_queue_w WRITE, ad_banner_queue AS ad_banner_queue_r READ;
... perform your select query on ad_banner_queue_r, then update that row in ad_banner_queue_w with is_sent = 1...
COMMIT;
UNLOCK TABLES;
```
The reason we lock with an alias is that you [cannot refer to a locked table multiple times in a single query using the same name](https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html). So we use aliases instead and obtain a separate lock for the table and each alias.
|
Presumably, the ads are presented from separate pages. HTML is "stateless", so you cannot expect one page to know what ads have previously been displayed. So, you have to either pass this info from page to page, or store it somewhere in the database associated with the individual user.
You also want some randomizing? Let's do both things at the same time.
What is the "state"? There is an "initial state", at which time you randomly pick the first ad to display. And you pass that info on to the next page (in the url or in a cookie or in the database).
The other "state" looks at the previous state and computes which ad to display next. (Eventually, you need to worry about running out of ads -- will you start over? Will you re-randomize? Etc.)
But how to avoid showing the same "random" ad twice in a row?
* You have N ads -- `SELECT COUNT(*) ...`
* You picked add number J as the first ad to display -- simple application of `RAND()`, either in SQL or in the app.
* Pick a number, M, such that M and N are "relatively prime".
* The "next" ad is number (J := (J + M) mod N). This will cycle through all the ads without duplicating until all have been shown. -- Again, this can be done in SQL or in the ap.
* Pass J and M from one page to the next.
To get the J'th row: Either have the rows uniquely *and* consecutively numbered; or use `ORDER BY ... LIMIT 1 OFFSET J`. (Caveat: it may be tricky to fill J into the SQL.)
No table locks, no mutexes, just passing info from one page to the next.
|
52,426,582 |
I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.
Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?
Below is the Code:
```
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
```
|
2018/09/20
|
['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']
|
You should create a separate db table and mark ads that user received with its help. Before sending ads to user check if he has already received it.
|
Make your index unique or make a check that checks the data and see's if it is a duplicate.
Hope this helps. Good luck
|
52,426,582 |
I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.
Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?
Below is the Code:
```
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
```
|
2018/09/20
|
['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']
|
I'm taking it that you mean that different "people" that are conducting simultaneous requests should not get the same random row? The most robust way, without testing it, in order to avoid the minute chance of the same record being selected twice in two running requests will probably be to lock the table and perform the read and update in a transaction. You would have to use a storage engine that supports this, such as InnoDB.
The way to accomplish `LOCK TABLES` and `UNLOCK TABLES` with transactional tables, such as InnoDB tables, is to begin a transaction with `SET autocommit = 0`, **not** `START TRANSACTION`, followed by `LOCK TABLES`. Then you should not call `UNLOCK TABLES` until you commit the transaction explicitly.
For example, if you need to read and write to your table in one go, you can do this:
```
SET autocommit = 0;
LOCK TABLES ad_banner_queue AS ad_banner_queue_w WRITE, ad_banner_queue AS ad_banner_queue_r READ;
... perform your select query on ad_banner_queue_r, then update that row in ad_banner_queue_w with is_sent = 1...
COMMIT;
UNLOCK TABLES;
```
The reason we lock with an alias is that you [cannot refer to a locked table multiple times in a single query using the same name](https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html). So we use aliases instead and obtain a separate lock for the table and each alias.
|
You may use [mutex](https://www.yiiframework.com/doc/api/2.0/yii-mutex-mutex) component to ensure that there is only one process trying to pop ad from queue.
```
$banner = [];
$key = __CLASS__ . '::generateAdQueue()' . serialize($params);
if (Yii::$app->mutex->acquire($key, 1)) {
$banner = $this->getBanner($params);
Yii::$app->mutex->release($key);
}
```
However be aware that this may greatly reduce performance, especially if you want to process multiple request at the same time. You may consider different technology for such queue, relational databases does not really fit well for such task. Using Redis-based queue and [`SPOP`](https://redis.io/commands/spop) may be much better choice.
|
52,426,582 |
I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.
Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?
Below is the Code:
```
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
```
|
2018/09/20
|
['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']
|
Although it might seem to be a trivial question it is not at all, there are several ways to handle it and each of them has its own downsides, mainly you can face this issue from three different points:
Live with it
============
Chances you can get a repeated pull are low in real life and you need to really think if you are willing to face the extra work just to make sure an ad is not shown twice in a row, you also need to think caches exist and you might break your brain making ads atomic just to find out browser/proxy/cache are serving a repeated ad :(
Handle it on database
=====================
You can handle this issue leaving the database the responsability to keep data safe and coherent(indeed it is the main task of database), there are several ways of doing it:
* **Locks and table** (as previously suggested), I personally disklike the approach of using locks with PHP and MySQL, you will suffer performance penalities and risk deadlocking but anyway it's still a solution, you just make a select for update on your queue table to be sure no-one reads again until you update. The problem in here is you will lock the whole table while this is done and you need to be careful with your DB Driver and autocommits.
* **Cursors** Cursors are database structures created basically for the duty you are willing to do, you create a cursor and safely traverse it with [its functions](https://dev.mysql.com/doc/refman/5.7/en/cursors.html). Using cursors into PHP might be very tricky due to transactions too and you need to know very well what are you doing to avoid errors.
* **Cursors and stored procedures** the best way to handle this into database is managing cursors inside the database itself, that's why stored procedures are there, just create procedures to pull a new item from your cursor and to fill it again once it's all consumed.
Handle it on PHP side
=====================
In this case you need to implement your own queue on PHP and there might be several ways to do so but the main problem might be implementing multiprocess-safe atomic operations on your app, I personally dislike using any kind of locks if you are not 100% sure of the execution flow of your app or you might end up locking it all. Anyway there are three chances in here:
* **Use sems or mutex** both included on php or third party, timeouts and locks can become a hell and they are not easy to detect so as stated above I'd avoid it.
* **[Use PHP MSG Queue](https://secure.php.net/manual/en/function.msg-get-queue.php)** I think this is the safest way as long as you run your app on a \*nix system, just send all the available ads to the message queue instead of creating a table on database, once all ads are consumed you can regenerate the queue once again, the drawback of this system is your server can not be distributed and you might lose the current queue status if you don't save it before a restart.
* **Third party queue system** depending on your app workload or interactions you might need to use a queue management system, this is a must if you want a distributed system, it might sound too serious using a msg queue system to handle this issue but this kind of approaches may be life-savers.
Summary
=======
If you can't live with it and are proficient enough with databases i'd go for stored procedures and cursors, you don't need to break your mind with concurrency, database will handle it as long as you are using an ACID compliant database (not MyISAM i.e.)
If you want to avoid conding into the database and your system is \*nix and not going to be distributed you can give a try to msg\_queues
If you think your system may be sometime distributed or do not rely on old SysV mechanisms you can give a try to a message broker like RabbitMQ, this nice things are addictive and once you start using them you start seeing new uses for them daily.
|
Make your index unique or make a check that checks the data and see's if it is a duplicate.
Hope this helps. Good luck
|
52,426,582 |
I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.
Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?
Below is the Code:
```
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
```
|
2018/09/20
|
['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']
|
Presumably, the ads are presented from separate pages. HTML is "stateless", so you cannot expect one page to know what ads have previously been displayed. So, you have to either pass this info from page to page, or store it somewhere in the database associated with the individual user.
You also want some randomizing? Let's do both things at the same time.
What is the "state"? There is an "initial state", at which time you randomly pick the first ad to display. And you pass that info on to the next page (in the url or in a cookie or in the database).
The other "state" looks at the previous state and computes which ad to display next. (Eventually, you need to worry about running out of ads -- will you start over? Will you re-randomize? Etc.)
But how to avoid showing the same "random" ad twice in a row?
* You have N ads -- `SELECT COUNT(*) ...`
* You picked add number J as the first ad to display -- simple application of `RAND()`, either in SQL or in the app.
* Pick a number, M, such that M and N are "relatively prime".
* The "next" ad is number (J := (J + M) mod N). This will cycle through all the ads without duplicating until all have been shown. -- Again, this can be done in SQL or in the ap.
* Pass J and M from one page to the next.
To get the J'th row: Either have the rows uniquely *and* consecutively numbered; or use `ORDER BY ... LIMIT 1 OFFSET J`. (Caveat: it may be tricky to fill J into the SQL.)
No table locks, no mutexes, just passing info from one page to the next.
|
You can use transactions and SELECT FOR UPDATE construction for lock data and consistent executing of queries. For instance:
```
public function getAds()
{
$db = Yii::$app->db;
$transaction = $db->beginTransaction(Transaction::REPEATABLE_READ);
try {
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where(new Expression('is_sent=0 FOR UPDATE'))
->orderBy('RAND()')
->one();
if ($ads_queue === false) {
$transaction->commit();
return null;
}
$db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
$transaction->commit();
return $ads_queue;
} catch(Exception $e) {
$transaction->rollBack();
throw $e;
}
}
public function getBanner($params)
{
$ads_queue = $this->getAds();
if (is_null($ads_queue)) {
$output = $this->generateAdQueue();
if ($output == false) {
return array();
}
$ads_queue = $this->getAds();
}
return $ads_queue;
}
```
|
30,707,256 |
I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?
|
2015/06/08
|
['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']
|
I'm from Instamojo.
You can't use a local URL. This is because a webhook request is a POST request that is made from our server. Therefore, the only URLs that we can make these requests to would be URLs that are publicly available.
For testing purposes, I would recommend using [RequestBin](https://requestbin.com/). You can create a new bin and paste the URL for that bin in the webhook URL field of your Instamojo link. This will give you a link that is accessible by our server and you can inspect the POST requests to this link by appending `?inspect` at the end of the URL.
|
I doubt if you can use local host URL
but instead you can create new links, as below
<https://www.instamojo.com/api/1.1/links/>
|
30,707,256 |
I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?
|
2015/06/08
|
['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']
|
It is possible to forward Instamojo's webhooks to your local machine using tools like `localtunnel`.
* `npm` is required to install localtunnel. [[How to install node and npm]](https://docs.npmjs.com/getting-started/installing-node)
* Install
[localtunnel](https://localtunnel.me/)
Suppose you are running your local server at port 8000, in a new terminal window, execute this:
* `lt --port 8000`
It will show you output like:
* `your url is: https://whawgpctcs.localtunnel.me`
This is a *temporary* webhook URL that will forward every HTTPS request sent to `https://whawgpctcs.localtunnel.me` to your local server running on port `8000`.
* Paste this temporary url into Instamojo's webhook field and continue testing.
* **Remember to remove the temporary webhook URL from Instamojo once you are done testing**
The temporary webhook URL is valid as long as the `lt --port 8000` command (and your Internet connection) is active.
|
I doubt if you can use local host URL
but instead you can create new links, as below
<https://www.instamojo.com/api/1.1/links/>
|
30,707,256 |
I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?
|
2015/06/08
|
['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']
|
I doubt if you can use local host URL
but instead you can create new links, as below
<https://www.instamojo.com/api/1.1/links/>
|
You cannot use the localhost URL as a webhook URL in order to test the process. But you can simply bypass it, open hosts file from `C:\Windows\System32\Drivers\etc\hosts`
At the end of the line write
```
127.0.0.1 yourname.com
```
And access localhost using yourname.com.
Just change localhost/your-location url with yourname.com/your-location in the PHP file.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.