qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
59,208,214 |
Value:
0.344
-0.124
0.880
0
0.910
-0.800
|
2019/12/06
|
[
"https://Stackoverflow.com/questions/59208214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742655/"
] |
This will help you understand lambda expressions better.
[Anatomy of the Lambda Expression](https://www.tutorialsteacher.com/linq/linq-lambda-expression)
And this is for [Linq](https://www.tutorialsteacher.com/linq/what-is-linq)
Hope this helps.
Thank you.
|
Where clause exists in Enumerable class which uses for querying in .net framework. it provides as boolean condition and return source. It will convert to respective sql query eventually.
so your linq
```
var salaries = customerList
.Where(c => c.Age > 30)
.Select(c => c.Salary) // salary is of type long
.ToList();
```
old school sql command
```
SELECT [c].[Salary] FROM [CustomerList] WHERE [c].[Age] > '30'
```
|
59,208,214 |
Value:
0.344
-0.124
0.880
0
0.910
-0.800
|
2019/12/06
|
[
"https://Stackoverflow.com/questions/59208214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742655/"
] |
`Where` is probably implemented like this (note that this is a very rough implementation, just do give you an idea of what it is like):
```
public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
foreach (T t in source) {
if (predicate(t)) {
yield return t;
}
}
}
```
Note that `Where` is an extension method. You are essentially calling `Where(customerList, c => c.Age > 30)`. Now you should see where it gets access of the `customerList`. It also infers what `T` should be by looking at what kind of `IEnumerable` `customerList` is. Since it is a `IEnumerable<Customer>`, `T` is `Customer`, and so it expects a `Func<Customer, bool>` for the second argument. This is how it knows that `c` is `Customer`.
`Where` does not return a temporary list. A lot of LINQ methods make use of deferred evaluation. `Where` returns an `IEnumerable<Customer>` that is filtered. Remember that `IEnumerable` is just a sequence of things. This sequence returned by `Where` however, is not evaluated, until you ask for it. `Select` does the same as well. So a list is not created until you call `ToList`.
Your third question is kind of like asking "How does `Where` know how to filter" or "How does `Console.WriteLine` know how to write to the screen". That's what `Select` does. You can look at its implementation if you want. Here's a rough sketch:
```
public static IEnumerable<U> Select<T, U>(this IEnumerable<T> source, Func<T, U> mapping) {
foreach (T t in source) {
yield mapping(t);
}
}
```
The type of the variable `salaries` is determined by looking at the method signatures of each of the methods you call. Your `Select` call returns a `IEnumerable<long>`, and `ToList`'s signature tells the compiler that, given a `IEnumerable<T>` it will return `List<T>`, so in this case, it returns a `List<long>`.
|
Where clause exists in Enumerable class which uses for querying in .net framework. it provides as boolean condition and return source. It will convert to respective sql query eventually.
so your linq
```
var salaries = customerList
.Where(c => c.Age > 30)
.Select(c => c.Salary) // salary is of type long
.ToList();
```
old school sql command
```
SELECT [c].[Salary] FROM [CustomerList] WHERE [c].[Age] > '30'
```
|
59,208,214 |
Value:
0.344
-0.124
0.880
0
0.910
-0.800
|
2019/12/06
|
[
"https://Stackoverflow.com/questions/59208214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742655/"
] |
This will help you understand lambda expressions better.
[Anatomy of the Lambda Expression](https://www.tutorialsteacher.com/linq/linq-lambda-expression)
And this is for [Linq](https://www.tutorialsteacher.com/linq/what-is-linq)
Hope this helps.
Thank you.
|
>
> how does "Where" get access to the customerList and how does it define
> the type of "c"?
>
>
>
* customerList is of type List and `Where()` is an extension method of type List. So `Where()` method is accessible to customerList. `c => c.Age > 30` is a predicate define inside `Where()` clause. This predicate help list to filter out data based on condition. Here `c` indicates individual element present in List.
>
> How exactly does "Select" know that it has to return only the
> "Salary"?
>
>
>
* Select is used to project individual element from List, in your case each `customer` from `customerList`. As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of `Salary` property from `Customer` class.
>
> How does the type of the variable "salaries" get set to List< long >?
>
>
>
* `Select()` will crate new form with only Salary property something like
```
new {
public long Salary{get; set;}
}
```
.ToList() will convert `IEnumerable` returned by Select into `List`. Ultimately you will get `List<long>`
>
> "Where" return a temporary list of customers after applying the
> filter on which the Select acts?
>
>
>
* Yes, Where will return filtered list(Precise `IEnumerable`) on which you applied `Select()` method
I would suggest you to read [Linq in C#](https://learn.microsoft.com/en-us/dotnet/csharp/linq/), [Where clause](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=netframework-4.8), [Select method](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.8), [List](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.8).
|
59,208,214 |
Value:
0.344
-0.124
0.880
0
0.910
-0.800
|
2019/12/06
|
[
"https://Stackoverflow.com/questions/59208214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742655/"
] |
`Where` is probably implemented like this (note that this is a very rough implementation, just do give you an idea of what it is like):
```
public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
foreach (T t in source) {
if (predicate(t)) {
yield return t;
}
}
}
```
Note that `Where` is an extension method. You are essentially calling `Where(customerList, c => c.Age > 30)`. Now you should see where it gets access of the `customerList`. It also infers what `T` should be by looking at what kind of `IEnumerable` `customerList` is. Since it is a `IEnumerable<Customer>`, `T` is `Customer`, and so it expects a `Func<Customer, bool>` for the second argument. This is how it knows that `c` is `Customer`.
`Where` does not return a temporary list. A lot of LINQ methods make use of deferred evaluation. `Where` returns an `IEnumerable<Customer>` that is filtered. Remember that `IEnumerable` is just a sequence of things. This sequence returned by `Where` however, is not evaluated, until you ask for it. `Select` does the same as well. So a list is not created until you call `ToList`.
Your third question is kind of like asking "How does `Where` know how to filter" or "How does `Console.WriteLine` know how to write to the screen". That's what `Select` does. You can look at its implementation if you want. Here's a rough sketch:
```
public static IEnumerable<U> Select<T, U>(this IEnumerable<T> source, Func<T, U> mapping) {
foreach (T t in source) {
yield mapping(t);
}
}
```
The type of the variable `salaries` is determined by looking at the method signatures of each of the methods you call. Your `Select` call returns a `IEnumerable<long>`, and `ToList`'s signature tells the compiler that, given a `IEnumerable<T>` it will return `List<T>`, so in this case, it returns a `List<long>`.
|
This will help you understand lambda expressions better.
[Anatomy of the Lambda Expression](https://www.tutorialsteacher.com/linq/linq-lambda-expression)
And this is for [Linq](https://www.tutorialsteacher.com/linq/what-is-linq)
Hope this helps.
Thank you.
|
59,208,214 |
Value:
0.344
-0.124
0.880
0
0.910
-0.800
|
2019/12/06
|
[
"https://Stackoverflow.com/questions/59208214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742655/"
] |
This will help you understand lambda expressions better.
[Anatomy of the Lambda Expression](https://www.tutorialsteacher.com/linq/linq-lambda-expression)
And this is for [Linq](https://www.tutorialsteacher.com/linq/what-is-linq)
Hope this helps.
Thank you.
|
The [link from @Amit](https://stackoverflow.com/questions/671235/how-linq-works-internally/671425#671425) can give a good idea.
Short answer is that LINQ is built on the compiler feature called Expressions. When you write something like `Where(c => c.Age > 18)` compiler doesn't actually compile the `c=> c.Age > 18` all the way like a regular method.
It builds a syntax tree that describes what that code does.
The `Where` function uses this to build a SQL query that is sent to the SQL server which executes that to get the results.
Suggest you look into the workings of [`IQueryable`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.iqueryable?view=netcore-3.0) and [`Expression<TDelegate>`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression-1?view=netcore-3.0) for more information.
Also helps to understand the [difference between IEnumerable and IQueryable](https://stackoverflow.com/q/252785/975887).
Another example of Expressions used in other parts of C# like Razor pages that uses functions like [LabelFor(...)](https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.html.labelextensions.labelfor?view=aspnet-mvc-5.2) which uses the property you *express* to build a HTML label rather than executing the code.
HTH
|
59,208,214 |
Value:
0.344
-0.124
0.880
0
0.910
-0.800
|
2019/12/06
|
[
"https://Stackoverflow.com/questions/59208214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742655/"
] |
`Where` is probably implemented like this (note that this is a very rough implementation, just do give you an idea of what it is like):
```
public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
foreach (T t in source) {
if (predicate(t)) {
yield return t;
}
}
}
```
Note that `Where` is an extension method. You are essentially calling `Where(customerList, c => c.Age > 30)`. Now you should see where it gets access of the `customerList`. It also infers what `T` should be by looking at what kind of `IEnumerable` `customerList` is. Since it is a `IEnumerable<Customer>`, `T` is `Customer`, and so it expects a `Func<Customer, bool>` for the second argument. This is how it knows that `c` is `Customer`.
`Where` does not return a temporary list. A lot of LINQ methods make use of deferred evaluation. `Where` returns an `IEnumerable<Customer>` that is filtered. Remember that `IEnumerable` is just a sequence of things. This sequence returned by `Where` however, is not evaluated, until you ask for it. `Select` does the same as well. So a list is not created until you call `ToList`.
Your third question is kind of like asking "How does `Where` know how to filter" or "How does `Console.WriteLine` know how to write to the screen". That's what `Select` does. You can look at its implementation if you want. Here's a rough sketch:
```
public static IEnumerable<U> Select<T, U>(this IEnumerable<T> source, Func<T, U> mapping) {
foreach (T t in source) {
yield mapping(t);
}
}
```
The type of the variable `salaries` is determined by looking at the method signatures of each of the methods you call. Your `Select` call returns a `IEnumerable<long>`, and `ToList`'s signature tells the compiler that, given a `IEnumerable<T>` it will return `List<T>`, so in this case, it returns a `List<long>`.
|
>
> how does "Where" get access to the customerList and how does it define
> the type of "c"?
>
>
>
* customerList is of type List and `Where()` is an extension method of type List. So `Where()` method is accessible to customerList. `c => c.Age > 30` is a predicate define inside `Where()` clause. This predicate help list to filter out data based on condition. Here `c` indicates individual element present in List.
>
> How exactly does "Select" know that it has to return only the
> "Salary"?
>
>
>
* Select is used to project individual element from List, in your case each `customer` from `customerList`. As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of `Salary` property from `Customer` class.
>
> How does the type of the variable "salaries" get set to List< long >?
>
>
>
* `Select()` will crate new form with only Salary property something like
```
new {
public long Salary{get; set;}
}
```
.ToList() will convert `IEnumerable` returned by Select into `List`. Ultimately you will get `List<long>`
>
> "Where" return a temporary list of customers after applying the
> filter on which the Select acts?
>
>
>
* Yes, Where will return filtered list(Precise `IEnumerable`) on which you applied `Select()` method
I would suggest you to read [Linq in C#](https://learn.microsoft.com/en-us/dotnet/csharp/linq/), [Where clause](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=netframework-4.8), [Select method](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.8), [List](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.8).
|
59,208,214 |
Value:
0.344
-0.124
0.880
0
0.910
-0.800
|
2019/12/06
|
[
"https://Stackoverflow.com/questions/59208214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4742655/"
] |
`Where` is probably implemented like this (note that this is a very rough implementation, just do give you an idea of what it is like):
```
public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
foreach (T t in source) {
if (predicate(t)) {
yield return t;
}
}
}
```
Note that `Where` is an extension method. You are essentially calling `Where(customerList, c => c.Age > 30)`. Now you should see where it gets access of the `customerList`. It also infers what `T` should be by looking at what kind of `IEnumerable` `customerList` is. Since it is a `IEnumerable<Customer>`, `T` is `Customer`, and so it expects a `Func<Customer, bool>` for the second argument. This is how it knows that `c` is `Customer`.
`Where` does not return a temporary list. A lot of LINQ methods make use of deferred evaluation. `Where` returns an `IEnumerable<Customer>` that is filtered. Remember that `IEnumerable` is just a sequence of things. This sequence returned by `Where` however, is not evaluated, until you ask for it. `Select` does the same as well. So a list is not created until you call `ToList`.
Your third question is kind of like asking "How does `Where` know how to filter" or "How does `Console.WriteLine` know how to write to the screen". That's what `Select` does. You can look at its implementation if you want. Here's a rough sketch:
```
public static IEnumerable<U> Select<T, U>(this IEnumerable<T> source, Func<T, U> mapping) {
foreach (T t in source) {
yield mapping(t);
}
}
```
The type of the variable `salaries` is determined by looking at the method signatures of each of the methods you call. Your `Select` call returns a `IEnumerable<long>`, and `ToList`'s signature tells the compiler that, given a `IEnumerable<T>` it will return `List<T>`, so in this case, it returns a `List<long>`.
|
The [link from @Amit](https://stackoverflow.com/questions/671235/how-linq-works-internally/671425#671425) can give a good idea.
Short answer is that LINQ is built on the compiler feature called Expressions. When you write something like `Where(c => c.Age > 18)` compiler doesn't actually compile the `c=> c.Age > 18` all the way like a regular method.
It builds a syntax tree that describes what that code does.
The `Where` function uses this to build a SQL query that is sent to the SQL server which executes that to get the results.
Suggest you look into the workings of [`IQueryable`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.iqueryable?view=netcore-3.0) and [`Expression<TDelegate>`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression-1?view=netcore-3.0) for more information.
Also helps to understand the [difference between IEnumerable and IQueryable](https://stackoverflow.com/q/252785/975887).
Another example of Expressions used in other parts of C# like Razor pages that uses functions like [LabelFor(...)](https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.html.labelextensions.labelfor?view=aspnet-mvc-5.2) which uses the property you *express* to build a HTML label rather than executing the code.
HTH
|
593,376 |
I am currently studying electricity in my physics class, and am really confused about electric potential in a uniform electric field, like the one pictured. [](https://i.stack.imgur.com/y0Wmj.png)
What I don't understand is, how come many textbooks say that the electric potential at the negative plate is zero. The equation for electric potential is $V=kq/r$, so as a positive test charge gets closer and closer to the negative plate, wouldn't the electric potential be a huge negative number, because the radius is decreasing and the plate is negative? Please help me understand!
|
2020/11/12
|
[
"https://physics.stackexchange.com/questions/593376",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/276079/"
] |
>
> The equation for electric potential is V=kq/r
>
>
>
Only for a point charge.
>
> so as a positive test charge gets closer and closer to the negative plate, wouldn't the electric potential be a huge negative number, because the radius is decreasing and the plate is negative? Please help me understand!
>
>
>
If you consider point charges then they cause discontinuities in an electric field (eg: potential where they are located r=0, is a blow-up) however if you have a smooth distribution of charge, there are no such blow-ups.
>
> , how come many textbooks say that the electric potential at the negative plate is zero.
>
>
>
Irrelevant what the potential at the negative plate is, all that is important is the **potential difference** between plates. You can increase the potential on both plates by any amount you want and the difference would still be preserved.
---
**Comments** : A nice EM textbook [here](https://physics.info/)
|
The only quantity related to potential that is ever relevant to an electrostatics problem is *potential difference*. That is the difference between potential between two points. Because of that it doesn't matter where you set the potential to be zero.
Concerning the huge negative number: no, while the potential of a point charge approaches infinity, the potential is finite at a charged *surface*. This is because the electric field is constant near the surface. If doubt that, I'm sure it will be made clear to you soon as your course progresses.
|
593,376 |
I am currently studying electricity in my physics class, and am really confused about electric potential in a uniform electric field, like the one pictured. [](https://i.stack.imgur.com/y0Wmj.png)
What I don't understand is, how come many textbooks say that the electric potential at the negative plate is zero. The equation for electric potential is $V=kq/r$, so as a positive test charge gets closer and closer to the negative plate, wouldn't the electric potential be a huge negative number, because the radius is decreasing and the plate is negative? Please help me understand!
|
2020/11/12
|
[
"https://physics.stackexchange.com/questions/593376",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/276079/"
] |
>
> The equation for electric potential is V=kq/r
>
>
>
Only for a point charge.
>
> so as a positive test charge gets closer and closer to the negative plate, wouldn't the electric potential be a huge negative number, because the radius is decreasing and the plate is negative? Please help me understand!
>
>
>
If you consider point charges then they cause discontinuities in an electric field (eg: potential where they are located r=0, is a blow-up) however if you have a smooth distribution of charge, there are no such blow-ups.
>
> , how come many textbooks say that the electric potential at the negative plate is zero.
>
>
>
Irrelevant what the potential at the negative plate is, all that is important is the **potential difference** between plates. You can increase the potential on both plates by any amount you want and the difference would still be preserved.
---
**Comments** : A nice EM textbook [here](https://physics.info/)
|
The fact you can not define the potential at a point. All you can do is to define a potential difference between two points. In your figure, They have taken zero potential at the negative plate, and relative to this point they have written the potential at other point.
And this make sense, How? We know that charge will flow from high to low potential and thus If you put a charge near positive plate it will go towards the negative plate. That's exactly you would expect.
|
593,376 |
I am currently studying electricity in my physics class, and am really confused about electric potential in a uniform electric field, like the one pictured. [](https://i.stack.imgur.com/y0Wmj.png)
What I don't understand is, how come many textbooks say that the electric potential at the negative plate is zero. The equation for electric potential is $V=kq/r$, so as a positive test charge gets closer and closer to the negative plate, wouldn't the electric potential be a huge negative number, because the radius is decreasing and the plate is negative? Please help me understand!
|
2020/11/12
|
[
"https://physics.stackexchange.com/questions/593376",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/276079/"
] |
>
> The equation for electric potential is V=kq/r
>
>
>
Only for a point charge.
>
> so as a positive test charge gets closer and closer to the negative plate, wouldn't the electric potential be a huge negative number, because the radius is decreasing and the plate is negative? Please help me understand!
>
>
>
If you consider point charges then they cause discontinuities in an electric field (eg: potential where they are located r=0, is a blow-up) however if you have a smooth distribution of charge, there are no such blow-ups.
>
> , how come many textbooks say that the electric potential at the negative plate is zero.
>
>
>
Irrelevant what the potential at the negative plate is, all that is important is the **potential difference** between plates. You can increase the potential on both plates by any amount you want and the difference would still be preserved.
---
**Comments** : A nice EM textbook [here](https://physics.info/)
|
You are correct. Strictly the potential of a stationary pont charge is kq/r so the potential at infinity should be zero. However, you can add a constant potential to any system without physical consequences. This allows you to redefine the potential such that it is zero at one of the plates.
|
593,376 |
I am currently studying electricity in my physics class, and am really confused about electric potential in a uniform electric field, like the one pictured. [](https://i.stack.imgur.com/y0Wmj.png)
What I don't understand is, how come many textbooks say that the electric potential at the negative plate is zero. The equation for electric potential is $V=kq/r$, so as a positive test charge gets closer and closer to the negative plate, wouldn't the electric potential be a huge negative number, because the radius is decreasing and the plate is negative? Please help me understand!
|
2020/11/12
|
[
"https://physics.stackexchange.com/questions/593376",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/276079/"
] |
>
> The equation for electric potential is V=kq/r
>
>
>
Only for a point charge.
>
> so as a positive test charge gets closer and closer to the negative plate, wouldn't the electric potential be a huge negative number, because the radius is decreasing and the plate is negative? Please help me understand!
>
>
>
If you consider point charges then they cause discontinuities in an electric field (eg: potential where they are located r=0, is a blow-up) however if you have a smooth distribution of charge, there are no such blow-ups.
>
> , how come many textbooks say that the electric potential at the negative plate is zero.
>
>
>
Irrelevant what the potential at the negative plate is, all that is important is the **potential difference** between plates. You can increase the potential on both plates by any amount you want and the difference would still be preserved.
---
**Comments** : A nice EM textbook [here](https://physics.info/)
|
allow me to explain a couple of concepts.
Firstly, you must understand what electric potential is. It is an abstract concept. A helpful way to think about it is by considering it's unit, that is Joules/Couloumb. That tells us that electric potential shows us the **potential energy per unit charge**. It is simply a number associated with a point in space. unlike electric potential energy, it isn't fixed number but changes depending on what we compare it to.
To calculate electric potential, we need a point of comparison, where we assume the potential is 0. Usually this is taken as infinity. However, it's fairly common to consider an actual point (in this case, the negatively charged plate) as a 'zero potential' point. We then just measure the electric potential of other points in comparison to this 0 potential point.
It's the equivalent of measuring height in the following way. lets say I have a pole that's 10 metres long and stick it in the ground. if we take the ground as 0m, then the the top of thevpole is 10 m above that.
if we take a point halfway up the pole as our point of comparison instead, then the top of the pole is 5 m above that reference point.
Another example: when you want to measure the length of a line drawn on a page by a pencil, you bust out a ruler. You place the 0 mark at the beginning of the line, and you check how long it is by seeing where the line ends **with reference to the 0 mark**. if it ends at 15cm, the line is 15cm long. If instead we placed the 5 cm mark at the beginning, the line would end at 20cm. we now have a different point of reference, but the line is still the same length See how that works? you need a point of reference to measure things.
In your case, they've simply stated that you are to consider the negatively charged plate to be at an electric potential of 0V. the electric potential of any other point in this system is then measured in comparison to this zero.
You must also consider the sign of the test charge in question (positive or negative)
In the arrangement that you have shown in the photo, a positive charge +q placed near the positively charged plate would have a high electric potential, as it would be strongly repelled by the plate. if it were able to move, it would move away from the plate at a high velocity. It would move in the direction of the negatively charged plate, which for +q would be at a lower potential.
Another thing you must know is that electric potential is not kq/r for all charges. V = kq/r is only true for a point charge q, and is different for different charge distributions. In the photo that you have displayed, the charges are distributed on charged plates. Here kq/r cannot be used to calculate the potential due to the plates. You would have to use V = - ∫ E. dl
If this helped, remember to please upvote and tick the answer :)
|
3,945,233 |
What's the point of using template structure like this:
```
templates/
app/
article_view.html # or view_article.html
category_view.html
```
vs
```
templates/
app/
article/
view.html
category/
view.html
```
It's easier to find particular template with second approach, but I almost don't see any apps using it. Why?
|
2010/10/15
|
[
"https://Stackoverflow.com/questions/3945233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268774/"
] |
This depends on the scale of the project; a small-scale thingie could be more easy to handle with the first approach, while a project with several hundred template files could use a better folder structure, i.e. the second approach
|
Generally speaking, templates are associated with views rather than models. A view pulls in one or more models as needed, then renders the appropriate template. Since an app usually consolidates views in one file, the template to app correspondence works well enough.
|
27,853,657 |
I am aware that there is a similar question to this [here](https://stackoverflow.com/questions/16188836/avoid-instanceof-in-a-composite-pattern). It considered a more generic question of class specific behaviour than my question here.
Consider the following simple implementation of a Composite pattern:
```
interface Item {
int getWeight();
}
class SimpleItem implements Item {
private int weight;
public int getWeight() {
return weight;
}
}
class Container implements Item {
private List<Item> items;
private int weight;
public void add(Item item) {
items.add(item);
}
public int getWeight() {
return weight + items.stream().mapToInt(Item::getWeight).sum();
}
}
```
Now consider how a user of Item can determine whether it is a container. For example a method is required in Container `pushAdd` that pushes an item down the hierarchy to a container that has no containers inside it. The container only knows about Items, it doesn't know if those items are Containers or SimpleItems or some other class that implements Item.
There are three potential solutions:
1.
Using instance of and casting
```
public void pushAdd(Item item) {
Optional<Container> childContainer = items.stream()
.filter(item instanceof Container)
.map(item -> (Container)item)
.findAny();
if (childContainer.isPresent()) {
childContainer.get().pushAdd(item);
} else {
add(item);
}
}
```
2.
Implement is/as methods
```
public pushAdd(Item item) {
Optional<Container> childContainer = items.stream()
.filter(Item::isContainer)
.map(Item::asContainer);
....
}
```
3.
Visitor pattern (I've omitted the simple `accept` implementation).
```
interface ItemVisitor {
default void visit(SimpleItem simpleItem) { throw ...}
default void visit(Container container) { throw ... };
}
public pushAdd(Item item) {
Optional<Container> childContainer = ... (using instanceOf);
if (childContainer.isPresent()) {
childContainer.get().accept(new ItemVisitor(item) {
void visit(Container container) {
container.pushAdd(item);
}
};
} else {
add(item);
}
}
```
The first is evil because it uses instanceof and casting. The second is evil because it forces knowledge of Container into Item - and it gets a lot worse when other subclasses of item are created. The third doesn't help you know whether you can add to the Item before calling the visitor. You can catch the exception but that seems to be a misuse of exceptions to me: much better to have a way to check before visiting.
So my question is: is there another pattern I can use to avoid casts and instanceof without having to push knowledge of subclasses up the hierarchy?
|
2015/01/09
|
[
"https://Stackoverflow.com/questions/27853657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3705127/"
] |
I think I speak for any java person when I say that the visitor pattern is not exactly popular in java. So the above could be implemented like this (I will use interfaces here because in my experience they are more flexible):
```
interface Item { /* methods omitted */ }
interface SimpleItem extends Item { /* methods omitted */ }
interface ContainerItem extends Item { /* methods omitted */ }
// telling clients that this can throw an exception or not
// here is a whole different design question :)
interface ItemVisitor { void visit(Item i) /* throws Exception */; }
class MyVisitor implements ItemVisitor {
void visit(Item i) {
if (i instanceof SimpleItem) {
// handle simple items
} else if (i instanceof ContainerItem) {
// handle containers using container specific methods
} else {
// either throw or ignore, depending on the specifications
}
}
}
```
The cost of `instanceof` is pretty low on the latest JVM so I would not worry about that too much, unless you can prove that the traditional visitor is considerably faster.
The readability and maintainability of the code is arguably identical, with a few differences. First of all, if a new interface is added to the hierarchy that does *not* modify existing visitors, those visitors don't need to be changed. On the other hand, it's easier to overlook a visitor that *does* need to be changed (especially in client code that you don't control) because the visitor does not explicitly require clients to do so, but, hey that's the nature of maintaining code and the general shortcoming of a design that requires visiting.
Another advantage of this pattern is that clients that don't need visiting don't need to worry about it (there's no `accept` method), i.e., a shorter learning curve.
Finally, I think this pattern is closer to the "purist" OOD in the sense that the interface hierarchy does not contain spurious methods (`visit`, `canAddItems`, etc.), i.e., there are [no "tags"](http://jtechies.blogspot.com/2012/07/item-20-prefer-class-hierarchies-to.html) of sorts.
|
Well it seems from the fact that no one has posted an answer that there are no better options than the 3 I put up.
So I'll post my preferred solution and see if anyone can improve on it. In my view the best option is a combination of options 2 and 3. I don't think it's too evil to have a `canAddItems` member of `Item` - it's arguable that it's reasonable that implementers of Item tell you if you can add Items to them. But visitors seem like a good way of hiding the details of how to items are added.
So, fwiw this is my best compromise to the problem I posed. I'm still not 100% happy with it. In particular the visitor to add items will break if another class is implemented that can add items. But that's probably what you want because it's changing the semantics of pushAdd.
```
interface Item {
int getWeight();
void accept(ItemVisitor visitor);
default boolean canAddItems() {
return false;
}
}
interface ItemVisitor {
default void visit(SimpleItem simpleItem) {
throw new IllegalArgumentException("ItemVisitor does not accept SimpleItem");
}
default void visit(Container container) {
throw new IllegalArgumentException("ItemVisitor does not accept Container");
}
}
class SimpleItem implements Item {
private int weight;
public int getWeight() {
return weight;
}
public void accept(ItemVisitor visitor) {
visitor.visit(this);
}
}
class Container implements Item {
private List<Item> items;
private int weight;
public void add(Item item) {
items.add(item);
}
public int getWeight() {
return weight + items.stream().mapToInt(Item::getWeight).sum();
}
public void accept(ItemVisitor visitor) {
visitor.visit(this);
}
public void pushAdd(Item item) {
Optional<Item> child = items.stream().filter(Item::canAddItems).findAny();
if (child.isPresent()) {
child.get().accept(new ItemVisitor() {
public void visit(Container container) {
container.add(item);
}
});
} else {
add(item);
}
}
}
```
|
281,877 |
In No Man's Sky planets and animals are found by the community and registered centrally. Is there a system such as an interstellar map for planets, or a "pokedex" for discovered animals by the community, so that I can view them and possibly plot a course for them?
Similarly, is it possible to view which animals I will encounter on a planet before landing on it?
|
2016/08/15
|
[
"https://gaming.stackexchange.com/questions/281877",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/152693/"
] |
There is currently no online list available to the public - based on countless efforts to find one.
However, we do know that the [Hello Games team knows exactly what everyone has discovered and named](https://twitter.com/NoMansSky/status/762691001198796800). This could mean that eventually the Hello Games team will release either an API to retrieve information from their database to create a list of discovered galaxies, planets, moons, animals, plants etc. OR they will be making one themselves (based on the link, my best bet is they are already making a website or app of some sort).
YET, just because they do know what everyone has discovered, does not mean they want to share this information. I don't know how Sean's mind works, eh.
(Sean if you're reading this make it happen please..)
|
The animal catalog, I'm not seeing one. You can see what discoveries you've made, in the interstellar map, to access it you have to be in space, and then press `M` or `dpad down`.
From the galactic map you can then scan for discoveries, which will list systems you've already discovered, however it will not list the animal species on the planets in those systems.
[Also, be aware there are some issues with the galactic scan, as documented in this answer](https://gaming.stackexchange.com/a/281065/5357).
*My Suggestion to Hello Games*
If I were Sean I'd have all of the uploads be automatically filling out wiki pages. Using a tree structure it could be easily organized. If they included gps cordinates (or however you'd measure location of planets) they could then build a web browser map using the wikiverse platform. Making all discoveries searchable, and easy to navigate. Eventually allowing you to search for a friend and add a waypoint on one of their galaxies.
|
25,039,084 |
Say I have three div's which contain unique content;
* div1 = Is a Photoshop guide
* div2 = Contains a gallery of images
* div3 = Lists personal contact details
When my page loads they all need to be hidden;
* div1 = hidden
* div2 = hidden
* div3 = hidden
They are also laid ontop of one another (occupy the same space having the same width, but varying heights).
There's a horizontal menu above these divs that trigger their visbilities;
| View 1 | View 2 | View 3 |
If a user clicks 'View 1', div1 becomes visible;
* div1 = visible
* div2 = hidden
* div3 = hidden
If a user clicks 'View 2', only div2 is visible;
* div1 = hidden
* div2 = visible
* div3 = hidden
And the same for clicking 'View 3';
* div1 = hidden
* div2 = hidden
* div3 = visible
My current solution is available via JSFiddle here;
<http://jsfiddle.net/t6cU4/>
only using check-boxes and opacity settings with `<div>`, `<label>` and `<input>`
How do I go about this using only HTML and CSS (no scripts) in the smallest way possible?
* What I'm trying to achieve is a singular page design, where no external pages are used
* A background (or active) style would also be of use for the menu items (so the user knows which div they are viewing)
* The problem with the current solution is that the labels and have no selection effect and the divs do not overlap (they appear below each other like a list inside of overlapping). The logo also disappears along with item 3 when clicking a label
|
2014/07/30
|
[
"https://Stackoverflow.com/questions/25039084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3887181/"
] |
The trick is add a `<label>` tag after a `<input type="checkbox">` and in CSS, add the selector `:checked` for the input, like a trigger.
**HTML**
```
<input class="trigger" id="1" type="checkbox">
<label for="1">Click me</label>
<div>Surprise!</div>
<br><br>
<input class="trigger" id="2" type="checkbox">
<label for="2">Click me too</label>
<div>Surprise again!</div>
```
**CSS**
```
.trigger + label + div /*This selects the div that is placed after a label that's after a element with 'trigger' class*/
{
display:none; /*hiding the element*/
}
.trigger /*This selects a element with class 'trigger'*/
{
display:none; /*hiding the element*/
}
.trigger:checked + label + div /*This selects the div that is placed after a label that's after a CHECKED input with class 'trigger'*/
{
display:block; /*showing the element*/
}
```
***[See Working Fiddle](http://jsfiddle.net/HN9am/)
------------------------------------------------***
Or
***### [See Fiddle With Explanations](http://jsfiddle.net/HN9am/2/)***
07.30.2014 - UPDATE:
--------------------
You said you want the divs appearing without any menu deformations, right? Try to put all `<div>`'s in the bottom and put every corresponding `<input>` before that. The labels stay on top.
Just like that:
```
<label for="1">Click me</label>
<label for="2">Click me too</label>
<br/><br/>
<input class="trigger" id="1" type="checkbox"/>
<div class="cont"><strong>1st Title</strong><br/>And 1st content.</div>
<input class="trigger" id="2" type="checkbox"/>
<div class="cont"><strong>2nd Title</strong><br/>And 2nd content.</div>
```
and in CSS:
```
.trigger:checked + div {
display:block;
}
```
[### -> See new Fiddle <-](http://jsfiddle.net/HN9am/4/)
***(Sorry if my english is bad)***
|
Try different CSS menus. You can grab a lot from google.
Here are some samples collected from web:
```
http://www.smashingapps.com/2013/02/18/48-free-dropdown-menu-in-html5-and-css3.html
http://css3menu.com/enterprise-green.html
```
|
45,188,043 |
While typing code in XCode i have found the word LIST\_FOREACH. what is the purpose of LIST\_FOREACH in XCode? why its displayed?
Since there is no other function such as foreach in XCode - Objective C,then what is the use of LIST\_FOREACH?
Can anyone teach me what's the purpose of LIST\_FOREACH in Objective-c?.When there is no foreach concept in Objective-c
Any answer is welcome :)
|
2017/07/19
|
[
"https://Stackoverflow.com/questions/45188043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2455574/"
] |
**For your information there is no loop like foreach in objective or swift, like c# or other language.**
But the same can be achieved by the following code
```
NSArray *a = [NSArray new]; // Any container class can be substituted
for(id obj in a) { // Note the dynamic typing (we do not need to know the
// Type of object stored in 'a'. In fact, there can be
// many different types of object in the array.
printf("%s\n", [[obj description] UTF8String]); // Must use UTF8String with %s
NSLog(@"%@", obj); // Leave as an object
}
```
|
Are you attempting to do Fast Enumeration on arrays? You can do it as -
```
for (id tempObject in myArray) {
NSLog(@"Single element: %@", tempObject);
}
```
|
45,188,043 |
While typing code in XCode i have found the word LIST\_FOREACH. what is the purpose of LIST\_FOREACH in XCode? why its displayed?
Since there is no other function such as foreach in XCode - Objective C,then what is the use of LIST\_FOREACH?
Can anyone teach me what's the purpose of LIST\_FOREACH in Objective-c?.When there is no foreach concept in Objective-c
Any answer is welcome :)
|
2017/07/19
|
[
"https://Stackoverflow.com/questions/45188043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2455574/"
] |
**For your information there is no loop like foreach in objective or swift, like c# or other language.**
But the same can be achieved by the following code
```
NSArray *a = [NSArray new]; // Any container class can be substituted
for(id obj in a) { // Note the dynamic typing (we do not need to know the
// Type of object stored in 'a'. In fact, there can be
// many different types of object in the array.
printf("%s\n", [[obj description] UTF8String]); // Must use UTF8String with %s
NSLog(@"%@", obj); // Leave as an object
}
```
|
Syntex of Fast Enumeration:
```
for (NSString* key in xyz) {
id value = [xyz objectForKey:key];
// do stuff
}
```
For more info:
>
> <https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Collections/Articles/Enumerators.html>
>
>
>
|
13,069 |
I have a data frame which has three columns as shown below. There are about 10,000 entries in the data frame and there are duplicates as well.
```
Hospital_ID District_ID Employee
Hospital 1 District 19 5
Hospital 1 District 19 10
Hospital 1 District 19 6
Hospital 2 District 10 50
Hospital 2 District 10 51
```
Now I want to remove the duplicates but I want to replace the values in my original data frame by their mean so that it should look like this:
```
Hospital 1 District 19 7.0000
Hospital 2 District 10 50.5000
```
|
2016/07/29
|
[
"https://datascience.stackexchange.com/questions/13069",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/15412/"
] |
As [Emre](https://datascience.stackexchange.com/users/381/emre) already mentioned, you may use the [groupby](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) function. After that, you should apply [reset\_index](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html) to move the MultiIndex to the columns:
```
import pandas as pd
df = pd.DataFrame( [ ['Hospital 1', 'District 19', 5],
['Hospital 1', 'District 19', 10],
['Hospital 1', 'District 19', 6],
['Hospital 2', 'District 10', 50],
['Hospital 2', 'District 10', 51]], columns = ['Hospital_ID', 'District_ID', 'Employee'] )
df = df.groupby( ['Hospital_ID', 'District_ID'] ).mean()
```
which gives you:
```
Hospital_ID District_ID Employee
0 Hospital 1 District 19 7.0
1 Hospital 2 District 10 50.5
```
|
What you want to do is called [aggregation](https://en.wikipedia.org/wiki/Aggregate_function); deduplication or duplicate removal is something else. I think the code self-explanatory:
`df.groupby(['Hospital_ID', 'District_ID']).mean()`
|
34,553,596 |
My html is like:
```
<a class="title" href="">
<b>name
<span class="c-gray">position</span>
</b>
</a>
```
I want to get name and position string separately. So my script is like:
```
lia = soup.find('a',attrs={'class':'title'})
pos = lia.find('span').get_text()
lia.find('span').replace_with('')
name = lia.get_text()
print name.strip()+','+pos
```
Although it can do the job, I don't think is a beautiful way. Any brighter idea?
|
2016/01/01
|
[
"https://Stackoverflow.com/questions/34553596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3145081/"
] |
You can use `.contents` method this way:
```
person = lia.find('b').contents
name = person[0].strip()
position = person[1].text
```
|
The idea is to locate the `a` element, then, for the `name` - get the first text node from an inner `b` element and, for the `position` - get the `span` element's text:
```
>>> a = soup.find("a", class_="title")
>>> name, position = a.b.find(text=True).strip(), a.b.span.get_text(strip=True)
>>> name, position
(u'name', u'position')
```
|
60,380,110 |
After update to Angular 9 it does not work to use Hammer.js anymore. We have extended the Angular `HammerGestureConfig` like the following.:
```js
import {HammerGestureConfig} from '@angular/platform-browser';
import {Injectable} from '@angular/core';
@Injectable({providedIn: 'root'})
export class HammerConfig extends HammerGestureConfig {
overrides = <any>{
'pan': {
direction: Hammer.DIRECTION_ALL,
threshold: 5
} // override default settings
};
buildHammer(element) {
const recognizers = [];
if (element.hasAttribute('data-hammer-pan')) {
recognizers.push([Hammer.Pan]);
}
if (element.hasAttribute('data-hammer-pan-x')) {
recognizers.push([Hammer.Pan, {direction: Hammer.DIRECTION_HORIZONTAL}]);
}
if (element.hasAttribute('data-hammer-tap')) {
recognizers.push([Hammer.Tap]);
}
if (element.hasAttribute('data-hammer-pinch')) {
recognizers.push([Hammer.Pinch]);
}
if (element.hasAttribute('data-hammer-rotate')) {
recognizers.push([Hammer.Rotate]);
}
if (element.hasAttribute('data-hammer-press')) {
recognizers.push([Hammer.Press]);
}
if (element.hasAttribute('data-hammer-swipe')) {
recognizers.push([Hammer.Swipe]);
}
const hammer = new Hammer.Manager(element, {
recognizers: recognizers,
touchAction: 'auto'
});
return hammer;
}
}
```
The `HammerConfig` is added to the app module.:
```js
providers: [
{
provide: HAMMER_GESTURE_CONFIG,
useClass: HammerConfig
}
],
```
As far as I understand the method `buildHammer` should be called, but it is never called.
What could be the problem?
|
2020/02/24
|
[
"https://Stackoverflow.com/questions/60380110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183704/"
] |
The `HammerModule` needs to be imported to the Angular app module.
```js
imports: [
...
HammerModule
],
providers: [
{
provide: HAMMER_GESTURE_CONFIG,
useClass: HammerConfig
},
...
],
...
```
>
> ivy: make Hammer support tree-shakable. Previously, in Ivy
> applications, Hammer providers were included by default. With this
> commit, apps that want Hammer support must import `HammerModule` in their
> root module. ([#32203](http://ivy:%20make%20Hammer%20support%20tree-shakable.%20Previously,%20in%20Ivy%20applications,%20Hammer%20providers%20were%20included%20by%20default.%20With%20this%20commit,%20apps%20that%20want%20Hammer%20support%20must%20import%20HammerModulein%20their%20root%20module.%20(#32203)%20(de8ebbd))) ([de8ebbd](https://github.com/angular/angular/commit/de8ebbd))
>
>
>
<https://github.com/angular/angular/blob/9.0.0/CHANGELOG.md>
|
After upgrading to Angular 9, I had to re-npm-install `hammerjs` since it had been removed from my `package.json`. I would check that yours is still there.
|
60,380,110 |
After update to Angular 9 it does not work to use Hammer.js anymore. We have extended the Angular `HammerGestureConfig` like the following.:
```js
import {HammerGestureConfig} from '@angular/platform-browser';
import {Injectable} from '@angular/core';
@Injectable({providedIn: 'root'})
export class HammerConfig extends HammerGestureConfig {
overrides = <any>{
'pan': {
direction: Hammer.DIRECTION_ALL,
threshold: 5
} // override default settings
};
buildHammer(element) {
const recognizers = [];
if (element.hasAttribute('data-hammer-pan')) {
recognizers.push([Hammer.Pan]);
}
if (element.hasAttribute('data-hammer-pan-x')) {
recognizers.push([Hammer.Pan, {direction: Hammer.DIRECTION_HORIZONTAL}]);
}
if (element.hasAttribute('data-hammer-tap')) {
recognizers.push([Hammer.Tap]);
}
if (element.hasAttribute('data-hammer-pinch')) {
recognizers.push([Hammer.Pinch]);
}
if (element.hasAttribute('data-hammer-rotate')) {
recognizers.push([Hammer.Rotate]);
}
if (element.hasAttribute('data-hammer-press')) {
recognizers.push([Hammer.Press]);
}
if (element.hasAttribute('data-hammer-swipe')) {
recognizers.push([Hammer.Swipe]);
}
const hammer = new Hammer.Manager(element, {
recognizers: recognizers,
touchAction: 'auto'
});
return hammer;
}
}
```
The `HammerConfig` is added to the app module.:
```js
providers: [
{
provide: HAMMER_GESTURE_CONFIG,
useClass: HammerConfig
}
],
```
As far as I understand the method `buildHammer` should be called, but it is never called.
What could be the problem?
|
2020/02/24
|
[
"https://Stackoverflow.com/questions/60380110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183704/"
] |
Comment out any imports for hammerjs that are likely in your main.ts file that were likely added in Angular 8 or earlier -- for me it was originally an Angular 4 project 2 years old that we have evolved. But Angular 9 can't use it there.
Move them all to app.module.ts in this order…
```
import { HammerModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';
declare var Hammer: any;
```
If you are using it for swipes, like for a carousel, you will need to export a custom class...
```js
@Injectable()
export class MyHammerConfig extends HammerGestureConfig {
overrides = <any>{
pan: { direction: Hammer.DIRECTION_All },
swipe: { direction: Hammer.DIRECTION_VERTICAL },
}
buildHammer(element: HTMLElement) {
const mc = new Hammer(element, {
touchAction: 'auto',
inputClass: Hammer.SUPPORT_POINTER_EVENTS ? Hammer.PointerEventInput : Hammer.TouchInput,
recognizers: [
[
Hammer.Swipe,
{
direction: Hammer.DIRECTION_HORIZONTAL,
},
],
],
})
return mc
}
}
```
Then in NgModule
```js
@NgModule({
// ...
imports: [
HammerModule,
// ...
```
don't forget the providers...
```js
providers: [
{provide: HAMMER_GESTURE_CONFIG, useClass: MyHammerConfig}
// ...
]
```
It should work.
|
After upgrading to Angular 9, I had to re-npm-install `hammerjs` since it had been removed from my `package.json`. I would check that yours is still there.
|
60,380,110 |
After update to Angular 9 it does not work to use Hammer.js anymore. We have extended the Angular `HammerGestureConfig` like the following.:
```js
import {HammerGestureConfig} from '@angular/platform-browser';
import {Injectable} from '@angular/core';
@Injectable({providedIn: 'root'})
export class HammerConfig extends HammerGestureConfig {
overrides = <any>{
'pan': {
direction: Hammer.DIRECTION_ALL,
threshold: 5
} // override default settings
};
buildHammer(element) {
const recognizers = [];
if (element.hasAttribute('data-hammer-pan')) {
recognizers.push([Hammer.Pan]);
}
if (element.hasAttribute('data-hammer-pan-x')) {
recognizers.push([Hammer.Pan, {direction: Hammer.DIRECTION_HORIZONTAL}]);
}
if (element.hasAttribute('data-hammer-tap')) {
recognizers.push([Hammer.Tap]);
}
if (element.hasAttribute('data-hammer-pinch')) {
recognizers.push([Hammer.Pinch]);
}
if (element.hasAttribute('data-hammer-rotate')) {
recognizers.push([Hammer.Rotate]);
}
if (element.hasAttribute('data-hammer-press')) {
recognizers.push([Hammer.Press]);
}
if (element.hasAttribute('data-hammer-swipe')) {
recognizers.push([Hammer.Swipe]);
}
const hammer = new Hammer.Manager(element, {
recognizers: recognizers,
touchAction: 'auto'
});
return hammer;
}
}
```
The `HammerConfig` is added to the app module.:
```js
providers: [
{
provide: HAMMER_GESTURE_CONFIG,
useClass: HammerConfig
}
],
```
As far as I understand the method `buildHammer` should be called, but it is never called.
What could be the problem?
|
2020/02/24
|
[
"https://Stackoverflow.com/questions/60380110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183704/"
] |
The `HammerModule` needs to be imported to the Angular app module.
```js
imports: [
...
HammerModule
],
providers: [
{
provide: HAMMER_GESTURE_CONFIG,
useClass: HammerConfig
},
...
],
...
```
>
> ivy: make Hammer support tree-shakable. Previously, in Ivy
> applications, Hammer providers were included by default. With this
> commit, apps that want Hammer support must import `HammerModule` in their
> root module. ([#32203](http://ivy:%20make%20Hammer%20support%20tree-shakable.%20Previously,%20in%20Ivy%20applications,%20Hammer%20providers%20were%20included%20by%20default.%20With%20this%20commit,%20apps%20that%20want%20Hammer%20support%20must%20import%20HammerModulein%20their%20root%20module.%20(#32203)%20(de8ebbd))) ([de8ebbd](https://github.com/angular/angular/commit/de8ebbd))
>
>
>
<https://github.com/angular/angular/blob/9.0.0/CHANGELOG.md>
|
Comment out any imports for hammerjs that are likely in your main.ts file that were likely added in Angular 8 or earlier -- for me it was originally an Angular 4 project 2 years old that we have evolved. But Angular 9 can't use it there.
Move them all to app.module.ts in this order…
```
import { HammerModule, HammerGestureConfig, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';
declare var Hammer: any;
```
If you are using it for swipes, like for a carousel, you will need to export a custom class...
```js
@Injectable()
export class MyHammerConfig extends HammerGestureConfig {
overrides = <any>{
pan: { direction: Hammer.DIRECTION_All },
swipe: { direction: Hammer.DIRECTION_VERTICAL },
}
buildHammer(element: HTMLElement) {
const mc = new Hammer(element, {
touchAction: 'auto',
inputClass: Hammer.SUPPORT_POINTER_EVENTS ? Hammer.PointerEventInput : Hammer.TouchInput,
recognizers: [
[
Hammer.Swipe,
{
direction: Hammer.DIRECTION_HORIZONTAL,
},
],
],
})
return mc
}
}
```
Then in NgModule
```js
@NgModule({
// ...
imports: [
HammerModule,
// ...
```
don't forget the providers...
```js
providers: [
{provide: HAMMER_GESTURE_CONFIG, useClass: MyHammerConfig}
// ...
]
```
It should work.
|
2,546,295 |
I have two projects in my Solution. One implements my business logic and has defined entity model of entity framework. When I want to work with classes defined within this project from another project I have some problems in runtime. Actually, the most concerning thing is why I can not instantiate my, so called, TicketEntities(ObjectContext) object from other projects? when I catch following exception:
`The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.`
I found out it's brake at:
```
public partial class TicketEntities : global::System.Data.Objects.ObjectContext
{
public TicketEntities() :
base("name=TicketEntities", "TicketEntities")
{
this.OnContextCreated();
}
```
with exception: Unable to load the specified metadata resource.
Just to remind you everthing works fine from orginal project.
|
2010/03/30
|
[
"https://Stackoverflow.com/questions/2546295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255623/"
] |
You need to copy the Connection string from the original app.config or web.config into the corresponding app.config / web.config in the new project.
Then everything should work.
Alex
|
Think about how you will make the treatment of transaction and make use the same connection between classes.
|
14,209,145 |
I have a UITableViewController that shows a list of items from NSMutableArray, along with a button that serves as a check box that the user can select/deselect. I am able to successfully display the table, as well as the checkboxes. However, I would like to have a tableheader at the very top of the table that would have a "select all" check box, which would allow the user to select all of the cells, or deselect all of the cells. If some cells are already checked off, then I want only those cells that are not selected, to be selected.
Here is the code that I have thus far:
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
testButton = [UIButton buttonWithType:UIButtonTypeCustom];
[testButton setFrame:CGRectMake(280, 57, 25, 25)];
[testButton setImage:[UIImage imageNamed:@"CheckBox1.png"] forState:UIControlStateSelected];
[testButton setImage:[UIImage imageNamed:@"CheckBox2.png"] forState:UIControlStateNormal];
[testButton setUserInteractionEnabled:YES];
[testButton addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
[cell setAccessoryView:testButton];
}
// Configure the cell...
TestObject *tObject = [[DataModel sharedInstance].testList objectAtIndex:indexPath.row];
cell.textLabel.text = tObject.testTitle;
return cell;
}
-(void)buttonTouched:(id)sender
{
UIButton *btn = (UIButton *)sender;
if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"CheckBox1.png"]])
{
[btn setImage:[UIImage imageNamed:@"CheckBox2.png"] forState:UIControlStateNormal];
// other statements
}
else
{
[btn setImage:[UIImage imageNamed:@"CheckBox1.png"] forState:UIControlStateNormal];
// other statements
}
}
//Here is the additional method that I have added to my code to select all
-(void)clickOnCheckButton {
NSLog(@"Did it select?");
for (int i = 0; i < [self.tableView numberOfSections]; i++) {
for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
NSUInteger ints[2] = {i,j};
NSIndexPath *indexPath = [NSIndexPath indexPathWithIndexes:ints length:2];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//Here is your code
[self buttonTouched:nil];
}
}
}
```
Does anyone have any suggestions on how to do this?
Thanks in advance to all who reply.
|
2013/01/08
|
[
"https://Stackoverflow.com/questions/14209145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/458811/"
] |
If you don't need to support windows RT, then you can go for iTextSharp(its free),
and if you want to support windows RT then there is no free library for C#, you might prefer to code your apps using HTML5 and Javascript and use Mozilla's pdf.js to read PDF files.
|
The Foxit SDK has support for UWP development. If I look into samples there is whole demo viewer UWP sample code.
|
2,073 |
I have a friend that just described her situation and I'm lost. Hopefully someone here can help me out. I'm a programmer so I'm using variables instead of names :)
* A = my friend
* B = her friend (female)
* C & D = her friend's children
* E & F = her friend's children's respective fathers
and the situation:
* B is in the hospital on life support likely to die (malpractice suit in progress)
* A is the god-mother of C & D
* A is unmarried without room for the children but will change her environment if needed to qualify for custody
* E has given up all rights as a father
* F is a drug addict and shouldn't raise a child (subjective but true)
My question is this: What legal options does A have for obtaining custody of C & D?
|
2011/06/23
|
[
"https://parenting.stackexchange.com/questions/2073",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/1210/"
] |
Disclaimer .. IANAL, and **A needs a lawyer**.
I don't think there are inherent legal rights conferred by being a "god-parent".
However ... the real answer is it depends who is contesting. If no one contests, the court will award A custody. It will initially temporary, and she will need to petition for adoption after all is settled.
Relevant Issues:
* What sort of legal provisions were made by B?
* The ages of the children and their wishes and concerns.
* Are there any other relatives of B or E&F around?
* How big is the malpractice settlement going to be?
* Is there any clear indications available that B intended for A to raise the kids.
* Did E renounce paternity rights through a legal process?
Absent other relatives, B has a reasonable shot to get the C (the child of E), because E no longer has parental rights. It will be far harder to get D (the child of F), particularly if F gets an eye on the malpractice jackpot. The courts will search out F, and he will get the benefit of the doubt.
My advice to A ...
1. **GET A LAWYER.**
2. Get the court to appoint the kids their own legal guardian(s) for the process.
3. Work with the court appointed guardian/s and be clear that the kids are all that matters to you.
4. Push to get trusts setup for the kids in the event they come into money through the litigation. The guardian/s should be able to do this.
5. In case I wasn't clear enough ... **GET A LAWYER.**
|
Adding to tomjedrz...
Things to consider:
* Who currently has physical custody of the children? If it is A, make it official with the authorities, such as a family court or child protective services. If not we will need more information.
* What sort of documents are available to assert B's intentions? Find letters, emails, baptismal records, power of attorney as relates to medical decisions, and any others.
* In addition to the fathers, what about grandparents of C & D: there should be six to choose from if still living.
* What about siblings of B?
* Does A want custody of the children or does A want to fulfill her commitments to B or does A want what's best for the children? This can be difficult to work through.
* If being a godparent was part of a church ceremony approach the church for help.
* Obtaining legal custody of children is often difficult and painful in the courts, in addition to the difficulty of actually taking children into your life unexpectedly. A may work through all of this and at the end find she can not accommodate the result.
* What do the children want?
If A cannot afford a lawyer, especially as she may be taking on the needs of the children, seek out and obtain legal advice from charitable legal services. Sometimes called legal assistance or pro bono. Find a list of free service providers [here](http://apps.americanbar.org/legalservices/probono/directory.html) from the American Bar Association.
|
2,073 |
I have a friend that just described her situation and I'm lost. Hopefully someone here can help me out. I'm a programmer so I'm using variables instead of names :)
* A = my friend
* B = her friend (female)
* C & D = her friend's children
* E & F = her friend's children's respective fathers
and the situation:
* B is in the hospital on life support likely to die (malpractice suit in progress)
* A is the god-mother of C & D
* A is unmarried without room for the children but will change her environment if needed to qualify for custody
* E has given up all rights as a father
* F is a drug addict and shouldn't raise a child (subjective but true)
My question is this: What legal options does A have for obtaining custody of C & D?
|
2011/06/23
|
[
"https://parenting.stackexchange.com/questions/2073",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/1210/"
] |
Disclaimer .. IANAL, and **A needs a lawyer**.
I don't think there are inherent legal rights conferred by being a "god-parent".
However ... the real answer is it depends who is contesting. If no one contests, the court will award A custody. It will initially temporary, and she will need to petition for adoption after all is settled.
Relevant Issues:
* What sort of legal provisions were made by B?
* The ages of the children and their wishes and concerns.
* Are there any other relatives of B or E&F around?
* How big is the malpractice settlement going to be?
* Is there any clear indications available that B intended for A to raise the kids.
* Did E renounce paternity rights through a legal process?
Absent other relatives, B has a reasonable shot to get the C (the child of E), because E no longer has parental rights. It will be far harder to get D (the child of F), particularly if F gets an eye on the malpractice jackpot. The courts will search out F, and he will get the benefit of the doubt.
My advice to A ...
1. **GET A LAWYER.**
2. Get the court to appoint the kids their own legal guardian(s) for the process.
3. Work with the court appointed guardian/s and be clear that the kids are all that matters to you.
4. Push to get trusts setup for the kids in the event they come into money through the litigation. The guardian/s should be able to do this.
5. In case I wasn't clear enough ... **GET A LAWYER.**
|
I will answer what I know as a foster parent in the U.S.
In the situation you describe, the children would probably be in foster care. This is one of the "scenarios" we had to deal with during our training.
The good news is, if that's true then A has got a great place to start. She should work with DCF in that area. She should reach out to them and let them know. DCF would be more then willing to place the children with A if they can (we will address that in a moment).
If the children are with F has custody, then the first step is to get the children into Foster care, and away from the bad parent.
Based on your tags I am going to continue as if the children are in Foster care.
1. Reach out to the "Case Manager" and let them know you were friends of A and the childrens god parents. They will be thrilled.
2. Be prepared to do a "home study". The case worker will stop by and make sure that you have what you need, things like enough room, the ability to care for children (money), and general safety (no chain saws on the living room floor).
3. Next will be transitioning the children from their foster parents to you. This needs to be a smooth process so be prepared for it to take a while. The children have already been traumatized once by "loosing" their mother. So take your time with the transition and focus on making it a smooth process for them. Start with visits and then nights over and finally "moving in". The case worker will know how to proceed. Don't be afraid to reach out to the foster parents and ask for help. Almost all will be more then happy to help.
4. With the kids in your custody, then prepare for adoption. The process is long. About a year. You will have frequent home inspections, and lots of different "case workers" in and out of your home. Around here there are about 6 different workers that come in and out of the home during the adoption phase. Try to work with each one of them. If they suggest classes take them. A lot of the classes help with how to work with the system. Others focus on working with the needs of children that have been through trauma (these children have).
5. Make sure to hire an adoption lawyer. Then finalize everything. This will likely be a couple of years after the kids move in. It's a process, but it's designed to make sure that the kids are safe and secure and not moved around all the time.
There are a few things to note. IANAL I am a foster parent, you need a lawyer. Make sure to get one as soon as you can. A should reach out the case worker ASAP. Even though she can't take the children right now, if the case worker knows that she is trying to get things together, there is often funding to help speed that process up, and more importantly the current foster parents can be told, and the children prepared. Entering foster care is always traumatic. There's not much that can be done about that. You yanked away from every one and every thing you have every known and thrown into some strangers house. One of the best quotes from class was "Don't take candy from strangers, just move in with them." On the exit side though it doesn't have to be that traumatic. It will be emotional, but if the children and the foster parents know, then trauma can be avoided. just taking the kids from their current foster home with no warning is usually more traumatic then the first time around because it just re-enforces the "can't count on anyone" feelings.
As for E, not a problem. Once given up, getting parental rights back is near impossible (this will depend on local laws).
F could be an issue, you will have to prove that he is an unfit parent. That could be a very hard thing to do. Even in foster care, we would try to reach out to F and make them a better parent (get them off the drugs) instead of ruling them out completely. A should be willing to work with F. If not this may get messy.
And if A has a trump card (a living will stating the mothers intentions) PLAY IT NOW! Get it on file with the courts and make it known to everyone. That could make a huge difference.
|
2,073 |
I have a friend that just described her situation and I'm lost. Hopefully someone here can help me out. I'm a programmer so I'm using variables instead of names :)
* A = my friend
* B = her friend (female)
* C & D = her friend's children
* E & F = her friend's children's respective fathers
and the situation:
* B is in the hospital on life support likely to die (malpractice suit in progress)
* A is the god-mother of C & D
* A is unmarried without room for the children but will change her environment if needed to qualify for custody
* E has given up all rights as a father
* F is a drug addict and shouldn't raise a child (subjective but true)
My question is this: What legal options does A have for obtaining custody of C & D?
|
2011/06/23
|
[
"https://parenting.stackexchange.com/questions/2073",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/1210/"
] |
Adding to tomjedrz...
Things to consider:
* Who currently has physical custody of the children? If it is A, make it official with the authorities, such as a family court or child protective services. If not we will need more information.
* What sort of documents are available to assert B's intentions? Find letters, emails, baptismal records, power of attorney as relates to medical decisions, and any others.
* In addition to the fathers, what about grandparents of C & D: there should be six to choose from if still living.
* What about siblings of B?
* Does A want custody of the children or does A want to fulfill her commitments to B or does A want what's best for the children? This can be difficult to work through.
* If being a godparent was part of a church ceremony approach the church for help.
* Obtaining legal custody of children is often difficult and painful in the courts, in addition to the difficulty of actually taking children into your life unexpectedly. A may work through all of this and at the end find she can not accommodate the result.
* What do the children want?
If A cannot afford a lawyer, especially as she may be taking on the needs of the children, seek out and obtain legal advice from charitable legal services. Sometimes called legal assistance or pro bono. Find a list of free service providers [here](http://apps.americanbar.org/legalservices/probono/directory.html) from the American Bar Association.
|
I will answer what I know as a foster parent in the U.S.
In the situation you describe, the children would probably be in foster care. This is one of the "scenarios" we had to deal with during our training.
The good news is, if that's true then A has got a great place to start. She should work with DCF in that area. She should reach out to them and let them know. DCF would be more then willing to place the children with A if they can (we will address that in a moment).
If the children are with F has custody, then the first step is to get the children into Foster care, and away from the bad parent.
Based on your tags I am going to continue as if the children are in Foster care.
1. Reach out to the "Case Manager" and let them know you were friends of A and the childrens god parents. They will be thrilled.
2. Be prepared to do a "home study". The case worker will stop by and make sure that you have what you need, things like enough room, the ability to care for children (money), and general safety (no chain saws on the living room floor).
3. Next will be transitioning the children from their foster parents to you. This needs to be a smooth process so be prepared for it to take a while. The children have already been traumatized once by "loosing" their mother. So take your time with the transition and focus on making it a smooth process for them. Start with visits and then nights over and finally "moving in". The case worker will know how to proceed. Don't be afraid to reach out to the foster parents and ask for help. Almost all will be more then happy to help.
4. With the kids in your custody, then prepare for adoption. The process is long. About a year. You will have frequent home inspections, and lots of different "case workers" in and out of your home. Around here there are about 6 different workers that come in and out of the home during the adoption phase. Try to work with each one of them. If they suggest classes take them. A lot of the classes help with how to work with the system. Others focus on working with the needs of children that have been through trauma (these children have).
5. Make sure to hire an adoption lawyer. Then finalize everything. This will likely be a couple of years after the kids move in. It's a process, but it's designed to make sure that the kids are safe and secure and not moved around all the time.
There are a few things to note. IANAL I am a foster parent, you need a lawyer. Make sure to get one as soon as you can. A should reach out the case worker ASAP. Even though she can't take the children right now, if the case worker knows that she is trying to get things together, there is often funding to help speed that process up, and more importantly the current foster parents can be told, and the children prepared. Entering foster care is always traumatic. There's not much that can be done about that. You yanked away from every one and every thing you have every known and thrown into some strangers house. One of the best quotes from class was "Don't take candy from strangers, just move in with them." On the exit side though it doesn't have to be that traumatic. It will be emotional, but if the children and the foster parents know, then trauma can be avoided. just taking the kids from their current foster home with no warning is usually more traumatic then the first time around because it just re-enforces the "can't count on anyone" feelings.
As for E, not a problem. Once given up, getting parental rights back is near impossible (this will depend on local laws).
F could be an issue, you will have to prove that he is an unfit parent. That could be a very hard thing to do. Even in foster care, we would try to reach out to F and make them a better parent (get them off the drugs) instead of ruling them out completely. A should be willing to work with F. If not this may get messy.
And if A has a trump card (a living will stating the mothers intentions) PLAY IT NOW! Get it on file with the courts and make it known to everyone. That could make a huge difference.
|
10,143,960 |
Im using the following to retrieve a string from php, i would like to know how to make my string into an array.
**Jquery**
```
$.get("get.php", function(data){
alert(data);
//alert($.parseJSON(data));
}, "json");
```
the commented out section seems to have no effect, so I cant really tell what I am doing wrong, could someone please advice?
I can post the PHP if needed.
Thanks.
**PHP**
```
<?php
$username="root";
$password="root";
$database="testing";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$name= $_GET['name'];
$query="SELECT * FROM tableone ";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$array = array();
$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"firstname");
$last=mysql_result($result,$i,"lastname");
$date=mysql_result($result,$i,"date");
$ID=mysql_result($result,$i,"id");
$array[$i] = $first;
$i++;
}
echo json_encode($array);
?>
```
Output:
`["James","Lydia","John"]`
|
2012/04/13
|
[
"https://Stackoverflow.com/questions/10143960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/360481/"
] |
You likely want to set the `:ARCHIVE:` property on the parent headlines.
It allows you for headline specific `org-archive-location` settings. (See the [manual](http://orgmode.org/manual/Moving-subtrees.html#Moving-subtrees))
For example if your archive file is set as `%s_archive` you would want your original file to look like this
```
* Misc.
:PROPERTIES:
:ARCHIVE: %s_archive::* Misc
:END:
** TODO Task 1
** TODO Task 2
* Project 1
:PROPERTIES:
:ARCHIVE: %s_archive::* Project 1
:END:
** TODO Task 1
** TODO Task 2
```
This would sent any subtrees in `* Misc` to a `* Misc` headline in the archive file, and would do the equivalent for the subtrees in `Project 1` (unless you archive the whole tree in one shot). Archiving the parent tree after the subtrees appears to add it as an additional subheading under the destination. It does not support multiple levels, so you'd have to set up your archive file headlines ahead of time to ensure it outputs the way you desire if you need a complex setup of that sort.
You can also use this property to archive specific trees to separate files (for export/publication/sharing purposes).
|
I don't think `org-mode` has support for directly mirroring the current context inside your archive file.
There is a relevant variable, `org-archive-location` which can be used to specify a single heading to place your archived item, but multiple levels inside the tree is not supported. On [this page](http://orgmode.org/worg/org-hacks.html) there are two advices for `org-archive-subtree` that may be good enough. I am replicating the first one here in case the site goes away:
```lisp
(defadvice org-archive-subtree (around my-org-archive-subtree activate)
(let ((org-archive-location
(if (save-excursion (org-back-to-heading)
(> (org-outline-level) 1))
(concat (car (split-string org-archive-location "::"))
"::* "
(car (org-get-outline-path)))
org-archive-location)))
ad-do-it))
```
The second, and more complicated one also preserves tags found on the top level headings.
On last thing that may come in handy is the custom variable `org-archive-save-context-info`. If this list contains the symbol `'olpath`, the archived entry will contain `:ARCHIVE_OLPATH:` property, which is set to the outline path of the archived entry (e.g. `Projects/Misc`. Maybe you can do some post processing on the `org-archive-subtree` and relocate the archived entry to its original outline path using this.
|
10,143,960 |
Im using the following to retrieve a string from php, i would like to know how to make my string into an array.
**Jquery**
```
$.get("get.php", function(data){
alert(data);
//alert($.parseJSON(data));
}, "json");
```
the commented out section seems to have no effect, so I cant really tell what I am doing wrong, could someone please advice?
I can post the PHP if needed.
Thanks.
**PHP**
```
<?php
$username="root";
$password="root";
$database="testing";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$name= $_GET['name'];
$query="SELECT * FROM tableone ";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$array = array();
$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"firstname");
$last=mysql_result($result,$i,"lastname");
$date=mysql_result($result,$i,"date");
$ID=mysql_result($result,$i,"id");
$array[$i] = $first;
$i++;
}
echo json_encode($array);
?>
```
Output:
`["James","Lydia","John"]`
|
2012/04/13
|
[
"https://Stackoverflow.com/questions/10143960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/360481/"
] |
```
;; org-archive-subtree-hierarchical.el
;; modified from https://lists.gnu.org/archive/html/emacs-orgmode/2014-08/msg00109.html
;; In orgmode
;; * A
;; ** AA
;; *** AAA
;; ** AB
;; *** ABA
;; Archiving AA will remove the subtree from the original file and create
;; it like that in archive target:
;; * AA
;; ** AAA
;; And this give you
;; * A
;; ** AA
;; *** AAA
(require 'org-archive)
(defun org-archive-subtree-hierarchical--line-content-as-string ()
"Returns the content of the current line as a string"
(save-excursion
(beginning-of-line)
(buffer-substring-no-properties
(line-beginning-position) (line-end-position))))
(defun org-archive-subtree-hierarchical--org-child-list ()
"This function returns all children of a heading as a list. "
(interactive)
(save-excursion
;; this only works with org-version > 8.0, since in previous
;; org-mode versions the function (org-outline-level) returns
;; gargabe when the point is not on a heading.
(if (= (org-outline-level) 0)
(outline-next-visible-heading 1)
(org-goto-first-child))
(let ((child-list (list (org-archive-subtree-hierarchical--line-content-as-string))))
(while (org-goto-sibling)
(setq child-list (cons (org-archive-subtree-hierarchical--line-content-as-string) child-list)))
child-list)))
(defun org-archive-subtree-hierarchical--org-struct-subtree ()
"This function returns the tree structure in which a subtree
belongs as a list."
(interactive)
(let ((archive-tree nil))
(save-excursion
(while (org-up-heading-safe)
(let ((heading
(buffer-substring-no-properties
(line-beginning-position) (line-end-position))))
(if (eq archive-tree nil)
(setq archive-tree (list heading))
(setq archive-tree (cons heading archive-tree))))))
archive-tree))
(defun org-archive-subtree-hierarchical ()
"This function archives a subtree hierarchical"
(interactive)
(let ((org-tree (org-archive-subtree-hierarchical--org-struct-subtree))
(this-buffer (current-buffer))
(file (abbreviate-file-name
(or (buffer-file-name (buffer-base-buffer))
(error "No file associated to buffer")))))
(save-excursion
(setq location (org-get-local-archive-location)
afile (org-extract-archive-file location)
heading (org-extract-archive-heading location)
infile-p (equal file (abbreviate-file-name (or afile ""))))
(unless afile
(error "Invalid `org-archive-location'"))
(if (> (length afile) 0)
(setq newfile-p (not (file-exists-p afile))
visiting (find-buffer-visiting afile)
buffer (or visiting (find-file-noselect afile)))
(setq buffer (current-buffer)))
(unless buffer
(error "Cannot access file \"%s\"" afile))
(org-cut-subtree)
(set-buffer buffer)
(org-mode)
(goto-char (point-min))
(while (not (equal org-tree nil))
(let ((child-list (org-archive-subtree-hierarchical--org-child-list)))
(if (member (car org-tree) child-list)
(progn
(search-forward (car org-tree) nil t)
(setq org-tree (cdr org-tree)))
(progn
(goto-char (point-max))
(newline)
(org-insert-struct org-tree)
(setq org-tree nil)))))
(newline)
(org-yank)
(when (not (eq this-buffer buffer))
(save-buffer))
(message "Subtree archived %s"
(concat "in file: " (abbreviate-file-name afile))))))
(defun org-insert-struct (struct)
"TODO"
(interactive)
(when struct
(insert (car struct))
(newline)
(org-insert-struct (cdr struct))))
(defun org-archive-subtree ()
(org-archive-subtree-hierarchical)
)
```
This hack just act like refile to your archive file with whole same parent struct,no archive `:PROPERTIES:` here.
Also as a gist here: <https://gist.github.com/CodeFalling/87b116291aa87fde72cb>
|
I don't think `org-mode` has support for directly mirroring the current context inside your archive file.
There is a relevant variable, `org-archive-location` which can be used to specify a single heading to place your archived item, but multiple levels inside the tree is not supported. On [this page](http://orgmode.org/worg/org-hacks.html) there are two advices for `org-archive-subtree` that may be good enough. I am replicating the first one here in case the site goes away:
```lisp
(defadvice org-archive-subtree (around my-org-archive-subtree activate)
(let ((org-archive-location
(if (save-excursion (org-back-to-heading)
(> (org-outline-level) 1))
(concat (car (split-string org-archive-location "::"))
"::* "
(car (org-get-outline-path)))
org-archive-location)))
ad-do-it))
```
The second, and more complicated one also preserves tags found on the top level headings.
On last thing that may come in handy is the custom variable `org-archive-save-context-info`. If this list contains the symbol `'olpath`, the archived entry will contain `:ARCHIVE_OLPATH:` property, which is set to the outline path of the archived entry (e.g. `Projects/Misc`. Maybe you can do some post processing on the `org-archive-subtree` and relocate the archived entry to its original outline path using this.
|
10,143,960 |
Im using the following to retrieve a string from php, i would like to know how to make my string into an array.
**Jquery**
```
$.get("get.php", function(data){
alert(data);
//alert($.parseJSON(data));
}, "json");
```
the commented out section seems to have no effect, so I cant really tell what I am doing wrong, could someone please advice?
I can post the PHP if needed.
Thanks.
**PHP**
```
<?php
$username="root";
$password="root";
$database="testing";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$name= $_GET['name'];
$query="SELECT * FROM tableone ";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$array = array();
$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"firstname");
$last=mysql_result($result,$i,"lastname");
$date=mysql_result($result,$i,"date");
$ID=mysql_result($result,$i,"id");
$array[$i] = $first;
$i++;
}
echo json_encode($array);
?>
```
Output:
`["James","Lydia","John"]`
|
2012/04/13
|
[
"https://Stackoverflow.com/questions/10143960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/360481/"
] |
You likely want to set the `:ARCHIVE:` property on the parent headlines.
It allows you for headline specific `org-archive-location` settings. (See the [manual](http://orgmode.org/manual/Moving-subtrees.html#Moving-subtrees))
For example if your archive file is set as `%s_archive` you would want your original file to look like this
```
* Misc.
:PROPERTIES:
:ARCHIVE: %s_archive::* Misc
:END:
** TODO Task 1
** TODO Task 2
* Project 1
:PROPERTIES:
:ARCHIVE: %s_archive::* Project 1
:END:
** TODO Task 1
** TODO Task 2
```
This would sent any subtrees in `* Misc` to a `* Misc` headline in the archive file, and would do the equivalent for the subtrees in `Project 1` (unless you archive the whole tree in one shot). Archiving the parent tree after the subtrees appears to add it as an additional subheading under the destination. It does not support multiple levels, so you'd have to set up your archive file headlines ahead of time to ensure it outputs the way you desire if you need a complex setup of that sort.
You can also use this property to archive specific trees to separate files (for export/publication/sharing purposes).
|
```
;; org-archive-subtree-hierarchical.el
;; modified from https://lists.gnu.org/archive/html/emacs-orgmode/2014-08/msg00109.html
;; In orgmode
;; * A
;; ** AA
;; *** AAA
;; ** AB
;; *** ABA
;; Archiving AA will remove the subtree from the original file and create
;; it like that in archive target:
;; * AA
;; ** AAA
;; And this give you
;; * A
;; ** AA
;; *** AAA
(require 'org-archive)
(defun org-archive-subtree-hierarchical--line-content-as-string ()
"Returns the content of the current line as a string"
(save-excursion
(beginning-of-line)
(buffer-substring-no-properties
(line-beginning-position) (line-end-position))))
(defun org-archive-subtree-hierarchical--org-child-list ()
"This function returns all children of a heading as a list. "
(interactive)
(save-excursion
;; this only works with org-version > 8.0, since in previous
;; org-mode versions the function (org-outline-level) returns
;; gargabe when the point is not on a heading.
(if (= (org-outline-level) 0)
(outline-next-visible-heading 1)
(org-goto-first-child))
(let ((child-list (list (org-archive-subtree-hierarchical--line-content-as-string))))
(while (org-goto-sibling)
(setq child-list (cons (org-archive-subtree-hierarchical--line-content-as-string) child-list)))
child-list)))
(defun org-archive-subtree-hierarchical--org-struct-subtree ()
"This function returns the tree structure in which a subtree
belongs as a list."
(interactive)
(let ((archive-tree nil))
(save-excursion
(while (org-up-heading-safe)
(let ((heading
(buffer-substring-no-properties
(line-beginning-position) (line-end-position))))
(if (eq archive-tree nil)
(setq archive-tree (list heading))
(setq archive-tree (cons heading archive-tree))))))
archive-tree))
(defun org-archive-subtree-hierarchical ()
"This function archives a subtree hierarchical"
(interactive)
(let ((org-tree (org-archive-subtree-hierarchical--org-struct-subtree))
(this-buffer (current-buffer))
(file (abbreviate-file-name
(or (buffer-file-name (buffer-base-buffer))
(error "No file associated to buffer")))))
(save-excursion
(setq location (org-get-local-archive-location)
afile (org-extract-archive-file location)
heading (org-extract-archive-heading location)
infile-p (equal file (abbreviate-file-name (or afile ""))))
(unless afile
(error "Invalid `org-archive-location'"))
(if (> (length afile) 0)
(setq newfile-p (not (file-exists-p afile))
visiting (find-buffer-visiting afile)
buffer (or visiting (find-file-noselect afile)))
(setq buffer (current-buffer)))
(unless buffer
(error "Cannot access file \"%s\"" afile))
(org-cut-subtree)
(set-buffer buffer)
(org-mode)
(goto-char (point-min))
(while (not (equal org-tree nil))
(let ((child-list (org-archive-subtree-hierarchical--org-child-list)))
(if (member (car org-tree) child-list)
(progn
(search-forward (car org-tree) nil t)
(setq org-tree (cdr org-tree)))
(progn
(goto-char (point-max))
(newline)
(org-insert-struct org-tree)
(setq org-tree nil)))))
(newline)
(org-yank)
(when (not (eq this-buffer buffer))
(save-buffer))
(message "Subtree archived %s"
(concat "in file: " (abbreviate-file-name afile))))))
(defun org-insert-struct (struct)
"TODO"
(interactive)
(when struct
(insert (car struct))
(newline)
(org-insert-struct (cdr struct))))
(defun org-archive-subtree ()
(org-archive-subtree-hierarchical)
)
```
This hack just act like refile to your archive file with whole same parent struct,no archive `:PROPERTIES:` here.
Also as a gist here: <https://gist.github.com/CodeFalling/87b116291aa87fde72cb>
|
47,375,568 |
I have a little question. Can i in javascript use string.slice() = x?
Example: "Hello world!".slice(2,3) --> = x <-- can I use this?
```
^ the 3rd character in the string
```
So, can i change characters with a slice? (:
|
2017/11/19
|
[
"https://Stackoverflow.com/questions/47375568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8965634/"
] |
No, you can not assign a value to a part of a [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type):
>
> Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string.
>
>
>
You can split the string into an array of characters, change the wanted character at the given index and join the array for a new string.
```js
var string = "Hello world!",
array = string.split('');
array[2] = 'X';
string = array.join('');
console.log(string);
```
|
Yes you can use [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) to get the character.
```
var x = "Hello world!".slice(2,3);
console.log(x);
```
However, you can't change character with a slice. See [Nina's answer](https://stackoverflow.com/a/47375615/4154250) how to do that.
|
9,375,598 |
Need to help
1. How play video on `Surface(OpenGL)` in Android?
I tried playing video in `mySurfaceView extends SurfaceView` with help method `setSurface()` in `MediaPlayer`.
```
SurfaceTexture mTexture = new SurfaceTexture(texture_id);
Surface mSurface = new Surface(mTexture);
MediaPlayer mp = new MediaPlayer();
mp.setSurface(mSurface);
```
I got only playing audio - video not playing.
2. How get video buffer for sending in `OpenGL`??
3. How playing video on `GLTexture`?
|
2012/02/21
|
[
"https://Stackoverflow.com/questions/9375598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221256/"
] |
From android source code...
```
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;
import android.view.Surface;
class VideoSurfaceView extends GLSurfaceView {
VideoRender mRenderer;
private MediaPlayer mMediaPlayer = null;
public VideoSurfaceView(Context context, MediaPlayer mp) {
super(context);
setEGLContextClientVersion(2);
mMediaPlayer = mp;
mRenderer = new VideoRender(context);
setRenderer(mRenderer);
}
@Override
public void onResume() {
queueEvent(new Runnable(){
public void run() {
mRenderer.setMediaPlayer(mMediaPlayer);
}});
super.onResume();
}
private static class VideoRender
implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {
private static String TAG = "VideoRender";
private static final int FLOAT_SIZE_BYTES = 4;
private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
private final float[] mTriangleVerticesData = {
// X, Y, Z, U, V
-1.0f, -1.0f, 0, 0.f, 0.f,
1.0f, -1.0f, 0, 1.f, 0.f,
-1.0f, 1.0f, 0, 0.f, 1.f,
1.0f, 1.0f, 0, 1.f, 1.f,
};
private FloatBuffer mTriangleVertices;
private final String mVertexShader =
"uniform mat4 uMVPMatrix;\n" +
"uniform mat4 uSTMatrix;\n" +
"attribute vec4 aPosition;\n" +
"attribute vec4 aTextureCoord;\n" +
"varying vec2 vTextureCoord;\n" +
"void main() {\n" +
" gl_Position = uMVPMatrix * aPosition;\n" +
" vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
"}\n";
private final String mFragmentShader =
"#extension GL_OES_EGL_image_external : require\n" +
"precision mediump float;\n" +
"varying vec2 vTextureCoord;\n" +
"uniform samplerExternalOES sTexture;\n" +
"void main() {\n" +
" gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
"}\n";
private float[] mMVPMatrix = new float[16];
private float[] mSTMatrix = new float[16];
private int mProgram;
private int mTextureID;
private int muMVPMatrixHandle;
private int muSTMatrixHandle;
private int maPositionHandle;
private int maTextureHandle;
private SurfaceTexture mSurface;
private boolean updateSurface = false;
private static int GL_TEXTURE_EXTERNAL_OES = 0x8D65;
private MediaPlayer mMediaPlayer;
public VideoRender(Context context) {
mTriangleVertices = ByteBuffer.allocateDirect(
mTriangleVerticesData.length * FLOAT_SIZE_BYTES)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mTriangleVertices.put(mTriangleVerticesData).position(0);
Matrix.setIdentityM(mSTMatrix, 0);
}
public void setMediaPlayer(MediaPlayer player) {
mMediaPlayer = player;
}
public void onDrawFrame(GL10 glUnused) {
synchronized(this) {
if (updateSurface) {
mSurface.updateTexImage();
mSurface.getTransformMatrix(mSTMatrix);
updateSurface = false;
}
}
GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glUseProgram(mProgram);
checkGlError("glUseProgram");
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID);
mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
checkGlError("glVertexAttribPointer maPosition");
GLES20.glEnableVertexAttribArray(maPositionHandle);
checkGlError("glEnableVertexAttribArray maPositionHandle");
mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
GLES20.glVertexAttribPointer(maTextureHandle, 3, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
checkGlError("glVertexAttribPointer maTextureHandle");
GLES20.glEnableVertexAttribArray(maTextureHandle);
checkGlError("glEnableVertexAttribArray maTextureHandle");
Matrix.setIdentityM(mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(muSTMatrixHandle, 1, false, mSTMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
checkGlError("glDrawArrays");
GLES20.glFinish();
}
public void onSurfaceChanged(GL10 glUnused, int width, int height) {
}
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
mProgram = createProgram(mVertexShader, mFragmentShader);
if (mProgram == 0) {
return;
}
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
checkGlError("glGetAttribLocation aPosition");
if (maPositionHandle == -1) {
throw new RuntimeException("Could not get attrib location for aPosition");
}
maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord");
checkGlError("glGetAttribLocation aTextureCoord");
if (maTextureHandle == -1) {
throw new RuntimeException("Could not get attrib location for aTextureCoord");
}
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
checkGlError("glGetUniformLocation uMVPMatrix");
if (muMVPMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uMVPMatrix");
}
muSTMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix");
checkGlError("glGetUniformLocation uSTMatrix");
if (muSTMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uSTMatrix");
}
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
mTextureID = textures[0];
GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID);
checkGlError("glBindTexture mTextureID");
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER,
GLES20.GL_NEAREST);
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER,
GLES20.GL_LINEAR);
/*
* Create the SurfaceTexture that will feed this textureID,
* and pass it to the MediaPlayer
*/
mSurface = new SurfaceTexture(mTextureID);
mSurface.setOnFrameAvailableListener(this);
Surface surface = new Surface(mSurface);
mMediaPlayer.setSurface(surface);
surface.release();
try {
mMediaPlayer.prepare();
} catch (IOException t) {
Log.e(TAG, "media player prepare failed");
}
synchronized(this) {
updateSurface = false;
}
mMediaPlayer.start();
}
synchronized public void onFrameAvailable(SurfaceTexture surface) {
updateSurface = true;
}
private int loadShader(int shaderType, String source) {
int shader = GLES20.glCreateShader(shaderType);
if (shader != 0) {
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
int[] compiled = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) {
Log.e(TAG, "Could not compile shader " + shaderType + ":");
Log.e(TAG, GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
private int createProgram(String vertexSource, String fragmentSource) {
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0) {
return 0;
}
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0) {
return 0;
}
int program = GLES20.glCreateProgram();
if (program != 0) {
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
GLES20.glLinkProgram(program);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
Log.e(TAG, "Could not link program: ");
Log.e(TAG, GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
}
return program;
}
private void checkGlError(String op) {
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
Log.e(TAG, op + ": glError " + error);
throw new RuntimeException(op + ": glError " + error);
}
}
} // End of class VideoRender.
} // End of class VideoSurfaceView.
```
|
I guess you can't. At least that's what i found out.
My plan was to have some sort of OpenGL scene (text ticker) while playing a video.
Since android uses HW decoding for displaying a video, it will not be done with OpenGL. I also tried to play the video in OpenGL using ffmpeg but i found out, that no device i tried with, was performant enough to do SW decoding via ffmpeg.
So I had to use a VideoView to display my video and put a GLSurfaceView on top of it, to view my ticker text.
But you have to make the GLSurfaceView translucent like in ApiDemos done with 'TranslucentGLSurfaceViewActivity'.
Another thing i realized: If you put a GLSurfaceView on top of a VideoView your fps breaks down dramatically from 60fps (opengl) to about 30-40fps.
This applied to all 2.x versions of android i tested.
Last week i had the chance to test it on Android 4 and this time i got no break down in fps. Maybe they really improved graphics pipeline for ICS.
Greetings, -chris-
|
9,375,598 |
Need to help
1. How play video on `Surface(OpenGL)` in Android?
I tried playing video in `mySurfaceView extends SurfaceView` with help method `setSurface()` in `MediaPlayer`.
```
SurfaceTexture mTexture = new SurfaceTexture(texture_id);
Surface mSurface = new Surface(mTexture);
MediaPlayer mp = new MediaPlayer();
mp.setSurface(mSurface);
```
I got only playing audio - video not playing.
2. How get video buffer for sending in `OpenGL`??
3. How playing video on `GLTexture`?
|
2012/02/21
|
[
"https://Stackoverflow.com/questions/9375598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221256/"
] |
I guess you can't. At least that's what i found out.
My plan was to have some sort of OpenGL scene (text ticker) while playing a video.
Since android uses HW decoding for displaying a video, it will not be done with OpenGL. I also tried to play the video in OpenGL using ffmpeg but i found out, that no device i tried with, was performant enough to do SW decoding via ffmpeg.
So I had to use a VideoView to display my video and put a GLSurfaceView on top of it, to view my ticker text.
But you have to make the GLSurfaceView translucent like in ApiDemos done with 'TranslucentGLSurfaceViewActivity'.
Another thing i realized: If you put a GLSurfaceView on top of a VideoView your fps breaks down dramatically from 60fps (opengl) to about 30-40fps.
This applied to all 2.x versions of android i tested.
Last week i had the chance to test it on Android 4 and this time i got no break down in fps. Maybe they really improved graphics pipeline for ICS.
Greetings, -chris-
|
```
mMediaPlayer.setSurface(new Surface(mSurfaceTexture));
```
You can use above line of code to use it on your mediaPlayerObject over your desired surfaceTexture which is a applied texture over your surfaceview.
Hope that helps.
|
9,375,598 |
Need to help
1. How play video on `Surface(OpenGL)` in Android?
I tried playing video in `mySurfaceView extends SurfaceView` with help method `setSurface()` in `MediaPlayer`.
```
SurfaceTexture mTexture = new SurfaceTexture(texture_id);
Surface mSurface = new Surface(mTexture);
MediaPlayer mp = new MediaPlayer();
mp.setSurface(mSurface);
```
I got only playing audio - video not playing.
2. How get video buffer for sending in `OpenGL`??
3. How playing video on `GLTexture`?
|
2012/02/21
|
[
"https://Stackoverflow.com/questions/9375598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221256/"
] |
From android source code...
```
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;
import android.view.Surface;
class VideoSurfaceView extends GLSurfaceView {
VideoRender mRenderer;
private MediaPlayer mMediaPlayer = null;
public VideoSurfaceView(Context context, MediaPlayer mp) {
super(context);
setEGLContextClientVersion(2);
mMediaPlayer = mp;
mRenderer = new VideoRender(context);
setRenderer(mRenderer);
}
@Override
public void onResume() {
queueEvent(new Runnable(){
public void run() {
mRenderer.setMediaPlayer(mMediaPlayer);
}});
super.onResume();
}
private static class VideoRender
implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {
private static String TAG = "VideoRender";
private static final int FLOAT_SIZE_BYTES = 4;
private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
private final float[] mTriangleVerticesData = {
// X, Y, Z, U, V
-1.0f, -1.0f, 0, 0.f, 0.f,
1.0f, -1.0f, 0, 1.f, 0.f,
-1.0f, 1.0f, 0, 0.f, 1.f,
1.0f, 1.0f, 0, 1.f, 1.f,
};
private FloatBuffer mTriangleVertices;
private final String mVertexShader =
"uniform mat4 uMVPMatrix;\n" +
"uniform mat4 uSTMatrix;\n" +
"attribute vec4 aPosition;\n" +
"attribute vec4 aTextureCoord;\n" +
"varying vec2 vTextureCoord;\n" +
"void main() {\n" +
" gl_Position = uMVPMatrix * aPosition;\n" +
" vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
"}\n";
private final String mFragmentShader =
"#extension GL_OES_EGL_image_external : require\n" +
"precision mediump float;\n" +
"varying vec2 vTextureCoord;\n" +
"uniform samplerExternalOES sTexture;\n" +
"void main() {\n" +
" gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
"}\n";
private float[] mMVPMatrix = new float[16];
private float[] mSTMatrix = new float[16];
private int mProgram;
private int mTextureID;
private int muMVPMatrixHandle;
private int muSTMatrixHandle;
private int maPositionHandle;
private int maTextureHandle;
private SurfaceTexture mSurface;
private boolean updateSurface = false;
private static int GL_TEXTURE_EXTERNAL_OES = 0x8D65;
private MediaPlayer mMediaPlayer;
public VideoRender(Context context) {
mTriangleVertices = ByteBuffer.allocateDirect(
mTriangleVerticesData.length * FLOAT_SIZE_BYTES)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mTriangleVertices.put(mTriangleVerticesData).position(0);
Matrix.setIdentityM(mSTMatrix, 0);
}
public void setMediaPlayer(MediaPlayer player) {
mMediaPlayer = player;
}
public void onDrawFrame(GL10 glUnused) {
synchronized(this) {
if (updateSurface) {
mSurface.updateTexImage();
mSurface.getTransformMatrix(mSTMatrix);
updateSurface = false;
}
}
GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glUseProgram(mProgram);
checkGlError("glUseProgram");
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID);
mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
checkGlError("glVertexAttribPointer maPosition");
GLES20.glEnableVertexAttribArray(maPositionHandle);
checkGlError("glEnableVertexAttribArray maPositionHandle");
mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
GLES20.glVertexAttribPointer(maTextureHandle, 3, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
checkGlError("glVertexAttribPointer maTextureHandle");
GLES20.glEnableVertexAttribArray(maTextureHandle);
checkGlError("glEnableVertexAttribArray maTextureHandle");
Matrix.setIdentityM(mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(muSTMatrixHandle, 1, false, mSTMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
checkGlError("glDrawArrays");
GLES20.glFinish();
}
public void onSurfaceChanged(GL10 glUnused, int width, int height) {
}
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
mProgram = createProgram(mVertexShader, mFragmentShader);
if (mProgram == 0) {
return;
}
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
checkGlError("glGetAttribLocation aPosition");
if (maPositionHandle == -1) {
throw new RuntimeException("Could not get attrib location for aPosition");
}
maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord");
checkGlError("glGetAttribLocation aTextureCoord");
if (maTextureHandle == -1) {
throw new RuntimeException("Could not get attrib location for aTextureCoord");
}
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
checkGlError("glGetUniformLocation uMVPMatrix");
if (muMVPMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uMVPMatrix");
}
muSTMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix");
checkGlError("glGetUniformLocation uSTMatrix");
if (muSTMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uSTMatrix");
}
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
mTextureID = textures[0];
GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID);
checkGlError("glBindTexture mTextureID");
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER,
GLES20.GL_NEAREST);
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER,
GLES20.GL_LINEAR);
/*
* Create the SurfaceTexture that will feed this textureID,
* and pass it to the MediaPlayer
*/
mSurface = new SurfaceTexture(mTextureID);
mSurface.setOnFrameAvailableListener(this);
Surface surface = new Surface(mSurface);
mMediaPlayer.setSurface(surface);
surface.release();
try {
mMediaPlayer.prepare();
} catch (IOException t) {
Log.e(TAG, "media player prepare failed");
}
synchronized(this) {
updateSurface = false;
}
mMediaPlayer.start();
}
synchronized public void onFrameAvailable(SurfaceTexture surface) {
updateSurface = true;
}
private int loadShader(int shaderType, String source) {
int shader = GLES20.glCreateShader(shaderType);
if (shader != 0) {
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
int[] compiled = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) {
Log.e(TAG, "Could not compile shader " + shaderType + ":");
Log.e(TAG, GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
private int createProgram(String vertexSource, String fragmentSource) {
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0) {
return 0;
}
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0) {
return 0;
}
int program = GLES20.glCreateProgram();
if (program != 0) {
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
GLES20.glLinkProgram(program);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
Log.e(TAG, "Could not link program: ");
Log.e(TAG, GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
}
return program;
}
private void checkGlError(String op) {
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
Log.e(TAG, op + ": glError " + error);
throw new RuntimeException(op + ": glError " + error);
}
}
} // End of class VideoRender.
} // End of class VideoSurfaceView.
```
|
```
mMediaPlayer.setSurface(new Surface(mSurfaceTexture));
```
You can use above line of code to use it on your mediaPlayerObject over your desired surfaceTexture which is a applied texture over your surfaceview.
Hope that helps.
|
9,375,598 |
Need to help
1. How play video on `Surface(OpenGL)` in Android?
I tried playing video in `mySurfaceView extends SurfaceView` with help method `setSurface()` in `MediaPlayer`.
```
SurfaceTexture mTexture = new SurfaceTexture(texture_id);
Surface mSurface = new Surface(mTexture);
MediaPlayer mp = new MediaPlayer();
mp.setSurface(mSurface);
```
I got only playing audio - video not playing.
2. How get video buffer for sending in `OpenGL`??
3. How playing video on `GLTexture`?
|
2012/02/21
|
[
"https://Stackoverflow.com/questions/9375598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221256/"
] |
From android source code...
```
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;
import android.view.Surface;
class VideoSurfaceView extends GLSurfaceView {
VideoRender mRenderer;
private MediaPlayer mMediaPlayer = null;
public VideoSurfaceView(Context context, MediaPlayer mp) {
super(context);
setEGLContextClientVersion(2);
mMediaPlayer = mp;
mRenderer = new VideoRender(context);
setRenderer(mRenderer);
}
@Override
public void onResume() {
queueEvent(new Runnable(){
public void run() {
mRenderer.setMediaPlayer(mMediaPlayer);
}});
super.onResume();
}
private static class VideoRender
implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {
private static String TAG = "VideoRender";
private static final int FLOAT_SIZE_BYTES = 4;
private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
private final float[] mTriangleVerticesData = {
// X, Y, Z, U, V
-1.0f, -1.0f, 0, 0.f, 0.f,
1.0f, -1.0f, 0, 1.f, 0.f,
-1.0f, 1.0f, 0, 0.f, 1.f,
1.0f, 1.0f, 0, 1.f, 1.f,
};
private FloatBuffer mTriangleVertices;
private final String mVertexShader =
"uniform mat4 uMVPMatrix;\n" +
"uniform mat4 uSTMatrix;\n" +
"attribute vec4 aPosition;\n" +
"attribute vec4 aTextureCoord;\n" +
"varying vec2 vTextureCoord;\n" +
"void main() {\n" +
" gl_Position = uMVPMatrix * aPosition;\n" +
" vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
"}\n";
private final String mFragmentShader =
"#extension GL_OES_EGL_image_external : require\n" +
"precision mediump float;\n" +
"varying vec2 vTextureCoord;\n" +
"uniform samplerExternalOES sTexture;\n" +
"void main() {\n" +
" gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
"}\n";
private float[] mMVPMatrix = new float[16];
private float[] mSTMatrix = new float[16];
private int mProgram;
private int mTextureID;
private int muMVPMatrixHandle;
private int muSTMatrixHandle;
private int maPositionHandle;
private int maTextureHandle;
private SurfaceTexture mSurface;
private boolean updateSurface = false;
private static int GL_TEXTURE_EXTERNAL_OES = 0x8D65;
private MediaPlayer mMediaPlayer;
public VideoRender(Context context) {
mTriangleVertices = ByteBuffer.allocateDirect(
mTriangleVerticesData.length * FLOAT_SIZE_BYTES)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mTriangleVertices.put(mTriangleVerticesData).position(0);
Matrix.setIdentityM(mSTMatrix, 0);
}
public void setMediaPlayer(MediaPlayer player) {
mMediaPlayer = player;
}
public void onDrawFrame(GL10 glUnused) {
synchronized(this) {
if (updateSurface) {
mSurface.updateTexImage();
mSurface.getTransformMatrix(mSTMatrix);
updateSurface = false;
}
}
GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glUseProgram(mProgram);
checkGlError("glUseProgram");
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID);
mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
checkGlError("glVertexAttribPointer maPosition");
GLES20.glEnableVertexAttribArray(maPositionHandle);
checkGlError("glEnableVertexAttribArray maPositionHandle");
mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
GLES20.glVertexAttribPointer(maTextureHandle, 3, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
checkGlError("glVertexAttribPointer maTextureHandle");
GLES20.glEnableVertexAttribArray(maTextureHandle);
checkGlError("glEnableVertexAttribArray maTextureHandle");
Matrix.setIdentityM(mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(muSTMatrixHandle, 1, false, mSTMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
checkGlError("glDrawArrays");
GLES20.glFinish();
}
public void onSurfaceChanged(GL10 glUnused, int width, int height) {
}
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
mProgram = createProgram(mVertexShader, mFragmentShader);
if (mProgram == 0) {
return;
}
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
checkGlError("glGetAttribLocation aPosition");
if (maPositionHandle == -1) {
throw new RuntimeException("Could not get attrib location for aPosition");
}
maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord");
checkGlError("glGetAttribLocation aTextureCoord");
if (maTextureHandle == -1) {
throw new RuntimeException("Could not get attrib location for aTextureCoord");
}
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
checkGlError("glGetUniformLocation uMVPMatrix");
if (muMVPMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uMVPMatrix");
}
muSTMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix");
checkGlError("glGetUniformLocation uSTMatrix");
if (muSTMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uSTMatrix");
}
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
mTextureID = textures[0];
GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureID);
checkGlError("glBindTexture mTextureID");
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER,
GLES20.GL_NEAREST);
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER,
GLES20.GL_LINEAR);
/*
* Create the SurfaceTexture that will feed this textureID,
* and pass it to the MediaPlayer
*/
mSurface = new SurfaceTexture(mTextureID);
mSurface.setOnFrameAvailableListener(this);
Surface surface = new Surface(mSurface);
mMediaPlayer.setSurface(surface);
surface.release();
try {
mMediaPlayer.prepare();
} catch (IOException t) {
Log.e(TAG, "media player prepare failed");
}
synchronized(this) {
updateSurface = false;
}
mMediaPlayer.start();
}
synchronized public void onFrameAvailable(SurfaceTexture surface) {
updateSurface = true;
}
private int loadShader(int shaderType, String source) {
int shader = GLES20.glCreateShader(shaderType);
if (shader != 0) {
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
int[] compiled = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) {
Log.e(TAG, "Could not compile shader " + shaderType + ":");
Log.e(TAG, GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
private int createProgram(String vertexSource, String fragmentSource) {
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0) {
return 0;
}
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0) {
return 0;
}
int program = GLES20.glCreateProgram();
if (program != 0) {
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
GLES20.glLinkProgram(program);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
Log.e(TAG, "Could not link program: ");
Log.e(TAG, GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
}
return program;
}
private void checkGlError(String op) {
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
Log.e(TAG, op + ": glError " + error);
throw new RuntimeException(op + ": glError " + error);
}
}
} // End of class VideoRender.
} // End of class VideoSurfaceView.
```
|
I just converted the Java to Kotlin version
```
internal inline fun <T> glRun(message: String = "", block: (() -> T)): T {
return block().also {
var error: Int = GLES20.glGetError()
while (error != GLES20.GL_NO_ERROR) {
error = GLES20.glGetError()
Log.d("MOVIE_GL_ERROR", "$message: $error")
throw RuntimeException("GL Error: $message")
}
}
}
class MovieRenderer: GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {
private var program = 0
private var textureId = 0
// Handles
private var mvpMatrixHandle = 0
private var stMatrixHandle = 0
private var positionHandle = 0
private var textureHandle = 0
// Surface Texture
private var updateSurface = false
private lateinit var surfaceTexture: SurfaceTexture
// Matrices
private var mvpMatrix = FloatArray(16)
private var stMatrix = FloatArray(16)
// float buffer
private val vertices: FloatBuffer = ByteBuffer.allocateDirect(VERTICES_DATA.size * FLOAT_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer().also {
it.put(VERTICES_DATA).position(0)
}
var mediaPlayer: MediaPlayer? = null
@Synchronized
override fun onFrameAvailable(surfaceTexture: SurfaceTexture?) {
updateSurface = true
}
override fun onDrawFrame(gl: GL10?) {
synchronized(this) {
if (updateSurface) {
surfaceTexture.updateTexImage()
surfaceTexture.getTransformMatrix(stMatrix)
updateSurface = false
}
}
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f)
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT or GLES20.GL_COLOR_BUFFER_BIT)
glRun("glUseProgram: $program") {
GLES20.glUseProgram(program)
}
vertices.position(VERTICES_POS_OFFSET);
glRun("glVertexAttribPointer: Stride bytes") {
GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT, false,
VERTICES_STRIDE_BYTES, vertices)
}
glRun("glEnableVertexAttribArray") {
GLES20.glEnableVertexAttribArray(positionHandle)
}
vertices.position(VERTICES_UV_OFFSET)
glRun("glVertexAttribPointer: texture handle") {
GLES20.glVertexAttribPointer(textureHandle, 3, GLES20.GL_FLOAT, false,
VERTICES_STRIDE_BYTES, vertices)
}
glRun("glEnableVertexAttribArray") {
GLES20.glEnableVertexAttribArray(textureHandle)
}
Matrix.setIdentityM(mvpMatrix, 0)
glRun("glUniformMatrix4fv: mvpMatrix") {
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false, mvpMatrix, 0)
}
glRun("glUniformMatrix4fv: stMatrix") {
GLES20.glUniformMatrix4fv(stMatrixHandle, 1, false, stMatrix, 0)
}
glRun("glDrawArrays: GL_TRIANGLE_STRIP") {
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4)
}
GLES20.glFinish()
}
override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
GLES20.glViewport(0, 0, width, height)
}
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
program = createProgram()
positionHandle = "aPosition".attr()
textureHandle = "aTextureCoord".attr()
mvpMatrixHandle = "uMVPMatrix".uniform()
stMatrixHandle = "uSTMatrix".uniform()
createTexture()
}
private fun createTexture() {
val textures = IntArray(1)
GLES20.glGenTextures(1, textures, 0)
textureId = textures.first()
glRun("glBindTexture textureId") { GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, textureId) }
GLES20.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST)
GLES20.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
surfaceTexture = SurfaceTexture(textureId)
surfaceTexture.setOnFrameAvailableListener(this)
val surface = Surface(surfaceTexture)
mediaPlayer?.setSurface(surface)
surface.release()
try {
mediaPlayer?.prepare()
} catch (error: IOException) {
Log.e("MovieRenderer", "media player prepare failed");
throw error
}
synchronized(this) {
updateSurface = false
}
mediaPlayer?.start()
}
private fun String.attr(): Int {
return glRun("Get attribute location: $this") {
GLES20.glGetAttribLocation(program, this).also {
if (it == -1) fail("Error Attribute: $this not found!")
}
}
}
private fun String.uniform(): Int {
return glRun("Get uniform location: $this") {
GLES20.glGetUniformLocation(program, this).also {
if (it == -1) fail("Error Uniform: $this not found!")
}
}
}
companion object {
private const val GL_TEXTURE_EXTERNAL_OES = 0x8D65
private const val FLOAT_SIZE_BYTES = 4
private const val VERTICES_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES
private const val VERTICES_POS_OFFSET = 0
private const val VERTICES_UV_OFFSET = 3
private val VERTICES_DATA = floatArrayOf(
-1.0f, -1.0f, 0f, 0.0f, 0.0f,
1.0f, -1.0f, 0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0f, 0.0f, 1.0f,
1.0f, 1.0f, 0f, 1.0f, 1.0f
)
private const val VERTEX_SHADER = """
uniform mat4 uMVPMatrix;
uniform mat4 uSTMatrix;
attribute vec4 aPosition;
attribute vec4 aTextureCoord;
varying vec2 vTextureCoord;
void main() {
gl_Position = uMVPMatrix * aPosition;
vTextureCoord = (uSTMatrix * aTextureCoord).xy;
}
"""
private const val FRAGMENT_SHADER = """
#extension GL_OES_EGL_image_external : require
precision mediump float;
varying vec2 vTextureCoord;
uniform samplerExternalOES sTexture;
void main() {
gl_FragColor = texture2D(sTexture, vTextureCoord);
}
"""
private fun createShader(type: Int, source: String): Int {
val shader = GLES20.glCreateShader(type)
if (shader == 0) throw RuntimeException("Cannot create shader $type\n$source")
GLES20.glShaderSource(shader, source)
GLES20.glCompileShader(shader)
val args = IntArray(1)
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, args, 0)
if (args.first() == 0) {
Log.e("MOVIE_SHADER", "Failed to compile shader source")
Log.e("MOVIE_SHADER", GLES20.glGetShaderInfoLog(shader))
GLES20.glDeleteShader(shader)
throw RuntimeException("Could not compile shader $source\n$type")
}
return shader
}
private fun createProgram(vertexShaderSource: String = VERTEX_SHADER,
fragmentShaderSource: String = FRAGMENT_SHADER): Int {
val vertexShader = createShader(GLES20.GL_VERTEX_SHADER, vertexShaderSource)
val fragmentShader = createShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderSource)
val program = GLES20.glCreateProgram()
if (program == 0) throw RuntimeException("Cannot create program")
glRun("Attach vertex shader to program") {
GLES20.glAttachShader(program, vertexShader)
}
glRun("Attach fragment shader to program") {
GLES20.glAttachShader(program, fragmentShader)
}
GLES20.glLinkProgram(program)
val args = IntArray(1)
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, args, 0)
if (args.first() != GLES20.GL_TRUE) {
val info = GLES20.glGetProgramInfoLog(program)
GLES20.glDeleteProgram(program)
throw RuntimeException("Cannot link program $program, Info: $info")
}
return program
}
private fun fail(message: String): Nothing {
throw RuntimeException(message)
}
}
}
```
|
9,375,598 |
Need to help
1. How play video on `Surface(OpenGL)` in Android?
I tried playing video in `mySurfaceView extends SurfaceView` with help method `setSurface()` in `MediaPlayer`.
```
SurfaceTexture mTexture = new SurfaceTexture(texture_id);
Surface mSurface = new Surface(mTexture);
MediaPlayer mp = new MediaPlayer();
mp.setSurface(mSurface);
```
I got only playing audio - video not playing.
2. How get video buffer for sending in `OpenGL`??
3. How playing video on `GLTexture`?
|
2012/02/21
|
[
"https://Stackoverflow.com/questions/9375598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221256/"
] |
I just converted the Java to Kotlin version
```
internal inline fun <T> glRun(message: String = "", block: (() -> T)): T {
return block().also {
var error: Int = GLES20.glGetError()
while (error != GLES20.GL_NO_ERROR) {
error = GLES20.glGetError()
Log.d("MOVIE_GL_ERROR", "$message: $error")
throw RuntimeException("GL Error: $message")
}
}
}
class MovieRenderer: GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {
private var program = 0
private var textureId = 0
// Handles
private var mvpMatrixHandle = 0
private var stMatrixHandle = 0
private var positionHandle = 0
private var textureHandle = 0
// Surface Texture
private var updateSurface = false
private lateinit var surfaceTexture: SurfaceTexture
// Matrices
private var mvpMatrix = FloatArray(16)
private var stMatrix = FloatArray(16)
// float buffer
private val vertices: FloatBuffer = ByteBuffer.allocateDirect(VERTICES_DATA.size * FLOAT_SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer().also {
it.put(VERTICES_DATA).position(0)
}
var mediaPlayer: MediaPlayer? = null
@Synchronized
override fun onFrameAvailable(surfaceTexture: SurfaceTexture?) {
updateSurface = true
}
override fun onDrawFrame(gl: GL10?) {
synchronized(this) {
if (updateSurface) {
surfaceTexture.updateTexImage()
surfaceTexture.getTransformMatrix(stMatrix)
updateSurface = false
}
}
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f)
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT or GLES20.GL_COLOR_BUFFER_BIT)
glRun("glUseProgram: $program") {
GLES20.glUseProgram(program)
}
vertices.position(VERTICES_POS_OFFSET);
glRun("glVertexAttribPointer: Stride bytes") {
GLES20.glVertexAttribPointer(positionHandle, 3, GLES20.GL_FLOAT, false,
VERTICES_STRIDE_BYTES, vertices)
}
glRun("glEnableVertexAttribArray") {
GLES20.glEnableVertexAttribArray(positionHandle)
}
vertices.position(VERTICES_UV_OFFSET)
glRun("glVertexAttribPointer: texture handle") {
GLES20.glVertexAttribPointer(textureHandle, 3, GLES20.GL_FLOAT, false,
VERTICES_STRIDE_BYTES, vertices)
}
glRun("glEnableVertexAttribArray") {
GLES20.glEnableVertexAttribArray(textureHandle)
}
Matrix.setIdentityM(mvpMatrix, 0)
glRun("glUniformMatrix4fv: mvpMatrix") {
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false, mvpMatrix, 0)
}
glRun("glUniformMatrix4fv: stMatrix") {
GLES20.glUniformMatrix4fv(stMatrixHandle, 1, false, stMatrix, 0)
}
glRun("glDrawArrays: GL_TRIANGLE_STRIP") {
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4)
}
GLES20.glFinish()
}
override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
GLES20.glViewport(0, 0, width, height)
}
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
program = createProgram()
positionHandle = "aPosition".attr()
textureHandle = "aTextureCoord".attr()
mvpMatrixHandle = "uMVPMatrix".uniform()
stMatrixHandle = "uSTMatrix".uniform()
createTexture()
}
private fun createTexture() {
val textures = IntArray(1)
GLES20.glGenTextures(1, textures, 0)
textureId = textures.first()
glRun("glBindTexture textureId") { GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, textureId) }
GLES20.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST)
GLES20.glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
surfaceTexture = SurfaceTexture(textureId)
surfaceTexture.setOnFrameAvailableListener(this)
val surface = Surface(surfaceTexture)
mediaPlayer?.setSurface(surface)
surface.release()
try {
mediaPlayer?.prepare()
} catch (error: IOException) {
Log.e("MovieRenderer", "media player prepare failed");
throw error
}
synchronized(this) {
updateSurface = false
}
mediaPlayer?.start()
}
private fun String.attr(): Int {
return glRun("Get attribute location: $this") {
GLES20.glGetAttribLocation(program, this).also {
if (it == -1) fail("Error Attribute: $this not found!")
}
}
}
private fun String.uniform(): Int {
return glRun("Get uniform location: $this") {
GLES20.glGetUniformLocation(program, this).also {
if (it == -1) fail("Error Uniform: $this not found!")
}
}
}
companion object {
private const val GL_TEXTURE_EXTERNAL_OES = 0x8D65
private const val FLOAT_SIZE_BYTES = 4
private const val VERTICES_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES
private const val VERTICES_POS_OFFSET = 0
private const val VERTICES_UV_OFFSET = 3
private val VERTICES_DATA = floatArrayOf(
-1.0f, -1.0f, 0f, 0.0f, 0.0f,
1.0f, -1.0f, 0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0f, 0.0f, 1.0f,
1.0f, 1.0f, 0f, 1.0f, 1.0f
)
private const val VERTEX_SHADER = """
uniform mat4 uMVPMatrix;
uniform mat4 uSTMatrix;
attribute vec4 aPosition;
attribute vec4 aTextureCoord;
varying vec2 vTextureCoord;
void main() {
gl_Position = uMVPMatrix * aPosition;
vTextureCoord = (uSTMatrix * aTextureCoord).xy;
}
"""
private const val FRAGMENT_SHADER = """
#extension GL_OES_EGL_image_external : require
precision mediump float;
varying vec2 vTextureCoord;
uniform samplerExternalOES sTexture;
void main() {
gl_FragColor = texture2D(sTexture, vTextureCoord);
}
"""
private fun createShader(type: Int, source: String): Int {
val shader = GLES20.glCreateShader(type)
if (shader == 0) throw RuntimeException("Cannot create shader $type\n$source")
GLES20.glShaderSource(shader, source)
GLES20.glCompileShader(shader)
val args = IntArray(1)
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, args, 0)
if (args.first() == 0) {
Log.e("MOVIE_SHADER", "Failed to compile shader source")
Log.e("MOVIE_SHADER", GLES20.glGetShaderInfoLog(shader))
GLES20.glDeleteShader(shader)
throw RuntimeException("Could not compile shader $source\n$type")
}
return shader
}
private fun createProgram(vertexShaderSource: String = VERTEX_SHADER,
fragmentShaderSource: String = FRAGMENT_SHADER): Int {
val vertexShader = createShader(GLES20.GL_VERTEX_SHADER, vertexShaderSource)
val fragmentShader = createShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderSource)
val program = GLES20.glCreateProgram()
if (program == 0) throw RuntimeException("Cannot create program")
glRun("Attach vertex shader to program") {
GLES20.glAttachShader(program, vertexShader)
}
glRun("Attach fragment shader to program") {
GLES20.glAttachShader(program, fragmentShader)
}
GLES20.glLinkProgram(program)
val args = IntArray(1)
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, args, 0)
if (args.first() != GLES20.GL_TRUE) {
val info = GLES20.glGetProgramInfoLog(program)
GLES20.glDeleteProgram(program)
throw RuntimeException("Cannot link program $program, Info: $info")
}
return program
}
private fun fail(message: String): Nothing {
throw RuntimeException(message)
}
}
}
```
|
```
mMediaPlayer.setSurface(new Surface(mSurfaceTexture));
```
You can use above line of code to use it on your mediaPlayerObject over your desired surfaceTexture which is a applied texture over your surfaceview.
Hope that helps.
|
475,762 |
Suppose, I use Debian unstable or experimental version as guest OS. After installing new software it completely breaks the system. Can it also affect host OS?
|
2012/09/16
|
[
"https://superuser.com/questions/475762",
"https://superuser.com",
"https://superuser.com/users/34379/"
] |
Depending on the virtual machine, it can be possible.
For example, if the VM software has 3D acceleration enabled, then it gives the guest much more access to your graphics card than you might expect. There also have been several bugs in various virtualization software that would allow the guest to obtain the same privileges as the host.
But although this can be used by malicious software running in the guest, it is very unlikely to happen accidentally. If you merely destroy the guest OS in some way or another, there is no way it can affect the host.
|
In normal circumstances, no. The virtual machine is completely separated from the host machine.
But it is sometimes possible to share a folder between the host and the guest, and in that way is it possible to do harmful things to the host. Or you could connect in the guest to the host via internet and do bad things that way. But otherwise, it is quite safe to experiment in a virtual machine.
Note: depending on the virtualisation software, the guest file system is stored in a single file somewhere on the host. But it isn't possible for the guest to easily break out of the sandbox the virtualisation software provides.
|
475,762 |
Suppose, I use Debian unstable or experimental version as guest OS. After installing new software it completely breaks the system. Can it also affect host OS?
|
2012/09/16
|
[
"https://superuser.com/questions/475762",
"https://superuser.com",
"https://superuser.com/users/34379/"
] |
Most of the answers here discuss the virtual machine itself (as does your question) - but the real concern lies with the virtualization software. The concern is that virtualization software has a vulnerability in it's virtualized environment, or doesn't protect the host operating system. Most available virtualization products are pretty solid and have good track records of stability and security.
|
In normal circumstances, no. The virtual machine is completely separated from the host machine.
But it is sometimes possible to share a folder between the host and the guest, and in that way is it possible to do harmful things to the host. Or you could connect in the guest to the host via internet and do bad things that way. But otherwise, it is quite safe to experiment in a virtual machine.
Note: depending on the virtualisation software, the guest file system is stored in a single file somewhere on the host. But it isn't possible for the guest to easily break out of the sandbox the virtualisation software provides.
|
475,762 |
Suppose, I use Debian unstable or experimental version as guest OS. After installing new software it completely breaks the system. Can it also affect host OS?
|
2012/09/16
|
[
"https://superuser.com/questions/475762",
"https://superuser.com",
"https://superuser.com/users/34379/"
] |
Depending on the virtual machine, it can be possible.
For example, if the VM software has 3D acceleration enabled, then it gives the guest much more access to your graphics card than you might expect. There also have been several bugs in various virtualization software that would allow the guest to obtain the same privileges as the host.
But although this can be used by malicious software running in the guest, it is very unlikely to happen accidentally. If you merely destroy the guest OS in some way or another, there is no way it can affect the host.
|
Most of the answers here discuss the virtual machine itself (as does your question) - but the real concern lies with the virtualization software. The concern is that virtualization software has a vulnerability in it's virtualized environment, or doesn't protect the host operating system. Most available virtualization products are pretty solid and have good track records of stability and security.
|
72,786,603 |
How do I compare several rows and find words/combination of words that are present in each row? Using pure python, nltk or anything else.
```py
few_strings = ('this is foo bar', 'this is not a foo bar', 'some other foo bar here')
# some magic
result = 'foo bar'
```
|
2022/06/28
|
[
"https://Stackoverflow.com/questions/72786603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4845952/"
] |
Split each string at whitespaces and save the resulting words into sets. Then, compute the intersection of the three sets:
```py
few_strings = ('this is foo bar', 'this is not a foo bar', 'some other foo bar here')
sets = [set(s.split()) for s in few_strings]
common_words = sets[0].intersection(*sets[1:])
print(common_words)
```
Output:
```
{'bar', 'foo'}
```
|
```
few_strings = ('this is foo bar', 'this is not a foo bar', 'some other foo bar here')
```
1. Create sets of words for each sentence splitting by space (`" "`)
2. Add the first string to results
3. Loop over the sentences and update `result` variable with the interesction of the current result and one sentence
```
# 1.
sets = [set(s.split(" ")) for s in few_strings]
# 2.
result = sets[0]
# 3.
for i in range(len(sets)):
result = result.intersection(sets[i])
```
Now you have a Python `Set` of words which occured in all sentences.
You can convert the set to list with:
```
result = list(result)
```
or to string with
```
result = " ".join(result)
```
|
72,786,603 |
How do I compare several rows and find words/combination of words that are present in each row? Using pure python, nltk or anything else.
```py
few_strings = ('this is foo bar', 'this is not a foo bar', 'some other foo bar here')
# some magic
result = 'foo bar'
```
|
2022/06/28
|
[
"https://Stackoverflow.com/questions/72786603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4845952/"
] |
Split each string at whitespaces and save the resulting words into sets. Then, compute the intersection of the three sets:
```py
few_strings = ('this is foo bar', 'this is not a foo bar', 'some other foo bar here')
sets = [set(s.split()) for s in few_strings]
common_words = sets[0].intersection(*sets[1:])
print(common_words)
```
Output:
```
{'bar', 'foo'}
```
|
You can do it without using libraries too
```
few_strings = ('this is foo bar', 'some other foo bar here', 'this is not a foo bar')
strings = [s.split() for s in few_strings]
strings.sort(key=len)
print(strings)
result = ''
for word in strings[0]:
count = 0
for string in strings:
if word not in string:
break
else:
count += 1
if count == len(strings):
result += word + ' '
print(result)
```
|
72,786,603 |
How do I compare several rows and find words/combination of words that are present in each row? Using pure python, nltk or anything else.
```py
few_strings = ('this is foo bar', 'this is not a foo bar', 'some other foo bar here')
# some magic
result = 'foo bar'
```
|
2022/06/28
|
[
"https://Stackoverflow.com/questions/72786603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4845952/"
] |
You might want to use the standard library `difflib` for sequence comparisons including finding common substrings:
```py
from difflib import SequenceMatcher
list_of_str = ['this is foo bar', 'this is not a foo bar', 'some other foo bar here']
result = list_of_str[0]
for next_string in list_of_str:
match = SequenceMatcher(None, result, next_string).find_longest_match()
result = result[match.a:match.a + match.size]
# result be 'foo bar'
```
* The [documentation](https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.find_longest_match)
* The [two-string example](https://stackoverflow.com/questions/18715688/find-common-substring-between-two-strings):
```py
from difflib import SequenceMatcher
string1 = "apple pie available"
string2 = "come have some apple pies"
match = SequenceMatcher(None, string1, string2).find_longest_match()
print(match) # -> Match(a=0, b=15, size=9)
print(string1[match.a:match.a + match.size]) # -> apple pie
print(string2[match.b:match.b + match.size]) # -> apple pie
```
|
```
few_strings = ('this is foo bar', 'this is not a foo bar', 'some other foo bar here')
```
1. Create sets of words for each sentence splitting by space (`" "`)
2. Add the first string to results
3. Loop over the sentences and update `result` variable with the interesction of the current result and one sentence
```
# 1.
sets = [set(s.split(" ")) for s in few_strings]
# 2.
result = sets[0]
# 3.
for i in range(len(sets)):
result = result.intersection(sets[i])
```
Now you have a Python `Set` of words which occured in all sentences.
You can convert the set to list with:
```
result = list(result)
```
or to string with
```
result = " ".join(result)
```
|
72,786,603 |
How do I compare several rows and find words/combination of words that are present in each row? Using pure python, nltk or anything else.
```py
few_strings = ('this is foo bar', 'this is not a foo bar', 'some other foo bar here')
# some magic
result = 'foo bar'
```
|
2022/06/28
|
[
"https://Stackoverflow.com/questions/72786603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4845952/"
] |
You might want to use the standard library `difflib` for sequence comparisons including finding common substrings:
```py
from difflib import SequenceMatcher
list_of_str = ['this is foo bar', 'this is not a foo bar', 'some other foo bar here']
result = list_of_str[0]
for next_string in list_of_str:
match = SequenceMatcher(None, result, next_string).find_longest_match()
result = result[match.a:match.a + match.size]
# result be 'foo bar'
```
* The [documentation](https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.find_longest_match)
* The [two-string example](https://stackoverflow.com/questions/18715688/find-common-substring-between-two-strings):
```py
from difflib import SequenceMatcher
string1 = "apple pie available"
string2 = "come have some apple pies"
match = SequenceMatcher(None, string1, string2).find_longest_match()
print(match) # -> Match(a=0, b=15, size=9)
print(string1[match.a:match.a + match.size]) # -> apple pie
print(string2[match.b:match.b + match.size]) # -> apple pie
```
|
You can do it without using libraries too
```
few_strings = ('this is foo bar', 'some other foo bar here', 'this is not a foo bar')
strings = [s.split() for s in few_strings]
strings.sort(key=len)
print(strings)
result = ''
for word in strings[0]:
count = 0
for string in strings:
if word not in string:
break
else:
count += 1
if count == len(strings):
result += word + ' '
print(result)
```
|
55,183,295 |
My ultimate goal is to achieve a mapping from a set of two character strings to corresponding data types:
```
"AA" --> char
"BB" --> int
"CC" --> float
"DD" --> std::complex<double>
and so on ...
```
The best "not quite working" solution I can come up with is two parts. The first part is using std::map to map between the strings and corresponding enum values. The second part uses a templated type alias and std::conditional to map the enum values to types.
```
enum class StrEnum { AA, BB, CC, DD };
// STEP 1: string --> enum
// !! std::map will not work here since a constexpr is required !!
std::map<std::string, StrEnum> str_map = {
{"AA", StrEnum::AA},
{"BB", StrEnum::BB},
{"CC", StrEnum::CC},
{"DD", StrEnum::DD}
};
// STEP 2: enum --> type
template<StrEnum val> using StrType = typename std::conditional<
val == StrEnum::AA,
char,
typename std::conditional<
val == StrEnum::BB,
int,
typename std::conditional<
val == StrEnum::CC,
float,
std::complex<double>
>::type
>::type
>::type;
```
Goal Usage:
`StrType<str_map["BB"]> myVal; // <-- does not work in current state with std::map`
As more value mappings are added the above nesting can get very nasty.
Is there a better/cleaner/working overall way to achieve this mapping? I'm especially interested in STEP 2 and whether there is a way to have less nesting.
I am using C++11. (but if the only answer lies in C++14 or beyond it would be nice to at least be aware of it)
|
2019/03/15
|
[
"https://Stackoverflow.com/questions/55183295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5144595/"
] |
Since `std::map` does not have constexpr ctors, your template argument `str_map["BB"]` can not be evaluated at compile-time.
A simple and maintainable way to map **integers to types** would be using `std::tuple` and `std::tuple_element` as follows.
For instance, `StrType<0>` is `char`, `StrType<1>` is `int`, and so on:
```
using types = std::tuple<char, int, float, std::complex<double>>;
template<std::size_t N>
using StrType = typename std::tuple_element<N, types>::type;
```
Then the problem is how to map **strings to integers** in C++11.
First, strings can be compared at compile-time by the [accepted answer](https://stackoverflow.com/questions/27490858/how-can-you-compare-two-character-strings-statically-at-compile-time) in this post.
Second, we can use the ternary operator in compile-time evaluations.
Thus, at least the following function `getIdx` can map each string to the corresponding integer at compile-time.
For instance, `getIdx("AA")` is zero:
```
constexpr bool strings_equal(const char* a, const char* b) {
return *a == *b && (*a == '\0' || strings_equal(a + 1, b + 1));
}
constexpr std::size_t getIdx(const char* name)
{
return strings_equal(name, "AA") ? 0:
strings_equal(name, "BB") ? 1:
strings_equal(name, "CC") ? 2:
strings_equal(name, "DD") ? 3:
4; // compilation error
}
```
You can use these functions for the current purpose as follows:
[**DEMO**](https://wandbox.org/permlink/HOWwo2rCABq8S7bC)
```
StrType<getIdx("BB")> x; // x is int.
constexpr const char* float_type = "CC";
StrType<getIdx(float_type)> y; // y is float.
static_assert(std::is_same<StrType<getIdx("AA")>, char> ::value, "oops."); // OK.
static_assert(std::is_same<StrType<getIdx("BB")>, int> ::value, "oops."); // OK.
static_assert(std::is_same<StrType<getIdx("CC")>, float>::value, "oops."); // OK.
static_assert(std::is_same<StrType<getIdx("DD")>, std::complex<double>>::value, "oops."); // OK.
```
|
I recentlly worked on something like that. My proposed solution was something like this (with a lot more stuff but here the main idea):
```
//Define a Type for ID
using TypeIdentifier = size_t;
//Define a ID generator
struct id_generator {
static TypeIdentifier create_id() {
static TypeIdentifier value = 0;
return value++;
}
};
//Define some kind of handler for place
struct type_id_handler {
static std::vector<std::function<void(void*)>> type_handler;
};
std::vector<std::function<void(void*)>> type_id_handler::type_handler;
//Define id's and make a basic functions
template<typename T>
struct type_id_define {
static TypeIdentifier get_id() {
static TypeIdentifier id = id_generator::create_id();
static auto one_time_stuff = [] () -> bool {
type_id_handler::type_handler.resize(id+1);
type_id_handler::type_handler[id] = [](void* ptr) {
auto * object = static_cast<T*>(ptr);
//do stuff your type
std::cout << __PRETTY_FUNCTION__ << std::endl;
};
return true;
}();
return id;
}
};
```
For main dummy test:
```
int main() {
std::map<std::string, TypeIdentifier> typeMap {
{"AA", type_id_define<char>::get_id()},
{"BB", type_id_define<int>::get_id()},
};
int a;
char b;
type_id_handler::type_handler[typeMap["BB"]](&a);
type_id_handler::type_handler[typeMap["AA"]](&b);
return 0;
}
```
Output should be:
```
type_id_define<T>::get_id()::<lambda()>::<lambda(void*)> [with T = int]
type_id_define<T>::get_id()::<lambda()>::<lambda(void*)> [with T = char]
```
The main idea is to make a new `type_id_define` with the proper id for each type and use it as a index for select the correct function to execute. Also when generating the id it store a function for cast from `void*` to given type (I use void\* for store different type function on same vector) After that you can use std::any, void\*, or whatever you want for pass the object to the function and get type-safety.
If you want to use something like that I Also recommend you to think about better way for register types and add the corresponding function.
|
7,783,684 |
I have a database of coordinates in the schema:
ID:Latitude:Longitude:name:desc
I've set up my google maps application to show the markers effectively on the screen. However I need to add another feature whereby the user can view all pointers that fall within the radius from a central point.
How would I write up a sql statement of the kind:
```
Select all pointers that fall within a 10 mile radius of X & Y
```
|
2011/10/16
|
[
"https://Stackoverflow.com/questions/7783684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89752/"
] |
The SQL below should work:
```
SELECT * FROM Table1 a
WHERE (
acos(sin(a.Latitude * 0.0175) * sin(YOUR_LATITUDE_X * 0.0175)
+ cos(a.Latitude * 0.0175) * cos(YOUR_LATITUDE_X * 0.0175) *
cos((YOUR_LONGITUDE_Y * 0.0175) - (a.Longitude * 0.0175))
) * 3959 <= YOUR_RADIUS_INMILES
)
```
This is based on the spherical law of cosines, for more detailed information on the topic, check out this article - <http://www.movable-type.co.uk/scripts/latlong.html>
|
You probably need to do this in two steps. Select the points that lie within a 20 mile square with it's centre at X,Y. Assuming you calculate the top,left and bottom,right coordinates of the square first you can get all the points inside the square from the database with:
```
select * from coordinates where longitude < right and longitude > left and
latitude < top and latitude > bottom;
```
The second step is to see whether the set of points is inside the 10 mile radius circle. At this point I would be tempted to use Google maps to calculate the distance between the points and the centre of your square using the `google.maps.geometry.spherical.computeDistanceBetween(from:LatLng, to:LatLng, radius?:number)`function. Check the answer is less than 10 miles. This function uses the radius of the earth as a default.
|
7,783,684 |
I have a database of coordinates in the schema:
ID:Latitude:Longitude:name:desc
I've set up my google maps application to show the markers effectively on the screen. However I need to add another feature whereby the user can view all pointers that fall within the radius from a central point.
How would I write up a sql statement of the kind:
```
Select all pointers that fall within a 10 mile radius of X & Y
```
|
2011/10/16
|
[
"https://Stackoverflow.com/questions/7783684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89752/"
] |
You probably need to do this in two steps. Select the points that lie within a 20 mile square with it's centre at X,Y. Assuming you calculate the top,left and bottom,right coordinates of the square first you can get all the points inside the square from the database with:
```
select * from coordinates where longitude < right and longitude > left and
latitude < top and latitude > bottom;
```
The second step is to see whether the set of points is inside the 10 mile radius circle. At this point I would be tempted to use Google maps to calculate the distance between the points and the centre of your square using the `google.maps.geometry.spherical.computeDistanceBetween(from:LatLng, to:LatLng, radius?:number)`function. Check the answer is less than 10 miles. This function uses the radius of the earth as a default.
|
This SQL gives more accurate answer:
```sql
SELECT *
FROM Table1 a
WHERE 1 = 1
AND 2 * 3961 * asin(sqrt( power((sin(radians((X - cast(a.latitude as decimal(10,8))) / 2))) , 2) + cast(cos(radians(cast(a.latitude as decimal(18,8)))) * cos(radians(X)) * power((sin(radians((Y - cast(a.long as decimal(18,8))) / 2))) , 2) as decimal(18,10) ))) <= Radius_In_Miles
```
X = Latitude of Centroid
Y = Longitude of Centroid
I did it in Redshift, so I had to use cast to prevent numeric value overflow error.
Reference: <http://daynebatten.com/2015/09/latitude-longitude-distance-sql/>
|
7,783,684 |
I have a database of coordinates in the schema:
ID:Latitude:Longitude:name:desc
I've set up my google maps application to show the markers effectively on the screen. However I need to add another feature whereby the user can view all pointers that fall within the radius from a central point.
How would I write up a sql statement of the kind:
```
Select all pointers that fall within a 10 mile radius of X & Y
```
|
2011/10/16
|
[
"https://Stackoverflow.com/questions/7783684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89752/"
] |
The SQL below should work:
```
SELECT * FROM Table1 a
WHERE (
acos(sin(a.Latitude * 0.0175) * sin(YOUR_LATITUDE_X * 0.0175)
+ cos(a.Latitude * 0.0175) * cos(YOUR_LATITUDE_X * 0.0175) *
cos((YOUR_LONGITUDE_Y * 0.0175) - (a.Longitude * 0.0175))
) * 3959 <= YOUR_RADIUS_INMILES
)
```
This is based on the spherical law of cosines, for more detailed information on the topic, check out this article - <http://www.movable-type.co.uk/scripts/latlong.html>
|
This SQL gives more accurate answer:
```sql
SELECT *
FROM Table1 a
WHERE 1 = 1
AND 2 * 3961 * asin(sqrt( power((sin(radians((X - cast(a.latitude as decimal(10,8))) / 2))) , 2) + cast(cos(radians(cast(a.latitude as decimal(18,8)))) * cos(radians(X)) * power((sin(radians((Y - cast(a.long as decimal(18,8))) / 2))) , 2) as decimal(18,10) ))) <= Radius_In_Miles
```
X = Latitude of Centroid
Y = Longitude of Centroid
I did it in Redshift, so I had to use cast to prevent numeric value overflow error.
Reference: <http://daynebatten.com/2015/09/latitude-longitude-distance-sql/>
|
69,227,075 |
Writing a simple selenium script to click on links on aa website. The script is written like so:
```
from selenium import webdriver
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
browser = webdriver.Chrome(options=chrome_options)
try:
browser.get("https://www.google.com")
print("Page title was '{}'".format(browser.title))
finally:
browser.quit()
```
Now the issue is the actual chrome driver itself I get the following exception
```
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 94
Current browser version is 93.0.4577.82 with binary path /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
```
I went to the chromedriver downloads [site](https://chromedriver.chromium.org/downloads). I still get the same error though.
|
2021/09/17
|
[
"https://Stackoverflow.com/questions/69227075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3937811/"
] |
Compatibility issue.
Your `chrome driver` version is `94.0.4606.41` and this `driver` version supports `Chrome browser 94`
Please do anyone of the following.
* Update the `chrome browser` version to `94`
* Degrade the `driver` version to `93` (Download `93` version from here *<https://chromedriver.storage.googleapis.com/index.html?path=93.0.4577.63/>*)
|
I think there is another way to solve this problem. Uninstall the protarctor and reinstall it and see magic.
```
npm uninstall protractor
npm install protractor
```
[Session not created: This version of ChromeDriver only supports](https://medium.com/@prshannoct/session-not-created-this-version-of-chromedriver-only-supports-chrome-version-chromedrive-issue-3f17fd4e6a94)
|
69,227,075 |
Writing a simple selenium script to click on links on aa website. The script is written like so:
```
from selenium import webdriver
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
browser = webdriver.Chrome(options=chrome_options)
try:
browser.get("https://www.google.com")
print("Page title was '{}'".format(browser.title))
finally:
browser.quit()
```
Now the issue is the actual chrome driver itself I get the following exception
```
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 94
Current browser version is 93.0.4577.82 with binary path /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
```
I went to the chromedriver downloads [site](https://chromedriver.chromium.org/downloads). I still get the same error though.
|
2021/09/17
|
[
"https://Stackoverflow.com/questions/69227075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3937811/"
] |
Compatibility issue.
Your `chrome driver` version is `94.0.4606.41` and this `driver` version supports `Chrome browser 94`
Please do anyone of the following.
* Update the `chrome browser` version to `94`
* Degrade the `driver` version to `93` (Download `93` version from here *<https://chromedriver.storage.googleapis.com/index.html?path=93.0.4577.63/>*)
|
If you're using Mac run
```
brew reinstall chromedriver
```
|
69,227,075 |
Writing a simple selenium script to click on links on aa website. The script is written like so:
```
from selenium import webdriver
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
browser = webdriver.Chrome(options=chrome_options)
try:
browser.get("https://www.google.com")
print("Page title was '{}'".format(browser.title))
finally:
browser.quit()
```
Now the issue is the actual chrome driver itself I get the following exception
```
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 94
Current browser version is 93.0.4577.82 with binary path /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
```
I went to the chromedriver downloads [site](https://chromedriver.chromium.org/downloads). I still get the same error though.
|
2021/09/17
|
[
"https://Stackoverflow.com/questions/69227075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3937811/"
] |
Compatibility issue.
Your `chrome driver` version is `94.0.4606.41` and this `driver` version supports `Chrome browser 94`
Please do anyone of the following.
* Update the `chrome browser` version to `94`
* Degrade the `driver` version to `93` (Download `93` version from here *<https://chromedriver.storage.googleapis.com/index.html?path=93.0.4577.63/>*)
|
This made me go crazy I solved it like this we are using selenium npm module.
Run the code below and it will tell you what executable path you are using.
```
const { Builder, By, Key, util } = require("selenium-webdriver");
const chrome = require("selenium-webdriver/chrome");
console.log(chrome.getDefaultService().executable_);
```
I had installed chromedriver globally
```
npm i chromedriver -g
```
The executable path showed me it was using this and an older version.
Uninstalled this.
```
npm uninstall chromedriver -g
```
Now it started using the version I dowloaded and added to me PATH.
Download the latest chromedriver from here.
<https://chromedriver.chromium.org/downloads>
Add it to your path in the .zshrc file.
```
export PATH=/Users/dave/SeleniumWebdrivers:$PATH
```
Drag your downloaded drivers into this folder.
|
69,227,075 |
Writing a simple selenium script to click on links on aa website. The script is written like so:
```
from selenium import webdriver
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
browser = webdriver.Chrome(options=chrome_options)
try:
browser.get("https://www.google.com")
print("Page title was '{}'".format(browser.title))
finally:
browser.quit()
```
Now the issue is the actual chrome driver itself I get the following exception
```
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 94
Current browser version is 93.0.4577.82 with binary path /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
```
I went to the chromedriver downloads [site](https://chromedriver.chromium.org/downloads). I still get the same error though.
|
2021/09/17
|
[
"https://Stackoverflow.com/questions/69227075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3937811/"
] |
This error occurred because you have different versions of Google Chrome and driver. It is better to update the driver, rather than install the old version of Google, since in the future it will be constantly updated (why do you want to use outdated technologies?).
I usually use :
```
ChromeDriverManager
```
because at any time without going to the web driver website you can simply download the driver with the following command:
```
driver = webdriver.Chrome(ChromeDriverManager().install())
```
Further, using the path given by this command, you can use the freshly installed version:
```
driver = webdriver.Chrome(executable_path=r"C:\path_to_chrome_driver_executable\chromedriver.exe")
```
|
I think there is another way to solve this problem. Uninstall the protarctor and reinstall it and see magic.
```
npm uninstall protractor
npm install protractor
```
[Session not created: This version of ChromeDriver only supports](https://medium.com/@prshannoct/session-not-created-this-version-of-chromedriver-only-supports-chrome-version-chromedrive-issue-3f17fd4e6a94)
|
69,227,075 |
Writing a simple selenium script to click on links on aa website. The script is written like so:
```
from selenium import webdriver
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
browser = webdriver.Chrome(options=chrome_options)
try:
browser.get("https://www.google.com")
print("Page title was '{}'".format(browser.title))
finally:
browser.quit()
```
Now the issue is the actual chrome driver itself I get the following exception
```
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 94
Current browser version is 93.0.4577.82 with binary path /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
```
I went to the chromedriver downloads [site](https://chromedriver.chromium.org/downloads). I still get the same error though.
|
2021/09/17
|
[
"https://Stackoverflow.com/questions/69227075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3937811/"
] |
This error occurred because you have different versions of Google Chrome and driver. It is better to update the driver, rather than install the old version of Google, since in the future it will be constantly updated (why do you want to use outdated technologies?).
I usually use :
```
ChromeDriverManager
```
because at any time without going to the web driver website you can simply download the driver with the following command:
```
driver = webdriver.Chrome(ChromeDriverManager().install())
```
Further, using the path given by this command, you can use the freshly installed version:
```
driver = webdriver.Chrome(executable_path=r"C:\path_to_chrome_driver_executable\chromedriver.exe")
```
|
If you're using Mac run
```
brew reinstall chromedriver
```
|
69,227,075 |
Writing a simple selenium script to click on links on aa website. The script is written like so:
```
from selenium import webdriver
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
browser = webdriver.Chrome(options=chrome_options)
try:
browser.get("https://www.google.com")
print("Page title was '{}'".format(browser.title))
finally:
browser.quit()
```
Now the issue is the actual chrome driver itself I get the following exception
```
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 94
Current browser version is 93.0.4577.82 with binary path /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
```
I went to the chromedriver downloads [site](https://chromedriver.chromium.org/downloads). I still get the same error though.
|
2021/09/17
|
[
"https://Stackoverflow.com/questions/69227075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3937811/"
] |
This error occurred because you have different versions of Google Chrome and driver. It is better to update the driver, rather than install the old version of Google, since in the future it will be constantly updated (why do you want to use outdated technologies?).
I usually use :
```
ChromeDriverManager
```
because at any time without going to the web driver website you can simply download the driver with the following command:
```
driver = webdriver.Chrome(ChromeDriverManager().install())
```
Further, using the path given by this command, you can use the freshly installed version:
```
driver = webdriver.Chrome(executable_path=r"C:\path_to_chrome_driver_executable\chromedriver.exe")
```
|
This made me go crazy I solved it like this we are using selenium npm module.
Run the code below and it will tell you what executable path you are using.
```
const { Builder, By, Key, util } = require("selenium-webdriver");
const chrome = require("selenium-webdriver/chrome");
console.log(chrome.getDefaultService().executable_);
```
I had installed chromedriver globally
```
npm i chromedriver -g
```
The executable path showed me it was using this and an older version.
Uninstalled this.
```
npm uninstall chromedriver -g
```
Now it started using the version I dowloaded and added to me PATH.
Download the latest chromedriver from here.
<https://chromedriver.chromium.org/downloads>
Add it to your path in the .zshrc file.
```
export PATH=/Users/dave/SeleniumWebdrivers:$PATH
```
Drag your downloaded drivers into this folder.
|
69,227,075 |
Writing a simple selenium script to click on links on aa website. The script is written like so:
```
from selenium import webdriver
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
browser = webdriver.Chrome(options=chrome_options)
try:
browser.get("https://www.google.com")
print("Page title was '{}'".format(browser.title))
finally:
browser.quit()
```
Now the issue is the actual chrome driver itself I get the following exception
```
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 94
Current browser version is 93.0.4577.82 with binary path /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
```
I went to the chromedriver downloads [site](https://chromedriver.chromium.org/downloads). I still get the same error though.
|
2021/09/17
|
[
"https://Stackoverflow.com/questions/69227075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3937811/"
] |
If you're using Mac run
```
brew reinstall chromedriver
```
|
I think there is another way to solve this problem. Uninstall the protarctor and reinstall it and see magic.
```
npm uninstall protractor
npm install protractor
```
[Session not created: This version of ChromeDriver only supports](https://medium.com/@prshannoct/session-not-created-this-version-of-chromedriver-only-supports-chrome-version-chromedrive-issue-3f17fd4e6a94)
|
69,227,075 |
Writing a simple selenium script to click on links on aa website. The script is written like so:
```
from selenium import webdriver
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
browser = webdriver.Chrome(options=chrome_options)
try:
browser.get("https://www.google.com")
print("Page title was '{}'".format(browser.title))
finally:
browser.quit()
```
Now the issue is the actual chrome driver itself I get the following exception
```
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 94
Current browser version is 93.0.4577.82 with binary path /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
```
I went to the chromedriver downloads [site](https://chromedriver.chromium.org/downloads). I still get the same error though.
|
2021/09/17
|
[
"https://Stackoverflow.com/questions/69227075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3937811/"
] |
This made me go crazy I solved it like this we are using selenium npm module.
Run the code below and it will tell you what executable path you are using.
```
const { Builder, By, Key, util } = require("selenium-webdriver");
const chrome = require("selenium-webdriver/chrome");
console.log(chrome.getDefaultService().executable_);
```
I had installed chromedriver globally
```
npm i chromedriver -g
```
The executable path showed me it was using this and an older version.
Uninstalled this.
```
npm uninstall chromedriver -g
```
Now it started using the version I dowloaded and added to me PATH.
Download the latest chromedriver from here.
<https://chromedriver.chromium.org/downloads>
Add it to your path in the .zshrc file.
```
export PATH=/Users/dave/SeleniumWebdrivers:$PATH
```
Drag your downloaded drivers into this folder.
|
I think there is another way to solve this problem. Uninstall the protarctor and reinstall it and see magic.
```
npm uninstall protractor
npm install protractor
```
[Session not created: This version of ChromeDriver only supports](https://medium.com/@prshannoct/session-not-created-this-version-of-chromedriver-only-supports-chrome-version-chromedrive-issue-3f17fd4e6a94)
|
31,454,518 |
I have a two Database class objects allocated on Stack. I inherit this database class in my personal defined class. Now Database class has a function named "Close()" which throws an exception if closing that instance of database fails. Now for client perspective i don't want Client to call close() everytime to close the connection, rather i want to declare a vitrual Desctuctor in Database class which will automatically close the connection when object goes out of scope.
Now problem i am facing is, if i create two DB objects, and now try to delete both and if close succedds for both it's fine, but if close fails for first object it throws an exception, and now second is still allocated (if dynamically allocated member objects), which results in memory leak. How to handle this situation.
|
2015/07/16
|
[
"https://Stackoverflow.com/questions/31454518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312772/"
] |
you don't throw exception from the destructor what-so-ever!
See : <http://www.stroustrup.com/bs_faq2.html#ctor-exceptions>
Bjarne quote (can you throw exception from a d.tor):
>
> Not really: You can throw an exception in a destructor, but that exception must not leave the destructor; if a destructor exits by a throw, all kinds of bad things are likely to happen because the basic rules of the standard library and the language itself will be violated. Don't do it.
>
>
>
You might not want to allocate any DB object on the stack anyway, a safe, reusable way is to use Connection Pool :
<https://en.wikipedia.org/wiki/Object_pool_pattern>
like this, the destruction of each conenction object iswhen the program exist, where you can handle the closing as integral part of the pool, and not in a spread way in some random functions
|
Chances are that if `close` fails, there is not good recovery path anyway, you are best off logging the error and then carrying on as if it succeeded. So I would suggest you call `close` in a `try` block in you destructor and just logging the error in the corresponding `catch` block. The destructor can then complete normally.
As @David mentions above, destuctors should never leak exceptions, this is because destructors are called when an exception happens and an exception in an exception causes a crash.
|
31,454,518 |
I have a two Database class objects allocated on Stack. I inherit this database class in my personal defined class. Now Database class has a function named "Close()" which throws an exception if closing that instance of database fails. Now for client perspective i don't want Client to call close() everytime to close the connection, rather i want to declare a vitrual Desctuctor in Database class which will automatically close the connection when object goes out of scope.
Now problem i am facing is, if i create two DB objects, and now try to delete both and if close succedds for both it's fine, but if close fails for first object it throws an exception, and now second is still allocated (if dynamically allocated member objects), which results in memory leak. How to handle this situation.
|
2015/07/16
|
[
"https://Stackoverflow.com/questions/31454518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312772/"
] |
you don't throw exception from the destructor what-so-ever!
See : <http://www.stroustrup.com/bs_faq2.html#ctor-exceptions>
Bjarne quote (can you throw exception from a d.tor):
>
> Not really: You can throw an exception in a destructor, but that exception must not leave the destructor; if a destructor exits by a throw, all kinds of bad things are likely to happen because the basic rules of the standard library and the language itself will be violated. Don't do it.
>
>
>
You might not want to allocate any DB object on the stack anyway, a safe, reusable way is to use Connection Pool :
<https://en.wikipedia.org/wiki/Object_pool_pattern>
like this, the destruction of each conenction object iswhen the program exist, where you can handle the closing as integral part of the pool, and not in a spread way in some random functions
|
You probably should have a class for holding *one* database connection, and another class holding two instances of the first. Since I figure the *creation* of a database could fail as well, having each connection in its own class (with its own destructor) will handle partial construction / destruction quite nicely.
Besides, if a destructor throws, there is very little you can do (aside from logging the condition). [Your application](http://bin-login.name/ftp/pub/docs/programming_languages/cpp/cffective_cpp/MEC/MI11_FR.HTM) [is doomed](http://bin-login.name/ftp/pub/docs/programming_languages/cpp/cffective_cpp/MAGAZINE/SU_FRAME.HTM#destruct).
|
31,454,518 |
I have a two Database class objects allocated on Stack. I inherit this database class in my personal defined class. Now Database class has a function named "Close()" which throws an exception if closing that instance of database fails. Now for client perspective i don't want Client to call close() everytime to close the connection, rather i want to declare a vitrual Desctuctor in Database class which will automatically close the connection when object goes out of scope.
Now problem i am facing is, if i create two DB objects, and now try to delete both and if close succedds for both it's fine, but if close fails for first object it throws an exception, and now second is still allocated (if dynamically allocated member objects), which results in memory leak. How to handle this situation.
|
2015/07/16
|
[
"https://Stackoverflow.com/questions/31454518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312772/"
] |
you don't throw exception from the destructor what-so-ever!
See : <http://www.stroustrup.com/bs_faq2.html#ctor-exceptions>
Bjarne quote (can you throw exception from a d.tor):
>
> Not really: You can throw an exception in a destructor, but that exception must not leave the destructor; if a destructor exits by a throw, all kinds of bad things are likely to happen because the basic rules of the standard library and the language itself will be violated. Don't do it.
>
>
>
You might not want to allocate any DB object on the stack anyway, a safe, reusable way is to use Connection Pool :
<https://en.wikipedia.org/wiki/Object_pool_pattern>
like this, the destruction of each conenction object iswhen the program exist, where you can handle the closing as integral part of the pool, and not in a spread way in some random functions
|
Exceptions should never be thrown in destructor call.
You **should not** call anything that can cause them there, otherwise, you're crashing your class safety.
You should add a function that checks if database object can be "closed", not an exception. If you imagine that you just **can't** call function in destructor that may throw exception, you will find solution.
My choice is to do not use destructors to destroy associated objects, if there is a chance that this must not be allowed.
Destructors are intended to free only **internal** object resources only. You can create a something like `resource manager` that will store pointers to all objects you need to control. These may be `shared pointers`. And let this class make your behavior and not objects theirself.
|
31,454,518 |
I have a two Database class objects allocated on Stack. I inherit this database class in my personal defined class. Now Database class has a function named "Close()" which throws an exception if closing that instance of database fails. Now for client perspective i don't want Client to call close() everytime to close the connection, rather i want to declare a vitrual Desctuctor in Database class which will automatically close the connection when object goes out of scope.
Now problem i am facing is, if i create two DB objects, and now try to delete both and if close succedds for both it's fine, but if close fails for first object it throws an exception, and now second is still allocated (if dynamically allocated member objects), which results in memory leak. How to handle this situation.
|
2015/07/16
|
[
"https://Stackoverflow.com/questions/31454518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312772/"
] |
you don't throw exception from the destructor what-so-ever!
See : <http://www.stroustrup.com/bs_faq2.html#ctor-exceptions>
Bjarne quote (can you throw exception from a d.tor):
>
> Not really: You can throw an exception in a destructor, but that exception must not leave the destructor; if a destructor exits by a throw, all kinds of bad things are likely to happen because the basic rules of the standard library and the language itself will be violated. Don't do it.
>
>
>
You might not want to allocate any DB object on the stack anyway, a safe, reusable way is to use Connection Pool :
<https://en.wikipedia.org/wiki/Object_pool_pattern>
like this, the destruction of each conenction object iswhen the program exist, where you can handle the closing as integral part of the pool, and not in a spread way in some random functions
|
Do not throw exceptions from destructors, bad things happens, use a `shutdown()` method and call it ouside of destructor. Most C++ stuff is cleaned in destructors, if you throw from within a destructor you literally stop cleaning up things and you would end up having a C++ program in undefined state:
```
class Database{
std::vector<int> v;
connection c;
public:
~Database(){
c.close(); //ouch throws v don't get deallocated. (neither c)
}
};
```
may be changed to:
```
class Database{
std::vector<int> v;
connection c;
public:
~Database(){
// v deallocated here
}
void shutdown(){
c.close();
}
};
```
main.cpp
```
int main(){
Database d;
d.shutdown(); //even if d throws, d destructor will be called.
//and as consequence of d destructor also c & v
//destructors are called.
return 0;
}
```
since you have 2 databases
```
int main(){
Database d1,d2;
try{
d1.shutdown();
}catch( /** correct exception type*/){
//error handling for 1
}
try{
d2.shutdown();
}catch( /** correct exception type*/){
//error handling for 2
}
//both destructors called
return 0;
}
```
|
31,454,518 |
I have a two Database class objects allocated on Stack. I inherit this database class in my personal defined class. Now Database class has a function named "Close()" which throws an exception if closing that instance of database fails. Now for client perspective i don't want Client to call close() everytime to close the connection, rather i want to declare a vitrual Desctuctor in Database class which will automatically close the connection when object goes out of scope.
Now problem i am facing is, if i create two DB objects, and now try to delete both and if close succedds for both it's fine, but if close fails for first object it throws an exception, and now second is still allocated (if dynamically allocated member objects), which results in memory leak. How to handle this situation.
|
2015/07/16
|
[
"https://Stackoverflow.com/questions/31454518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312772/"
] |
You probably should have a class for holding *one* database connection, and another class holding two instances of the first. Since I figure the *creation* of a database could fail as well, having each connection in its own class (with its own destructor) will handle partial construction / destruction quite nicely.
Besides, if a destructor throws, there is very little you can do (aside from logging the condition). [Your application](http://bin-login.name/ftp/pub/docs/programming_languages/cpp/cffective_cpp/MEC/MI11_FR.HTM) [is doomed](http://bin-login.name/ftp/pub/docs/programming_languages/cpp/cffective_cpp/MAGAZINE/SU_FRAME.HTM#destruct).
|
Chances are that if `close` fails, there is not good recovery path anyway, you are best off logging the error and then carrying on as if it succeeded. So I would suggest you call `close` in a `try` block in you destructor and just logging the error in the corresponding `catch` block. The destructor can then complete normally.
As @David mentions above, destuctors should never leak exceptions, this is because destructors are called when an exception happens and an exception in an exception causes a crash.
|
31,454,518 |
I have a two Database class objects allocated on Stack. I inherit this database class in my personal defined class. Now Database class has a function named "Close()" which throws an exception if closing that instance of database fails. Now for client perspective i don't want Client to call close() everytime to close the connection, rather i want to declare a vitrual Desctuctor in Database class which will automatically close the connection when object goes out of scope.
Now problem i am facing is, if i create two DB objects, and now try to delete both and if close succedds for both it's fine, but if close fails for first object it throws an exception, and now second is still allocated (if dynamically allocated member objects), which results in memory leak. How to handle this situation.
|
2015/07/16
|
[
"https://Stackoverflow.com/questions/31454518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312772/"
] |
Do not throw exceptions from destructors, bad things happens, use a `shutdown()` method and call it ouside of destructor. Most C++ stuff is cleaned in destructors, if you throw from within a destructor you literally stop cleaning up things and you would end up having a C++ program in undefined state:
```
class Database{
std::vector<int> v;
connection c;
public:
~Database(){
c.close(); //ouch throws v don't get deallocated. (neither c)
}
};
```
may be changed to:
```
class Database{
std::vector<int> v;
connection c;
public:
~Database(){
// v deallocated here
}
void shutdown(){
c.close();
}
};
```
main.cpp
```
int main(){
Database d;
d.shutdown(); //even if d throws, d destructor will be called.
//and as consequence of d destructor also c & v
//destructors are called.
return 0;
}
```
since you have 2 databases
```
int main(){
Database d1,d2;
try{
d1.shutdown();
}catch( /** correct exception type*/){
//error handling for 1
}
try{
d2.shutdown();
}catch( /** correct exception type*/){
//error handling for 2
}
//both destructors called
return 0;
}
```
|
Chances are that if `close` fails, there is not good recovery path anyway, you are best off logging the error and then carrying on as if it succeeded. So I would suggest you call `close` in a `try` block in you destructor and just logging the error in the corresponding `catch` block. The destructor can then complete normally.
As @David mentions above, destuctors should never leak exceptions, this is because destructors are called when an exception happens and an exception in an exception causes a crash.
|
31,454,518 |
I have a two Database class objects allocated on Stack. I inherit this database class in my personal defined class. Now Database class has a function named "Close()" which throws an exception if closing that instance of database fails. Now for client perspective i don't want Client to call close() everytime to close the connection, rather i want to declare a vitrual Desctuctor in Database class which will automatically close the connection when object goes out of scope.
Now problem i am facing is, if i create two DB objects, and now try to delete both and if close succedds for both it's fine, but if close fails for first object it throws an exception, and now second is still allocated (if dynamically allocated member objects), which results in memory leak. How to handle this situation.
|
2015/07/16
|
[
"https://Stackoverflow.com/questions/31454518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312772/"
] |
You probably should have a class for holding *one* database connection, and another class holding two instances of the first. Since I figure the *creation* of a database could fail as well, having each connection in its own class (with its own destructor) will handle partial construction / destruction quite nicely.
Besides, if a destructor throws, there is very little you can do (aside from logging the condition). [Your application](http://bin-login.name/ftp/pub/docs/programming_languages/cpp/cffective_cpp/MEC/MI11_FR.HTM) [is doomed](http://bin-login.name/ftp/pub/docs/programming_languages/cpp/cffective_cpp/MAGAZINE/SU_FRAME.HTM#destruct).
|
Exceptions should never be thrown in destructor call.
You **should not** call anything that can cause them there, otherwise, you're crashing your class safety.
You should add a function that checks if database object can be "closed", not an exception. If you imagine that you just **can't** call function in destructor that may throw exception, you will find solution.
My choice is to do not use destructors to destroy associated objects, if there is a chance that this must not be allowed.
Destructors are intended to free only **internal** object resources only. You can create a something like `resource manager` that will store pointers to all objects you need to control. These may be `shared pointers`. And let this class make your behavior and not objects theirself.
|
31,454,518 |
I have a two Database class objects allocated on Stack. I inherit this database class in my personal defined class. Now Database class has a function named "Close()" which throws an exception if closing that instance of database fails. Now for client perspective i don't want Client to call close() everytime to close the connection, rather i want to declare a vitrual Desctuctor in Database class which will automatically close the connection when object goes out of scope.
Now problem i am facing is, if i create two DB objects, and now try to delete both and if close succedds for both it's fine, but if close fails for first object it throws an exception, and now second is still allocated (if dynamically allocated member objects), which results in memory leak. How to handle this situation.
|
2015/07/16
|
[
"https://Stackoverflow.com/questions/31454518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312772/"
] |
Do not throw exceptions from destructors, bad things happens, use a `shutdown()` method and call it ouside of destructor. Most C++ stuff is cleaned in destructors, if you throw from within a destructor you literally stop cleaning up things and you would end up having a C++ program in undefined state:
```
class Database{
std::vector<int> v;
connection c;
public:
~Database(){
c.close(); //ouch throws v don't get deallocated. (neither c)
}
};
```
may be changed to:
```
class Database{
std::vector<int> v;
connection c;
public:
~Database(){
// v deallocated here
}
void shutdown(){
c.close();
}
};
```
main.cpp
```
int main(){
Database d;
d.shutdown(); //even if d throws, d destructor will be called.
//and as consequence of d destructor also c & v
//destructors are called.
return 0;
}
```
since you have 2 databases
```
int main(){
Database d1,d2;
try{
d1.shutdown();
}catch( /** correct exception type*/){
//error handling for 1
}
try{
d2.shutdown();
}catch( /** correct exception type*/){
//error handling for 2
}
//both destructors called
return 0;
}
```
|
Exceptions should never be thrown in destructor call.
You **should not** call anything that can cause them there, otherwise, you're crashing your class safety.
You should add a function that checks if database object can be "closed", not an exception. If you imagine that you just **can't** call function in destructor that may throw exception, you will find solution.
My choice is to do not use destructors to destroy associated objects, if there is a chance that this must not be allowed.
Destructors are intended to free only **internal** object resources only. You can create a something like `resource manager` that will store pointers to all objects you need to control. These may be `shared pointers`. And let this class make your behavior and not objects theirself.
|
49,070,467 |
is it possible to create custom effects for JavaFX, based on a Pixle Shader? I found [this](http://lqd.hybird.org/journal/?p=196) article but what is Decora? I cannot find anything about it.
THX
|
2018/03/02
|
[
"https://Stackoverflow.com/questions/49070467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1770962/"
] |
Currently no - in the abstract base class Effect.java, there are abstract package-private methods like, copy(), sync(), update() etc.
The Decora project is discussed here: <http://labonnesoupe.org/static/code/> . I asked about opening JSL, to make some kind of public API in the developer OpenJFX thread perhaps 6 months ago, and was told, "no, there are no plans to open this api to the public".
As you may be aware, OpenJFX are considering new committers, which works, I believe on the premise that you sign an Oracle contributor agreement, and are voted in by lazy consensus. Perhaps this will shunt this much needed area into life.
In my own 2D game, I use Guassian Blurs, and Blooms, to highlight spell strikes, and I believe Decora was used in developing these Effects. However, they are pitifully slow. Taking my FPS from around 250 down to around 30 on a 10 series NVidia card. I would love to see improvements here.
I emailed Chris Campbell (author of Labonnesoupe) asking about his work on JavaFX shaders, but he emailed me back to say it was over 8 years ago, and he's not up on the latest. A search of web reveals that all reference to Decora is now ancient.
|
Use libgdx. Its free and Works on Web HTML 5 webgl ,ios,android,all desktop and with full shader support
|
49,070,467 |
is it possible to create custom effects for JavaFX, based on a Pixle Shader? I found [this](http://lqd.hybird.org/journal/?p=196) article but what is Decora? I cannot find anything about it.
THX
|
2018/03/02
|
[
"https://Stackoverflow.com/questions/49070467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1770962/"
] |
Currently no - in the abstract base class Effect.java, there are abstract package-private methods like, copy(), sync(), update() etc.
The Decora project is discussed here: <http://labonnesoupe.org/static/code/> . I asked about opening JSL, to make some kind of public API in the developer OpenJFX thread perhaps 6 months ago, and was told, "no, there are no plans to open this api to the public".
As you may be aware, OpenJFX are considering new committers, which works, I believe on the premise that you sign an Oracle contributor agreement, and are voted in by lazy consensus. Perhaps this will shunt this much needed area into life.
In my own 2D game, I use Guassian Blurs, and Blooms, to highlight spell strikes, and I believe Decora was used in developing these Effects. However, they are pitifully slow. Taking my FPS from around 250 down to around 30 on a 10 series NVidia card. I would love to see improvements here.
I emailed Chris Campbell (author of Labonnesoupe) asking about his work on JavaFX shaders, but he emailed me back to say it was over 8 years ago, and he's not up on the latest. A search of web reveals that all reference to Decora is now ancient.
|
Theoretically it IS POSSIBLE to create you custom effect in JavaFx however using way u probably won't like... Abstract class `javafx.scene.effect.Effect` has internal methods inside, that is right! But based on the fact that internal means "package private" we can do the following! In your project create a new package called "javafx.scene.effect" the same as Effect class is in, and inside this newly created package just create your custom effect class that extends `javafx.scene.effect.Effect` and that's it you have your custom JavaFx effect!!!
Custom Effect class example:
```
package javafx.scene.effect;
import com.sun.javafx.geom.BaseBounds;
import com.sun.javafx.geom.Rectangle;
import com.sun.javafx.geom.transform.BaseTransform;
import com.sun.javafx.scene.BoundsAccessor;
import com.sun.scenario.effect.FilterContext;
import com.sun.scenario.effect.ImageData;
import javafx.scene.Node;
public class MyEffect extends javafx.scene.effect.Effect
{
public MyEffect()
{
}
@Override
com.sun.scenario.effect.Effect impl_createImpl()
{
return new com.sun.scenario.effect.Effect()
{
@Override
public boolean reducesOpaquePixels()
{
// TODO Auto-generated method stub
return false;
}
@Override
public BaseBounds getBounds(BaseTransform transform, com.sun.scenario.effect.Effect defaultInput)
{
// TODO Auto-generated method stub
return null;
}
@Override
public AccelType getAccelType(FilterContext fctx)
{
// TODO Auto-generated method stub
return null;
}
@Override
public ImageData filter(FilterContext fctx, BaseTransform transform, Rectangle outputClip, Object renderHelper, com.sun.scenario.effect.Effect defaultInput)
{
// TODO Auto-generated method stub
return null;
}
};
}
@Override
void impl_update()
{
// TODO Auto-generated method stub
}
@Override
public BaseBounds impl_getBounds(BaseBounds bounds, BaseTransform tx, Node node, BoundsAccessor boundsAccessor)
{
// TODO Auto-generated method stub
return null;
}
@Override
boolean impl_checkChainContains(javafx.scene.effect.Effect e)
{
// TODO Auto-generated method stub
return false;
}
@Override
public javafx.scene.effect.Effect impl_copy()
{
// TODO Auto-generated method stub
return null;
}
}
```
However I have literally no idea what those inhered methods in from javafx.scene.effect.Effect supposed to do so you need to figure it out :)
Also, keep in mind that internal/private things are private for some reason (even though I also do not see that reason in this case)!
Aditional:
What I currently know is that JavaFx Effects are only some sort of "masks" or "providers" for Effects from `com.sun.scenario.effect` and there are many com.sun.scenario.effect children classes that have no direct JavaFx version/implementation so you should be theoretically able to add these ones into JavaFx by your self using my solution! But again there is a question if this is a good idea because I think `com.sun.scenario.effect` is something that regular JavaFx programer supposed to not even know about. But I will let you to decide!
|
49,070,467 |
is it possible to create custom effects for JavaFX, based on a Pixle Shader? I found [this](http://lqd.hybird.org/journal/?p=196) article but what is Decora? I cannot find anything about it.
THX
|
2018/03/02
|
[
"https://Stackoverflow.com/questions/49070467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1770962/"
] |
Theoretically it IS POSSIBLE to create you custom effect in JavaFx however using way u probably won't like... Abstract class `javafx.scene.effect.Effect` has internal methods inside, that is right! But based on the fact that internal means "package private" we can do the following! In your project create a new package called "javafx.scene.effect" the same as Effect class is in, and inside this newly created package just create your custom effect class that extends `javafx.scene.effect.Effect` and that's it you have your custom JavaFx effect!!!
Custom Effect class example:
```
package javafx.scene.effect;
import com.sun.javafx.geom.BaseBounds;
import com.sun.javafx.geom.Rectangle;
import com.sun.javafx.geom.transform.BaseTransform;
import com.sun.javafx.scene.BoundsAccessor;
import com.sun.scenario.effect.FilterContext;
import com.sun.scenario.effect.ImageData;
import javafx.scene.Node;
public class MyEffect extends javafx.scene.effect.Effect
{
public MyEffect()
{
}
@Override
com.sun.scenario.effect.Effect impl_createImpl()
{
return new com.sun.scenario.effect.Effect()
{
@Override
public boolean reducesOpaquePixels()
{
// TODO Auto-generated method stub
return false;
}
@Override
public BaseBounds getBounds(BaseTransform transform, com.sun.scenario.effect.Effect defaultInput)
{
// TODO Auto-generated method stub
return null;
}
@Override
public AccelType getAccelType(FilterContext fctx)
{
// TODO Auto-generated method stub
return null;
}
@Override
public ImageData filter(FilterContext fctx, BaseTransform transform, Rectangle outputClip, Object renderHelper, com.sun.scenario.effect.Effect defaultInput)
{
// TODO Auto-generated method stub
return null;
}
};
}
@Override
void impl_update()
{
// TODO Auto-generated method stub
}
@Override
public BaseBounds impl_getBounds(BaseBounds bounds, BaseTransform tx, Node node, BoundsAccessor boundsAccessor)
{
// TODO Auto-generated method stub
return null;
}
@Override
boolean impl_checkChainContains(javafx.scene.effect.Effect e)
{
// TODO Auto-generated method stub
return false;
}
@Override
public javafx.scene.effect.Effect impl_copy()
{
// TODO Auto-generated method stub
return null;
}
}
```
However I have literally no idea what those inhered methods in from javafx.scene.effect.Effect supposed to do so you need to figure it out :)
Also, keep in mind that internal/private things are private for some reason (even though I also do not see that reason in this case)!
Aditional:
What I currently know is that JavaFx Effects are only some sort of "masks" or "providers" for Effects from `com.sun.scenario.effect` and there are many com.sun.scenario.effect children classes that have no direct JavaFx version/implementation so you should be theoretically able to add these ones into JavaFx by your self using my solution! But again there is a question if this is a good idea because I think `com.sun.scenario.effect` is something that regular JavaFx programer supposed to not even know about. But I will let you to decide!
|
Use libgdx. Its free and Works on Web HTML 5 webgl ,ios,android,all desktop and with full shader support
|
63,104,066 |
here is my models.py file
```
class Customer(models.Model):
"""All Customers details goes here"""
name = models.CharField(max_length=255, null=False)
firm_name = models.CharField(max_length=255, null=False)
email = models.EmailField(null=False)
phone_number = models.CharField(max_length=255, null=False)
location = models.CharField(max_length=255,null=True)
date_created = models.DateTimeField(auto_now_add=True)
class Meta:
"""Meta definition for Customer."""
verbose_name = 'Customer'
verbose_name_plural = 'Customers'
def __str__(self):
"""Unicode representation of Customer."""
return self.name
class Order(models.Model):
"""All order details goes here.It has OneToMany relationship with Customer"""
STATUS = (
('CR', 'CR'),
('DR', 'DR'),
)
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
bill_name = models.CharField(max_length=255, null=False)
payment_date=models.DateField(auto_now=False)
status = models.CharField(max_length=255, choices=STATUS, null=False)
amount = models.FloatField(max_length=255, null=False)
date_created = models.DateTimeField(auto_now_add=True)
description = models.TextField(null=True)
class Meta:
"""Meta definition for Order."""
verbose_name = 'Order'
verbose_name_plural = 'Orders'
def __str__(self):
"""Unicode representation of Order."""
return self.bill_name
```
i want to access only Customer's name and all fields of Order,in short i want to convert the following SQL in Django Query-set
>
> select name ,bill\_name ,status from accounts\_customer left join
> accounts\_order on accounts\_customer.id = accounts\_order.customer\_id
> where accounts\_order.status="DR";
>
>
>
|
2020/07/26
|
[
"https://Stackoverflow.com/questions/63104066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13533308/"
] |
You may use
```
[Validators.required, Validators.pattern("-?\\d+(?:\\.\\d+)?")]
```
Or,
```
[Validators.required, Validators.pattern(/^-?\d+(?:\.\d+)?$/)]
```
**NOTES**:
* If you define the regex with a string literal, `"..."`, remember that `^` and `$` are appended by angular automatically, you do not need to specify them explicitly AND you need to double escape backslashes to define regex escape sequences, like `\d`, `\w`, `\b`, `\W`, etc.
* If you define the regex using a regex literal notation, `/.../`, you need to add `^` and `$` to ensure a full string match, and you need to use single backslashes to define regex escapes.
The `^-?\d+(?:\.\d+)?$` regex is rather basic, you may find more at [Regular expression for floating point numbers](https://stackoverflow.com/questions/12643009) and [Javascript: Regular expression to allow negative and positive floating point numbers?](https://stackoverflow.com/questions/8025060).
|
check [this](https://www.regextester.com/) works for Integers or decimal numbers with or without the exponential form
```html
^[+-]?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$
```
for more regex try this [website](https://regexlib.com/)
|
19,702,779 |
I want to use gzip for my mobile version of site. I tried to do it adding following line at the top of my php file
```
ob_start("ob_gzhandler");
```
But it gives me following error. 
I've been searching and trying number of ways but nothing could compress the page. How to achieve this?
|
2013/10/31
|
[
"https://Stackoverflow.com/questions/19702779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1784822/"
] |
May be you are using Apache's gzip compression that compress js/css files, again use of ob\_start('ob\_gzhandler') will compress that compression and browser will not handle that.
[check here](https://stackoverflow.com/questions/5441784/why-does-ob-startob-gzhandler-break-this-website) may be it will help you.
|
simply use double quotes as `"ob_start('ob_gzhandler')";` to avoid content encoding error
|
19,702,779 |
I want to use gzip for my mobile version of site. I tried to do it adding following line at the top of my php file
```
ob_start("ob_gzhandler");
```
But it gives me following error. 
I've been searching and trying number of ways but nothing could compress the page. How to achieve this?
|
2013/10/31
|
[
"https://Stackoverflow.com/questions/19702779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1784822/"
] |
Maybe you had the same problem as me and actually have **an utf-8 file WITH an UTF-8 BOM inside** \*.
I think gzip in combination with UTF-8 BOM gives an encoding problem.
***Notes:***
* Not all editors are able to show if the BOM is there or not. I had to actually use another editor, Notepad++, to realize there was a BOM there and remove it there via "Convert to utf-8 without BOM" and then saving the file. (Also closing it in my original editor first.)
But could as well be that you can set your editor not the include the BOM.
* Possibly this only occurs when php error reporting is on
\* *More about UTF BOM:*
* stackoverflow: [What's different between utf-8 and utf-8 without BOM?](https://stackoverflow.com/questions/2223882/whats-different-between-utf-8-and-utf-8-without-bom)
* Wikipedia: [Byte order mark](https://en.wikipedia.org/wiki/Byte_order_mark)
|
May be you are using Apache's gzip compression that compress js/css files, again use of ob\_start('ob\_gzhandler') will compress that compression and browser will not handle that.
[check here](https://stackoverflow.com/questions/5441784/why-does-ob-startob-gzhandler-break-this-website) may be it will help you.
|
19,702,779 |
I want to use gzip for my mobile version of site. I tried to do it adding following line at the top of my php file
```
ob_start("ob_gzhandler");
```
But it gives me following error. 
I've been searching and trying number of ways but nothing could compress the page. How to achieve this?
|
2013/10/31
|
[
"https://Stackoverflow.com/questions/19702779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1784822/"
] |
Maybe you had the same problem as me and actually have **an utf-8 file WITH an UTF-8 BOM inside** \*.
I think gzip in combination with UTF-8 BOM gives an encoding problem.
***Notes:***
* Not all editors are able to show if the BOM is there or not. I had to actually use another editor, Notepad++, to realize there was a BOM there and remove it there via "Convert to utf-8 without BOM" and then saving the file. (Also closing it in my original editor first.)
But could as well be that you can set your editor not the include the BOM.
* Possibly this only occurs when php error reporting is on
\* *More about UTF BOM:*
* stackoverflow: [What's different between utf-8 and utf-8 without BOM?](https://stackoverflow.com/questions/2223882/whats-different-between-utf-8-and-utf-8-without-bom)
* Wikipedia: [Byte order mark](https://en.wikipedia.org/wiki/Byte_order_mark)
|
simply use double quotes as `"ob_start('ob_gzhandler')";` to avoid content encoding error
|
488,485 |
I have two users, user1 and user2, that are both members of groupA. user2 has a folder in their home directory called folderA. If they wish to allow read-write-execute permissions for all members of groupA, how would they do this?
What if folderA contains many files and additional folders that also need to have read-write-execute permission?
Information regarding groups is a little 'spotty' across the web, so I am putting my question here in the hope someone posts a clear answer that might help others out too.
Thanks!
|
2014/06/26
|
[
"https://askubuntu.com/questions/488485",
"https://askubuntu.com",
"https://askubuntu.com/users/179016/"
] |
**FolderA** will first need to be part of **groupA** - the folder's owner or root can perform this operation
```
chgrp groupA ./folderA
```
Then **groupA** will need rwx permissions of the folder
```
chmod g+rwx ./folderA
```
There are options in the `chgrp` and `chmod` commands to recurse into the directory if required.
|
My own experience in this area here. Tested on Ubuntu 18.04.
### Allow to write in the system folder
Give write permission to `/etc/nginx/` folder.
```sh
# Check 'webmasters' group doen't exist
cat /etc/group | grep webmasters
# Create 'webmasters' group
sudo addgroup webmasters
# Add users to 'webmasters' group
sudo usermod -a -G webmasters username
sudo usermod -a -G webmasters vozman
sudo usermod -a -G webmasters romanroskach
# Group assignment changes won't take effect
# until the users log out and back in.
# Create directory
sudo mkdir /etc/nginx/
# Check directory permissions
ls -al /etc | grep nginx
drwxr-xr-x 2 root root 4096 Dec 5 18:30 nginx
# Change group owner of the directory
sudo chgrp -R webmasters /etc/nginx/
# Check that the group owner is changed
ls -al /etc | grep nginx
drwxr-xr-x 2 root webmasters 4096 Dec 5 18:30 nginx
# Give write permission to the group
sudo chmod -R g+w /etc/nginx/
# Check
ls -al /etc | grep nginx
drwxrwxr-x 2 root webmasters 4096 Dec 5 18:30 nginx
# Try to create file
sudo -u username touch /etc/nginx/test.txt # should work
sudo -u username touch /etc/test.txt # Permission denied
```
Give write permission to `/etc/systemd/system/` folder.
```sh
# List ACLs
getfacl /etc/systemd/system
getfacl: Removing leading '/' from absolute path names
# file: etc/systemd/system
# owner: root
# group: root
user::rwx
group::r-x
other::r-x
# Add 'webmasters' group to an ACL
sudo setfacl -m g:webmasters:rwx /etc/systemd/system
# Check
getfacl /etc/systemd/system
getfacl: Removing leading '/' from absolute path names
# file: etc/systemd/system
# owner: root
# group: root
user::rwx
group::r-x
group:webmasters:rwx
mask::rwx
other::r-x
sudo -u username touch /etc/systemd/system/test.txt # should work
sudo -u username touch /etc/systemd/test.txt # Permission denied
```
[Original how-to](https://github.com/foobar167/articles/blob/master/Ubuntu/07_Website_software.md/#allow-write).
|
635,632 |
I am trying to get the revision number of a project and save it into a variable. I know I can get the revision number by svnversion command but I'm not sure how I can store it. I am using regular windows command prompt. Basically I'm trying to do something like :
set svnVersion= %svnversion% but I'm not sure how??
|
2009/03/11
|
[
"https://Stackoverflow.com/questions/635632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62958/"
] |
In bash (via Cygwin):
```
svn info | grep -i "Revision" | cut -d ' ' -f 2
```
You can then use that in a bash shell script to store the value in a variable.
|
The "svn info" subcommand will tell you the revision number in your working copy.
|
635,632 |
I am trying to get the revision number of a project and save it into a variable. I know I can get the revision number by svnversion command but I'm not sure how I can store it. I am using regular windows command prompt. Basically I'm trying to do something like :
set svnVersion= %svnversion% but I'm not sure how??
|
2009/03/11
|
[
"https://Stackoverflow.com/questions/635632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62958/"
] |
In bash (via Cygwin):
```
svn info | grep -i "Revision" | cut -d ' ' -f 2
```
You can then use that in a bash shell script to store the value in a variable.
|
Something like:
```
svn version > ver.txt
set /p ver= < ver.txt
del ver.txt
echo %ver%
```
|
635,632 |
I am trying to get the revision number of a project and save it into a variable. I know I can get the revision number by svnversion command but I'm not sure how I can store it. I am using regular windows command prompt. Basically I'm trying to do something like :
set svnVersion= %svnversion% but I'm not sure how??
|
2009/03/11
|
[
"https://Stackoverflow.com/questions/635632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62958/"
] |
To set the output of variable to the output of svnversion in a batch file, you have to do this:
```
for /f "delims=" %%a in ('svnversion') do @set myvar=%%a
echo %myvar%
```
---
Different approach: If you have TortoiseSVN you can also use **SubWCRev.exe**. See
[get the project revision number into my project?](http://tortoisesvn.net/node/18) or [Automatic SVN Revision Numbering in ASP.Net MVC](http://www.fatlemon.co.uk/2008/12/automatic-svn-revision-numbering-in-aspnet-mvc/)
|
Here is an alternative that uses a pipe to findstr to get a single line:
```
FOR /F "tokens=2" %%G IN ('svn info ^| findstr /B Revision:') DO SET SVN_REVISION=%%G
echo SVN_REVISION: %SVN_REVISION%
FOR /F "tokens=2" %%G IN ('svn info ^| findstr /B URL:') DO SET SVN_URL=%%G
echo SVN_URL: %SVN_URL%
```
|
635,632 |
I am trying to get the revision number of a project and save it into a variable. I know I can get the revision number by svnversion command but I'm not sure how I can store it. I am using regular windows command prompt. Basically I'm trying to do something like :
set svnVersion= %svnversion% but I'm not sure how??
|
2009/03/11
|
[
"https://Stackoverflow.com/questions/635632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62958/"
] |
If you need this from a remote repository (as in not checked out localy) you can do this
```
for /f "delims=: tokens=1,2" %%a in ('svn info %SVN_REPO_URL%') do (
if "%%a"=="Revision" (
set /a RELEASE_REVISION=%%b
)
)
```
I use this in my release process to grab the revision number from a tag.
|
See if this help: [Change Revision Number](https://stackoverflow.com/questions/562087/change-revision-number-in-subversion-even-if-the-file-not-change-in-the-commit)
|
635,632 |
I am trying to get the revision number of a project and save it into a variable. I know I can get the revision number by svnversion command but I'm not sure how I can store it. I am using regular windows command prompt. Basically I'm trying to do something like :
set svnVersion= %svnversion% but I'm not sure how??
|
2009/03/11
|
[
"https://Stackoverflow.com/questions/635632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62958/"
] |
To set the output of variable to the output of svnversion in a batch file, you have to do this:
```
for /f "delims=" %%a in ('svnversion') do @set myvar=%%a
echo %myvar%
```
---
Different approach: If you have TortoiseSVN you can also use **SubWCRev.exe**. See
[get the project revision number into my project?](http://tortoisesvn.net/node/18) or [Automatic SVN Revision Numbering in ASP.Net MVC](http://www.fatlemon.co.uk/2008/12/automatic-svn-revision-numbering-in-aspnet-mvc/)
|
In bash (via Cygwin):
```
svn info | grep -i "Revision" | cut -d ' ' -f 2
```
You can then use that in a bash shell script to store the value in a variable.
|
635,632 |
I am trying to get the revision number of a project and save it into a variable. I know I can get the revision number by svnversion command but I'm not sure how I can store it. I am using regular windows command prompt. Basically I'm trying to do something like :
set svnVersion= %svnversion% but I'm not sure how??
|
2009/03/11
|
[
"https://Stackoverflow.com/questions/635632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62958/"
] |
To set the output of variable to the output of svnversion in a batch file, you have to do this:
```
for /f "delims=" %%a in ('svnversion') do @set myvar=%%a
echo %myvar%
```
---
Different approach: If you have TortoiseSVN you can also use **SubWCRev.exe**. See
[get the project revision number into my project?](http://tortoisesvn.net/node/18) or [Automatic SVN Revision Numbering in ASP.Net MVC](http://www.fatlemon.co.uk/2008/12/automatic-svn-revision-numbering-in-aspnet-mvc/)
|
The "svn info" subcommand will tell you the revision number in your working copy.
|
635,632 |
I am trying to get the revision number of a project and save it into a variable. I know I can get the revision number by svnversion command but I'm not sure how I can store it. I am using regular windows command prompt. Basically I'm trying to do something like :
set svnVersion= %svnversion% but I'm not sure how??
|
2009/03/11
|
[
"https://Stackoverflow.com/questions/635632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62958/"
] |
To set the output of variable to the output of svnversion in a batch file, you have to do this:
```
for /f "delims=" %%a in ('svnversion') do @set myvar=%%a
echo %myvar%
```
---
Different approach: If you have TortoiseSVN you can also use **SubWCRev.exe**. See
[get the project revision number into my project?](http://tortoisesvn.net/node/18) or [Automatic SVN Revision Numbering in ASP.Net MVC](http://www.fatlemon.co.uk/2008/12/automatic-svn-revision-numbering-in-aspnet-mvc/)
|
If you need this from a remote repository (as in not checked out localy) you can do this
```
for /f "delims=: tokens=1,2" %%a in ('svn info %SVN_REPO_URL%') do (
if "%%a"=="Revision" (
set /a RELEASE_REVISION=%%b
)
)
```
I use this in my release process to grab the revision number from a tag.
|
635,632 |
I am trying to get the revision number of a project and save it into a variable. I know I can get the revision number by svnversion command but I'm not sure how I can store it. I am using regular windows command prompt. Basically I'm trying to do something like :
set svnVersion= %svnversion% but I'm not sure how??
|
2009/03/11
|
[
"https://Stackoverflow.com/questions/635632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62958/"
] |
If you need this from a remote repository (as in not checked out localy) you can do this
```
for /f "delims=: tokens=1,2" %%a in ('svn info %SVN_REPO_URL%') do (
if "%%a"=="Revision" (
set /a RELEASE_REVISION=%%b
)
)
```
I use this in my release process to grab the revision number from a tag.
|
Here is an alternative that uses a pipe to findstr to get a single line:
```
FOR /F "tokens=2" %%G IN ('svn info ^| findstr /B Revision:') DO SET SVN_REVISION=%%G
echo SVN_REVISION: %SVN_REVISION%
FOR /F "tokens=2" %%G IN ('svn info ^| findstr /B URL:') DO SET SVN_URL=%%G
echo SVN_URL: %SVN_URL%
```
|
635,632 |
I am trying to get the revision number of a project and save it into a variable. I know I can get the revision number by svnversion command but I'm not sure how I can store it. I am using regular windows command prompt. Basically I'm trying to do something like :
set svnVersion= %svnversion% but I'm not sure how??
|
2009/03/11
|
[
"https://Stackoverflow.com/questions/635632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62958/"
] |
The "svn info" subcommand will tell you the revision number in your working copy.
|
See if this help: [Change Revision Number](https://stackoverflow.com/questions/562087/change-revision-number-in-subversion-even-if-the-file-not-change-in-the-commit)
|
635,632 |
I am trying to get the revision number of a project and save it into a variable. I know I can get the revision number by svnversion command but I'm not sure how I can store it. I am using regular windows command prompt. Basically I'm trying to do something like :
set svnVersion= %svnversion% but I'm not sure how??
|
2009/03/11
|
[
"https://Stackoverflow.com/questions/635632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62958/"
] |
In bash (via Cygwin):
```
svn info | grep -i "Revision" | cut -d ' ' -f 2
```
You can then use that in a bash shell script to store the value in a variable.
|
Here is an alternative that uses a pipe to findstr to get a single line:
```
FOR /F "tokens=2" %%G IN ('svn info ^| findstr /B Revision:') DO SET SVN_REVISION=%%G
echo SVN_REVISION: %SVN_REVISION%
FOR /F "tokens=2" %%G IN ('svn info ^| findstr /B URL:') DO SET SVN_URL=%%G
echo SVN_URL: %SVN_URL%
```
|
138,606 |
I'm looking at Deligne-Rapoport p.175 Prop 1.5:
Suppose $p: C\rightarrow S$ is a proper, flat morphism of finite presentation and suppose that geometric fibers are reduced, pure of dimension 1, of arithmetic genus 1 and connected.
Question: Why is the locus of points $s \in S$ where a geometric fiber $C\_{\bar{s}}$ has at most ordinary double points as singularities also open in S?
|
2013/08/05
|
[
"https://mathoverflow.net/questions/138606",
"https://mathoverflow.net",
"https://mathoverflow.net/users/38209/"
] |
Start with the sheaf of relative differentials, $\Omega\_{C/S}$. Next consider the Fitting ideal $\mathcal{I}$ of $\Omega\_{C/S}$ (measuring the deviation from being locally free of rank $1$). Consider the closed subscheme $C\_{\text{sing},p}$ of $C$ associated to $\mathcal{I}$. By hypothesis, the projection morphism $p':C\_{\text{sing},p}\to S$ is finite. Denote by $C\_{\text{non-odp},p} \subset C\_{\text{sing},p}$ the closed subscheme on which $p'$ fails to be unramified, i.e., the closed support of the sheaf of relative differentials of $p$. This is a closed subscheme of $C$. Since $p:C\to S$ is proper, the image of $C\_{\text{non-odp},p}$ in $S$ is a closed subscheme of $S$. The open complement is the maximal open subscheme of $S$ over which $p$ has at worst ordinary double points as singularities.
**Edit.** The OP asks for further details.
The claim is that a point of $C\_{\text{sing},p}$ is an ordinary double point if and only if it is not in $C\_{\text{non-odp},p}$. This claim is compatible
with arbitrary base change on $S$. Thus assume that $S$ equals $\text{Spec}(k)$ for an algebraically closed field $k$, and let $x$ be a $k$-point of $C\_{\text{sing},p}$. The original claim is equivalent to the claim that the Fitting ideal in $\mathcal{O}\_{C,x}$ of the stalk $(\Omega\_{C/S})\_x$ equals the maximal ideal $\mathfrak{m}\_x$ if and only if $x$ is an ordinary double point of $C$. This claim is compatible with passage to the completion of $\mathcal{O}\_{C,x}$.
If $x$ is an ordinary double point of $C$, then the completion $\widehat{\mathcal{O}}\_{C,x}$ is isomorphic to $k[[s,t]]/\langle st \rangle$. In this case, it is a straightforward computation that the Fitting ideal is generated by $s$ and $t$, i.e., the Fitting ideal equals the maximal ideal. So one direction of the claim is verified. It remains to prove that the Fitting ideal is strictly contained in the maximal ideal in every case that $C$ does not have an ordinary double point at $x$.
Denote by $e$ the embedding dimension, $\text{dim}\_k(\mathfrak{m}\_x/\mathfrak{m}\_x^2)$.
Up to choosing elements in $\mathfrak{m}\_x$ that map to a basis of $(\mathfrak{m}\_x/\mathfrak{m}\_x^2)$, there is a surjection $$q:(\mathfrak{m}\_x/\mathfrak{m}\_x^2)\otimes\_k \mathcal{O}\_{C,x} \to (\Omega\_{C/S})\_x.$$
Since $\mathfrak{O}\_{C,x}$ is Noetherian, the kernel of $q$ is finitely generated. Let $$r:\mathcal{O}\_{C,x}^{\oplus d} \to (\mathfrak{m}\_x/\mathfrak{m}\_x^2)\otimes\_k \mathcal{O}\_{C,x}$$ be an $\mathcal{O}\_{C,x}$-module homomorphism whose image equals $\text{Ker}(q)$. Thus there is an exact sequence of $\mathcal{O}\_{C,x}$-modules, $$\mathcal{O}\_{C,x}^{\oplus d} \to (\mathfrak{m}\_x/\mathfrak{m}\_x^2)\otimes\_k \mathcal{O}\_{C,x} \to (\Omega\_{C/S})\_x \to 0.$$
Since tensoring with $\mathcal{O}\_{C,x}/\mathfrak{m}\_x$ is right exact, this gives rise to an exact sequence of $k$-vector spaces,
$$ k^{\oplus d} \to (\mathfrak{m}\_x/\mathfrak{m}\_x^2) \to \Omega\_{C/S}|\_x \to 0.$$
But, of course, the last map is an isomorphism. Thus the first map is the zero map. Thus it follows that $r$ lands in $\mathfrak{m}\_x$ times the target module. In particular, choosing free bases for the domain and target of $r$, every entry of the $d\times e$ matrix representative is in $\mathfrak{m}\_x$. The (stalk at $x$ of the) Fitting ideal of $\Omega\_{C/S}$ is generated by the $(e-1)\times(e-1)$-minors of this matrix representative. Each of these minors is an element in $\mathfrak{m}\_x^{e-1}$.
Thus, if $e\geq 3$, then the generators of the Fitting ideal are contained in $\mathfrak{m}\_x^2$. By Krull's Intersection Theorem (or many other arguments), elements in $\mathfrak{m}\_x^2$ cannot generate $\mathfrak{m}\_x$.
Therefore assume that $e$ equals $2$. Then, using the hypothesis that the geometric fibers of $p$ are reduced and purely $1$-dimensional, it follows that the completion $\widehat{\mathcal{O}}\_{C,x}$ is isomorphic to $k[[s,t]]/\langle f \rangle$, where $f\in \langle s,t \rangle^2$ is a nonzero element. Of course the Fitting ideal is generated by the images (modulo $f$) of $\partial f/\partial s$ and $\partial f/\partial t$. Thus, as above, if $f\in \langle s,t\rangle^3$, then the partial derivatives are in $\mathfrak{m}\_x^2$, so that the
Fitting ideal is strictly contained in $\mathfrak{m}\_x$.
A bit more precisely, if we write $f=as^2 + bst+ct^2 + g$, where $g\in \langle s,t \rangle^3$, then the image of the partials in $\mathfrak{m}\_x/\mathfrak{m}\_x^2$ is precisely given by the two partials of $as^2+bst+ct^2$. Via Nakayama's Lemma, the Fitting ideal equals $\mathfrak{m}\_x$ if and only if these two images give a $k$-spaning set for the $2$-dimensional $k$-vector space $\mathfrak{m}\_x/\mathfrak{m}\_x^2$. Via the Rank-Nullity Theorem, these images are $k$-spanning if and only if they are linearly independent.
Using the standard basis $\overline{s}$ and $\overline{t}$ for this $2$-dimensional vector space, the determinant associated to these two partial derivatives is precisely the discriminant $4ac-b^2$. Thus, the Fitting ideal equals $\mathfrak{m}\_x$ if and only if the discriminant $4ac-b^2$ is nonzero (as an element in $k$). This is precisely the condition that, up to a linear change of coordinates, $f=st + g$, i.e., $C$ has an ordinary double point at $x$.
In some form this argument should be available in references that study "ordinary double points", e.g., probably most references on Morse theory.
|
Perhaps I can point to a more explicit explanation at the end of my notes : <http://math.rutgers.edu/~hjn11/Notes/moduli%20space%20of%20curves.pdf> . Check out Proposition 5.1 there. It essentially deals with this same question, though coming from the point of view of construction the Hilbert scheme of stable curves. The notes are somewhat rough, but should give you an explicit idea. Very briefly, you can show that the locus of fibers which are l.c.i. schemes (locally complete intersection) is open, and then using the l.c.i. condition you can basically reduce down to the definition of a nodal point as a hypersurface singularity such that the determinant of the Hessian of the defining equation doesn't vanish. The complement of this is the vanishing of this determinant, a closed condition. Then continue as Jason mentioned since the image of this closed guy under the proper map will be closed and its complement is the open set you want.
|
24,255 |
Currently, the standard behaviour for viewing web pages on a mobile is that:
* If viewed in portrait the text is smaller because the width of the device is small and the whole page width needs to fit into view.
* If viewed in landscape the view 'zooms in' as the width is now wider so that the text is larger and more readable, but with less content on screen as a result.
So, this brings a dilemma. When creating a responsive website what should happen on device rotation? *(Not on initial page load, I am referring to what should happen once the site is loaded and you decide to then rotate the screen)*
When rotated from portrait to landscape should you:
* **a)** Re-detect the device widths and map the contents according to the new dimensions (thereby retaining the same font / images sizes as when viewing portrait).
* **b)** Keep the same dimensions and on rotation just bring the content to fit the window (thereby zooming in the content to make it more readable for viewers if the portrait orientation text is too small).

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fOAQVC.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
Bear in mind that with a traditional web-page viewed in the mobile you have the option of pinch-to-zoom the text, so if it's too small you can zoom in. With a responsive site this isn't an option because the site will fit the dimensions so there is nothing to zoom into.
(I guess there is a third option too - use responsive fonts so that the font sizes change according to the screen width. But that's probably a different question altogether).
|
2012/08/02
|
[
"https://ux.stackexchange.com/questions/24255",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3865/"
] |
Let me add a late answer: **after the content has loaded, do not let rotations trigger breakpoints**.
If the user rotates the device accidentally, their most immediate task is to reorient themselves and re-find the content they were viewing or reading at the time of rotation. But a breakpoint trigger, the user is suddenly presented with an interface they don't recognize (which makes them wonder if something has happened), and with additional content that breaks any anchors they'd use for re-finding their initial position. Worse, if the breakpoint *removes* material, there's a chance the content the user wants to re-find has been taken out completely. Discovering that this has happened is a *very* expensive operation.
But what if the user rotates the device deliberately? Well, the same thing. Either the user wants to look closer at some content by moving from portrait to landscape (in which case, adding content just cancels out the effect), or the user wants to view the same content but with better comfort (that is, they're rotating for ergonomics reasons).
tl;dr - **don't change content after page load**.
|
Personally I'm a supporter of sites with a mix of the two.
* *Fonts should keep the same size both in landscape and portrait. It should merely be distributed differently depending on the current screen width. As you've also showed in the mockup for A.*
I feel that also scaling the text is like surrendering to a notion that "*-ok, we know the text is very small in portrait mode. But if you flip the phone it should be easy to read!*". If that's your stance then size up the text in portrait mode! The only real advantage with having the text smaller in portrait mode is that the user can see more of the page at the same time. But this can also be achieved by thoroughly thinking over the discoverability aspects while designing.
* *Images, can and should be scalable though, as discussed in option B.*
It's hard to have one image size that will fit into your layout perfectly no matter the screen size, wait make that *impossible*. I find that a small image will look puny on a big screen and a big image will be intrusive on a small screen. Plus if you find thresholds that kick in for each screen size interval you can have one layout that fits perfectly into each screen width.
I'd like to recommend you have a look at [food sense](http://foodsense.is/) who have a responsive website that really works well and looks good with five different layouts depending on the width. A funny feature is that they let some images get larger in the smaller displays because that fits better in to the narrower layout.
|
24,255 |
Currently, the standard behaviour for viewing web pages on a mobile is that:
* If viewed in portrait the text is smaller because the width of the device is small and the whole page width needs to fit into view.
* If viewed in landscape the view 'zooms in' as the width is now wider so that the text is larger and more readable, but with less content on screen as a result.
So, this brings a dilemma. When creating a responsive website what should happen on device rotation? *(Not on initial page load, I am referring to what should happen once the site is loaded and you decide to then rotate the screen)*
When rotated from portrait to landscape should you:
* **a)** Re-detect the device widths and map the contents according to the new dimensions (thereby retaining the same font / images sizes as when viewing portrait).
* **b)** Keep the same dimensions and on rotation just bring the content to fit the window (thereby zooming in the content to make it more readable for viewers if the portrait orientation text is too small).

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fOAQVC.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
Bear in mind that with a traditional web-page viewed in the mobile you have the option of pinch-to-zoom the text, so if it's too small you can zoom in. With a responsive site this isn't an option because the site will fit the dimensions so there is nothing to zoom into.
(I guess there is a third option too - use responsive fonts so that the font sizes change according to the screen width. But that's probably a different question altogether).
|
2012/08/02
|
[
"https://ux.stackexchange.com/questions/24255",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3865/"
] |
Let me add a late answer: **after the content has loaded, do not let rotations trigger breakpoints**.
If the user rotates the device accidentally, their most immediate task is to reorient themselves and re-find the content they were viewing or reading at the time of rotation. But a breakpoint trigger, the user is suddenly presented with an interface they don't recognize (which makes them wonder if something has happened), and with additional content that breaks any anchors they'd use for re-finding their initial position. Worse, if the breakpoint *removes* material, there's a chance the content the user wants to re-find has been taken out completely. Discovering that this has happened is a *very* expensive operation.
But what if the user rotates the device deliberately? Well, the same thing. Either the user wants to look closer at some content by moving from portrait to landscape (in which case, adding content just cancels out the effect), or the user wants to view the same content but with better comfort (that is, they're rotating for ergonomics reasons).
tl;dr - **don't change content after page load**.
|
Design for the content to fit within nicely within a range of widths, but don't assume any specific viewport widths. The content should determine the breakpoints for rearrangement and adjustment, not the currently popular device sizes (which is constantly changing).
For some content/applications, the layout structure will change (and elements added/removed as in the calculator example above), and for other content/applications (like a text oriented one) the layout structure will not change as the width changes.
In my experience, regarding text oriented sites, I almost always need to reduce header (h1 etc.) font sizes for narrow viewports but try hard keep the main content font the same size and squeeze the side margins.
But it all depends on the content.
|
24,255 |
Currently, the standard behaviour for viewing web pages on a mobile is that:
* If viewed in portrait the text is smaller because the width of the device is small and the whole page width needs to fit into view.
* If viewed in landscape the view 'zooms in' as the width is now wider so that the text is larger and more readable, but with less content on screen as a result.
So, this brings a dilemma. When creating a responsive website what should happen on device rotation? *(Not on initial page load, I am referring to what should happen once the site is loaded and you decide to then rotate the screen)*
When rotated from portrait to landscape should you:
* **a)** Re-detect the device widths and map the contents according to the new dimensions (thereby retaining the same font / images sizes as when viewing portrait).
* **b)** Keep the same dimensions and on rotation just bring the content to fit the window (thereby zooming in the content to make it more readable for viewers if the portrait orientation text is too small).

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fOAQVC.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
Bear in mind that with a traditional web-page viewed in the mobile you have the option of pinch-to-zoom the text, so if it's too small you can zoom in. With a responsive site this isn't an option because the site will fit the dimensions so there is nothing to zoom into.
(I guess there is a third option too - use responsive fonts so that the font sizes change according to the screen width. But that's probably a different question altogether).
|
2012/08/02
|
[
"https://ux.stackexchange.com/questions/24255",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3865/"
] |
This is delicate, and should be a sound judgment by the designer. There is no right or wrong, neither is there a convention (yet) to rely on. But there are a few things to consider, like zooming in just widening the page, which I feel is useless. If I want to zoom I can snap-in on the text getting it in a more readable form (both in Landscape and Portrait view). So that option is off.
Instead I like pages (or apps) that display more in landscape than in portrait view. On a web page that could be an image, related links or even a “facts box”. On a native application, there are better control, and you could supply more options, like the Windows Phone 7 calculator.


Problem with that is that the user doesn’t know if there is more to see when in landscape – which is bad for user experience, but great fun when you find out about it. My answer would in short be, add more stuff to the view when in landscape, don’t zoom.
|
Design for the content to fit within nicely within a range of widths, but don't assume any specific viewport widths. The content should determine the breakpoints for rearrangement and adjustment, not the currently popular device sizes (which is constantly changing).
For some content/applications, the layout structure will change (and elements added/removed as in the calculator example above), and for other content/applications (like a text oriented one) the layout structure will not change as the width changes.
In my experience, regarding text oriented sites, I almost always need to reduce header (h1 etc.) font sizes for narrow viewports but try hard keep the main content font the same size and squeeze the side margins.
But it all depends on the content.
|
24,255 |
Currently, the standard behaviour for viewing web pages on a mobile is that:
* If viewed in portrait the text is smaller because the width of the device is small and the whole page width needs to fit into view.
* If viewed in landscape the view 'zooms in' as the width is now wider so that the text is larger and more readable, but with less content on screen as a result.
So, this brings a dilemma. When creating a responsive website what should happen on device rotation? *(Not on initial page load, I am referring to what should happen once the site is loaded and you decide to then rotate the screen)*
When rotated from portrait to landscape should you:
* **a)** Re-detect the device widths and map the contents according to the new dimensions (thereby retaining the same font / images sizes as when viewing portrait).
* **b)** Keep the same dimensions and on rotation just bring the content to fit the window (thereby zooming in the content to make it more readable for viewers if the portrait orientation text is too small).

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fOAQVC.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
Bear in mind that with a traditional web-page viewed in the mobile you have the option of pinch-to-zoom the text, so if it's too small you can zoom in. With a responsive site this isn't an option because the site will fit the dimensions so there is nothing to zoom into.
(I guess there is a third option too - use responsive fonts so that the font sizes change according to the screen width. But that's probably a different question altogether).
|
2012/08/02
|
[
"https://ux.stackexchange.com/questions/24255",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3865/"
] |
There are different approaches to device oriented design, and you can implement one of several design patterns to choose from. The first one that comes to mind is the **fluid** design, which (simply put) just reorganize the elements to a better view. Some, less important elements, are hidden as the screen width gets narrower and vice versa.

Next is the **extended** design which adds an element, may or may not be navigation, to the existing screen in vertical orientation. The original screen is left untouched and flipping the device horizontally makes the extended element appear.

There is also the **complementary** design that adds more information going from vertical to horizontal orientation. This could be a grid view of data in vertical becoming a graph in horizontal orientation.

If you want to be bald you could also go with the **continuous** design, which shows a completely different screen in a different orientation. Today it’s not known how users react to that design, but it is possible that elderly users will have a hard time with this design.

>
> Designing for device orientation is not new. For example, when rotated to landscape mode, smartphones open a larger virtual keyboard, and the email applications in tablets switch to a master–detail interface. However, device orientation design is widely treated as secondary to the main interface because it is often missed by users who stick to the default orientation, mainly because they are not aware of its availability. By adding simple visual clues to the interface, UX professionals can make the case for using device orientation to enhance their products and, ultimately, for providing more engaging and user-friendly experiences.
>
>
>
Reference: [UX DESIGN FOR MOBILE Designing For Device Orientation: From Portrait To Landscape](http://uxdesign.smashingmagazine.com/2012/08/10/designing-device-orientation-portrait-landscape/)
|
Design for the content to fit within nicely within a range of widths, but don't assume any specific viewport widths. The content should determine the breakpoints for rearrangement and adjustment, not the currently popular device sizes (which is constantly changing).
For some content/applications, the layout structure will change (and elements added/removed as in the calculator example above), and for other content/applications (like a text oriented one) the layout structure will not change as the width changes.
In my experience, regarding text oriented sites, I almost always need to reduce header (h1 etc.) font sizes for narrow viewports but try hard keep the main content font the same size and squeeze the side margins.
But it all depends on the content.
|
24,255 |
Currently, the standard behaviour for viewing web pages on a mobile is that:
* If viewed in portrait the text is smaller because the width of the device is small and the whole page width needs to fit into view.
* If viewed in landscape the view 'zooms in' as the width is now wider so that the text is larger and more readable, but with less content on screen as a result.
So, this brings a dilemma. When creating a responsive website what should happen on device rotation? *(Not on initial page load, I am referring to what should happen once the site is loaded and you decide to then rotate the screen)*
When rotated from portrait to landscape should you:
* **a)** Re-detect the device widths and map the contents according to the new dimensions (thereby retaining the same font / images sizes as when viewing portrait).
* **b)** Keep the same dimensions and on rotation just bring the content to fit the window (thereby zooming in the content to make it more readable for viewers if the portrait orientation text is too small).

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fOAQVC.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
Bear in mind that with a traditional web-page viewed in the mobile you have the option of pinch-to-zoom the text, so if it's too small you can zoom in. With a responsive site this isn't an option because the site will fit the dimensions so there is nothing to zoom into.
(I guess there is a third option too - use responsive fonts so that the font sizes change according to the screen width. But that's probably a different question altogether).
|
2012/08/02
|
[
"https://ux.stackexchange.com/questions/24255",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3865/"
] |
Design for the content to fit within nicely within a range of widths, but don't assume any specific viewport widths. The content should determine the breakpoints for rearrangement and adjustment, not the currently popular device sizes (which is constantly changing).
For some content/applications, the layout structure will change (and elements added/removed as in the calculator example above), and for other content/applications (like a text oriented one) the layout structure will not change as the width changes.
In my experience, regarding text oriented sites, I almost always need to reduce header (h1 etc.) font sizes for narrow viewports but try hard keep the main content font the same size and squeeze the side margins.
But it all depends on the content.
|
So it is Jan 2017. This was a good question back in 2012 but I feel that our experience may have changed our opinion now. The responsiveness movement seems largely to prefer to follow a rule of
>
> use the space available
>
>
>
by re-organising the layout on orientation change. This seems to have become accepted and expected practice.
OTOH, speaking as an 'old guy' of 50+ years with natural eyesight reduction, I find the lack of pinch-zoom on some web sites a pain and I have some sympathy with the accepted answer from 2012 that suggests keeping the layout the same but just increasing font size.
Anyway enough of my own thinking - do others agree that the world has moved on and this question needs a new answer?
|
24,255 |
Currently, the standard behaviour for viewing web pages on a mobile is that:
* If viewed in portrait the text is smaller because the width of the device is small and the whole page width needs to fit into view.
* If viewed in landscape the view 'zooms in' as the width is now wider so that the text is larger and more readable, but with less content on screen as a result.
So, this brings a dilemma. When creating a responsive website what should happen on device rotation? *(Not on initial page load, I am referring to what should happen once the site is loaded and you decide to then rotate the screen)*
When rotated from portrait to landscape should you:
* **a)** Re-detect the device widths and map the contents according to the new dimensions (thereby retaining the same font / images sizes as when viewing portrait).
* **b)** Keep the same dimensions and on rotation just bring the content to fit the window (thereby zooming in the content to make it more readable for viewers if the portrait orientation text is too small).

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fOAQVC.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
Bear in mind that with a traditional web-page viewed in the mobile you have the option of pinch-to-zoom the text, so if it's too small you can zoom in. With a responsive site this isn't an option because the site will fit the dimensions so there is nothing to zoom into.
(I guess there is a third option too - use responsive fonts so that the font sizes change according to the screen width. But that's probably a different question altogether).
|
2012/08/02
|
[
"https://ux.stackexchange.com/questions/24255",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3865/"
] |
Let me add a late answer: **after the content has loaded, do not let rotations trigger breakpoints**.
If the user rotates the device accidentally, their most immediate task is to reorient themselves and re-find the content they were viewing or reading at the time of rotation. But a breakpoint trigger, the user is suddenly presented with an interface they don't recognize (which makes them wonder if something has happened), and with additional content that breaks any anchors they'd use for re-finding their initial position. Worse, if the breakpoint *removes* material, there's a chance the content the user wants to re-find has been taken out completely. Discovering that this has happened is a *very* expensive operation.
But what if the user rotates the device deliberately? Well, the same thing. Either the user wants to look closer at some content by moving from portrait to landscape (in which case, adding content just cancels out the effect), or the user wants to view the same content but with better comfort (that is, they're rotating for ergonomics reasons).
tl;dr - **don't change content after page load**.
|
There are different approaches to device oriented design, and you can implement one of several design patterns to choose from. The first one that comes to mind is the **fluid** design, which (simply put) just reorganize the elements to a better view. Some, less important elements, are hidden as the screen width gets narrower and vice versa.

Next is the **extended** design which adds an element, may or may not be navigation, to the existing screen in vertical orientation. The original screen is left untouched and flipping the device horizontally makes the extended element appear.

There is also the **complementary** design that adds more information going from vertical to horizontal orientation. This could be a grid view of data in vertical becoming a graph in horizontal orientation.

If you want to be bald you could also go with the **continuous** design, which shows a completely different screen in a different orientation. Today it’s not known how users react to that design, but it is possible that elderly users will have a hard time with this design.

>
> Designing for device orientation is not new. For example, when rotated to landscape mode, smartphones open a larger virtual keyboard, and the email applications in tablets switch to a master–detail interface. However, device orientation design is widely treated as secondary to the main interface because it is often missed by users who stick to the default orientation, mainly because they are not aware of its availability. By adding simple visual clues to the interface, UX professionals can make the case for using device orientation to enhance their products and, ultimately, for providing more engaging and user-friendly experiences.
>
>
>
Reference: [UX DESIGN FOR MOBILE Designing For Device Orientation: From Portrait To Landscape](http://uxdesign.smashingmagazine.com/2012/08/10/designing-device-orientation-portrait-landscape/)
|
24,255 |
Currently, the standard behaviour for viewing web pages on a mobile is that:
* If viewed in portrait the text is smaller because the width of the device is small and the whole page width needs to fit into view.
* If viewed in landscape the view 'zooms in' as the width is now wider so that the text is larger and more readable, but with less content on screen as a result.
So, this brings a dilemma. When creating a responsive website what should happen on device rotation? *(Not on initial page load, I am referring to what should happen once the site is loaded and you decide to then rotate the screen)*
When rotated from portrait to landscape should you:
* **a)** Re-detect the device widths and map the contents according to the new dimensions (thereby retaining the same font / images sizes as when viewing portrait).
* **b)** Keep the same dimensions and on rotation just bring the content to fit the window (thereby zooming in the content to make it more readable for viewers if the portrait orientation text is too small).

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fOAQVC.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
Bear in mind that with a traditional web-page viewed in the mobile you have the option of pinch-to-zoom the text, so if it's too small you can zoom in. With a responsive site this isn't an option because the site will fit the dimensions so there is nothing to zoom into.
(I guess there is a third option too - use responsive fonts so that the font sizes change according to the screen width. But that's probably a different question altogether).
|
2012/08/02
|
[
"https://ux.stackexchange.com/questions/24255",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3865/"
] |
Design for the content to fit within nicely within a range of widths, but don't assume any specific viewport widths. The content should determine the breakpoints for rearrangement and adjustment, not the currently popular device sizes (which is constantly changing).
For some content/applications, the layout structure will change (and elements added/removed as in the calculator example above), and for other content/applications (like a text oriented one) the layout structure will not change as the width changes.
In my experience, regarding text oriented sites, I almost always need to reduce header (h1 etc.) font sizes for narrow viewports but try hard keep the main content font the same size and squeeze the side margins.
But it all depends on the content.
|
For consistencies sake, I'd ensure that the page on a device that started in portrait and is rotated to landscape is the same as if I'd started on landscape in the first place. If a user visits your site on two different occasions and it's different because of what orientation the user started out with, she's going to be confused.
At which point I'd argue that I want the best experience for whatever my 'current' form factor is. A left-side navigation would be very poor in portrait, but very much more welcome in landscape.
|
24,255 |
Currently, the standard behaviour for viewing web pages on a mobile is that:
* If viewed in portrait the text is smaller because the width of the device is small and the whole page width needs to fit into view.
* If viewed in landscape the view 'zooms in' as the width is now wider so that the text is larger and more readable, but with less content on screen as a result.
So, this brings a dilemma. When creating a responsive website what should happen on device rotation? *(Not on initial page load, I am referring to what should happen once the site is loaded and you decide to then rotate the screen)*
When rotated from portrait to landscape should you:
* **a)** Re-detect the device widths and map the contents according to the new dimensions (thereby retaining the same font / images sizes as when viewing portrait).
* **b)** Keep the same dimensions and on rotation just bring the content to fit the window (thereby zooming in the content to make it more readable for viewers if the portrait orientation text is too small).

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fOAQVC.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
Bear in mind that with a traditional web-page viewed in the mobile you have the option of pinch-to-zoom the text, so if it's too small you can zoom in. With a responsive site this isn't an option because the site will fit the dimensions so there is nothing to zoom into.
(I guess there is a third option too - use responsive fonts so that the font sizes change according to the screen width. But that's probably a different question altogether).
|
2012/08/02
|
[
"https://ux.stackexchange.com/questions/24255",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3865/"
] |
Personally I'm a supporter of sites with a mix of the two.
* *Fonts should keep the same size both in landscape and portrait. It should merely be distributed differently depending on the current screen width. As you've also showed in the mockup for A.*
I feel that also scaling the text is like surrendering to a notion that "*-ok, we know the text is very small in portrait mode. But if you flip the phone it should be easy to read!*". If that's your stance then size up the text in portrait mode! The only real advantage with having the text smaller in portrait mode is that the user can see more of the page at the same time. But this can also be achieved by thoroughly thinking over the discoverability aspects while designing.
* *Images, can and should be scalable though, as discussed in option B.*
It's hard to have one image size that will fit into your layout perfectly no matter the screen size, wait make that *impossible*. I find that a small image will look puny on a big screen and a big image will be intrusive on a small screen. Plus if you find thresholds that kick in for each screen size interval you can have one layout that fits perfectly into each screen width.
I'd like to recommend you have a look at [food sense](http://foodsense.is/) who have a responsive website that really works well and looks good with five different layouts depending on the width. A funny feature is that they let some images get larger in the smaller displays because that fits better in to the narrower layout.
|
Design for the content to fit within nicely within a range of widths, but don't assume any specific viewport widths. The content should determine the breakpoints for rearrangement and adjustment, not the currently popular device sizes (which is constantly changing).
For some content/applications, the layout structure will change (and elements added/removed as in the calculator example above), and for other content/applications (like a text oriented one) the layout structure will not change as the width changes.
In my experience, regarding text oriented sites, I almost always need to reduce header (h1 etc.) font sizes for narrow viewports but try hard keep the main content font the same size and squeeze the side margins.
But it all depends on the content.
|
24,255 |
Currently, the standard behaviour for viewing web pages on a mobile is that:
* If viewed in portrait the text is smaller because the width of the device is small and the whole page width needs to fit into view.
* If viewed in landscape the view 'zooms in' as the width is now wider so that the text is larger and more readable, but with less content on screen as a result.
So, this brings a dilemma. When creating a responsive website what should happen on device rotation? *(Not on initial page load, I am referring to what should happen once the site is loaded and you decide to then rotate the screen)*
When rotated from portrait to landscape should you:
* **a)** Re-detect the device widths and map the contents according to the new dimensions (thereby retaining the same font / images sizes as when viewing portrait).
* **b)** Keep the same dimensions and on rotation just bring the content to fit the window (thereby zooming in the content to make it more readable for viewers if the portrait orientation text is too small).

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fOAQVC.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
Bear in mind that with a traditional web-page viewed in the mobile you have the option of pinch-to-zoom the text, so if it's too small you can zoom in. With a responsive site this isn't an option because the site will fit the dimensions so there is nothing to zoom into.
(I guess there is a third option too - use responsive fonts so that the font sizes change according to the screen width. But that's probably a different question altogether).
|
2012/08/02
|
[
"https://ux.stackexchange.com/questions/24255",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3865/"
] |
Let me add a late answer: **after the content has loaded, do not let rotations trigger breakpoints**.
If the user rotates the device accidentally, their most immediate task is to reorient themselves and re-find the content they were viewing or reading at the time of rotation. But a breakpoint trigger, the user is suddenly presented with an interface they don't recognize (which makes them wonder if something has happened), and with additional content that breaks any anchors they'd use for re-finding their initial position. Worse, if the breakpoint *removes* material, there's a chance the content the user wants to re-find has been taken out completely. Discovering that this has happened is a *very* expensive operation.
But what if the user rotates the device deliberately? Well, the same thing. Either the user wants to look closer at some content by moving from portrait to landscape (in which case, adding content just cancels out the effect), or the user wants to view the same content but with better comfort (that is, they're rotating for ergonomics reasons).
tl;dr - **don't change content after page load**.
|
So it is Jan 2017. This was a good question back in 2012 but I feel that our experience may have changed our opinion now. The responsiveness movement seems largely to prefer to follow a rule of
>
> use the space available
>
>
>
by re-organising the layout on orientation change. This seems to have become accepted and expected practice.
OTOH, speaking as an 'old guy' of 50+ years with natural eyesight reduction, I find the lack of pinch-zoom on some web sites a pain and I have some sympathy with the accepted answer from 2012 that suggests keeping the layout the same but just increasing font size.
Anyway enough of my own thinking - do others agree that the world has moved on and this question needs a new answer?
|
24,255 |
Currently, the standard behaviour for viewing web pages on a mobile is that:
* If viewed in portrait the text is smaller because the width of the device is small and the whole page width needs to fit into view.
* If viewed in landscape the view 'zooms in' as the width is now wider so that the text is larger and more readable, but with less content on screen as a result.
So, this brings a dilemma. When creating a responsive website what should happen on device rotation? *(Not on initial page load, I am referring to what should happen once the site is loaded and you decide to then rotate the screen)*
When rotated from portrait to landscape should you:
* **a)** Re-detect the device widths and map the contents according to the new dimensions (thereby retaining the same font / images sizes as when viewing portrait).
* **b)** Keep the same dimensions and on rotation just bring the content to fit the window (thereby zooming in the content to make it more readable for viewers if the portrait orientation text is too small).

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fOAQVC.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
Bear in mind that with a traditional web-page viewed in the mobile you have the option of pinch-to-zoom the text, so if it's too small you can zoom in. With a responsive site this isn't an option because the site will fit the dimensions so there is nothing to zoom into.
(I guess there is a third option too - use responsive fonts so that the font sizes change according to the screen width. But that's probably a different question altogether).
|
2012/08/02
|
[
"https://ux.stackexchange.com/questions/24255",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3865/"
] |
This is delicate, and should be a sound judgment by the designer. There is no right or wrong, neither is there a convention (yet) to rely on. But there are a few things to consider, like zooming in just widening the page, which I feel is useless. If I want to zoom I can snap-in on the text getting it in a more readable form (both in Landscape and Portrait view). So that option is off.
Instead I like pages (or apps) that display more in landscape than in portrait view. On a web page that could be an image, related links or even a “facts box”. On a native application, there are better control, and you could supply more options, like the Windows Phone 7 calculator.


Problem with that is that the user doesn’t know if there is more to see when in landscape – which is bad for user experience, but great fun when you find out about it. My answer would in short be, add more stuff to the view when in landscape, don’t zoom.
|
So it is Jan 2017. This was a good question back in 2012 but I feel that our experience may have changed our opinion now. The responsiveness movement seems largely to prefer to follow a rule of
>
> use the space available
>
>
>
by re-organising the layout on orientation change. This seems to have become accepted and expected practice.
OTOH, speaking as an 'old guy' of 50+ years with natural eyesight reduction, I find the lack of pinch-zoom on some web sites a pain and I have some sympathy with the accepted answer from 2012 that suggests keeping the layout the same but just increasing font size.
Anyway enough of my own thinking - do others agree that the world has moved on and this question needs a new answer?
|
11,353,545 |
I have attached a zip with an FLA that you can run in CS 5.5. The animation contains a performance analyser and sliders to control various parameters.
Demo:
<http://sephardi.ehclients.com/alivetest/index.html>
Click anywhere to start the animation
Files:
<https://www.dropbox.com/s/4rcpvzo1h7br8fh/alivesource.zip>
I have written a program that draws lines pixel by pixel and animates them in a wave-like manner, and displaces certain pixels using a displacement map.
This is what happens on each loop:
1. Display objects and variables from previous loop are cleared
2. Displacement map is stored in a bitmap data object
3. A line is drawn pixel by pixel by reading the y coordinates stored in an array. It's value is also altered using corresponding displacement map and sine wave data.
I have setup sliders with which you can control how many lines are drawn (linecount), the width of each line (canvaswidth), and the resolution of each line (res).
The performance is pretty poor, and I would like your help in optimising it. Maybe there is nothing I can do to optimise my code, please let me know.
I don't think caching as bitmap data is possible because the lines are in permanent motion
Keep in mind, I would really like to preserve 35 lines and a resolution of 1 pixel per iteration
Many thanks
UPDATE:
I am now using drawPath to draw the line rather than drawing pixel by pixel.
```
/*
Click anywhere on the stage to start anim
*/
import flash.display.BitmapData;
import com.greensock.*;
import flash.display.Shape;
import uk.co.soulwire.*;
import net.hires.debug.Stats;
import uk.co.soulwire.gui.SimpleGUI;
import flash.display.MovieClip;
import flash.display.Sprite;
/*
Performance analyser and variable sliders
*/
var stats:Stats;
var gui:SimpleGUI;
var guiholder:MovieClip;
stats=new Stats();
stats.x = 1200;
stats.y = 0;
addChild(stats);
gui = new SimpleGUI(this,"Parameters","h",1000,0);
gui.show();
/*
Stores the base coordinates
*/
var c:Coordinates;
c=new Coordinates();
/*
Holds the lines
*/
var holder:MovieClip = new MovieClip ;
addChild(holder);
/*
Generic variables
*/
var i:uint;
var j:uint;
var line:Sprite;
var lines:Array = [];
var bmd:BitmapData;
var brightness = 0;
var sinus = 0;
/**
*
Parameters used to control the animaitons and extrusions
*
**/
/*
How many pixels do we draw in each loop?
*/
var scaleFactor:Number=2
var canvasWidth:Number = 999;
var lineCount:Number = 35;
var res = 1;//Skip res-1 pixels per loop to lower the resolution
/*
Displacement map properties
*/
var extrusion:Number = 1;
var extrusiontarget:Number = .1;
var tolerance:Number = 1;
var smoothness = 10;
//Sinewave
var lasti = 0;
var sinedirection = -1;
var sineamplitude:Number = 3;
var sinespeed = 0.5;
var sinedensity = 100;
/*
Breathing animation
*/
var inhale:Number = 2;
var exhale:Number = 2;
var beforeInhale:Number = 0;
var beforeExhale:Number = 0;
/*
Add sliders to control the above variables
*/
gui.addGroup("Pixels being drawn");
gui.addSlider("lineCount", 5, 35);
gui.addSlider("canvasWidth",30,999);
gui.addSlider("res",1,10);
gui.addGroup("Displacement Map");
gui.addSlider("smoothness", 1, 100,{callback:setBlur});
gui.addSlider("tolerance", 1, 255);
gui.addSlider("extrusiontarget", 0.1, 3);
gui.addGroup("Sinwave");
gui.addSlider("sinedirection",-1,1);
gui.addSlider("sineamplitude",0,30);
gui.addSlider("sinespeed",0,10);
gui.addGroup("Breathing");
gui.addSlider("beforeInhale",0,5);
gui.addSlider("inhale",0,5);
gui.addSlider("beforeExhale",0,5);
gui.addSlider("exhale",0,5);
/**
Loop
**/
function myEnterFrame(event:Event):void {
/*
Start a new iteration of line drawing, triggered when you click anywhere ons tage
*/
drawLines();
}
function drawLines():void {
for (i=0; i<lines.length; i++) {
holder.removeChild(lines[i]);
lines[i] = null;
}
lines = [];
for (i=0; i<lineCount; i++) {
drawLine(i);
}
}
function resetBitmapData(){
bmd = null;
bmd = new BitmapData(canvasWidth,1000);
bmd.draw(mc);
mc.visible = false;
}
/**
plot the cordinates of each point absed on sin data and bmp brihgtness
**/
var targety:Number;
var myPath:GraphicsPath;
var myStroke:GraphicsStroke;
var myDrawing:Vector.<IGraphicsData > ;
var myFill:GraphicsSolidFill;
myFill= new GraphicsSolidFill();
myFill.color = 0x000000;
function drawLine(linenumber):void {
line=new Sprite();
holder.addChild(line);
myPath= new GraphicsPath(new Vector.<int>(), new Vector.<Number>());
myStroke = new GraphicsStroke(res);
myStroke.fill = new GraphicsSolidFill(0xff0000);// solid stroke
for (j=0; j<canvasWidth; j+=res) {
brightness = Math.ceil(getbrightness(getcolor(j,c.coords[linenumber][j]))/tolerance) ;
sinus= Math.sin((j + (lasti * sinespeed)) / sinedensity) * sineamplitude;
targety=c.coords[linenumber][j]-(sinus*0)-(brightness*extrusion)-(sinus*(linenumber-15)*1);
myPath.commands.push(2);
myPath.data.push(j,targety);
}
myPath.commands.push(2);
myPath.data.push(0,1000);
myDrawing = new Vector.<IGraphicsData>();
myDrawing.push(myStroke,myFill, myPath);
line.graphics.drawGraphicsData(myDrawing);
lines.push(line);
lasti -= sinedirection;
}
/*
Functions to retrieve brightness of displacement map
*/
function getcolor(xx,targety):uint {
var pixelValue:uint = bmd.getPixel(xx,targety);
return pixelValue;
}
function getbrightness(colour):Number {
var R:Number = 0;
var G:Number = 0;
var B:Number = 0;
R += colour >> 16 & 0xFF;
G += colour >> 8 & 0xFF;
B += colour & 0xFF;
var br = Math.sqrt(R * R * .241 + G * G * .691 + B * B * .068);
return br;
}
/*
Makes the displacment map "breathe"
*/
function grow():void {
TweenLite.to(this,inhale,{extrusion:extrusiontarget,onComplete:shrink,delay:beforeInhale});
}
function shrink():void {
TweenLite.to(this,exhale,{extrusion:0,onComplete:grow,delay:beforeExhale});
}
/*
Smoothness of displacement map
*/
var blur:BlurFilter = new BlurFilter();
function setBlur():void {
trace("sb");
blur.blurX = smoothness;
blur.blurY = smoothness;
blur.quality = BitmapFilterQuality.HIGH;
mc.word.filters = [blur];
//reset the bitmap data
resetBitmapData()
}
function mouseDownHandler(e) {
grow();
addEventListener(Event.ENTER_FRAME,myEnterFrame);
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
//Draws lines;
setBlur();
drawLines();
```
OLD CODE:
```
/*
Click anywhere on the stage to start anim
*/
import flash.display.BitmapData;
import com.greensock.*;
import flash.display.Shape;
import uk.co.soulwire.*;
import net.hires.debug.Stats;
import uk.co.soulwire.gui.SimpleGUI;
import flash.display.MovieClip;
/*
Performance analyser and variable sliders
*/
var stats:Stats;
var gui:SimpleGUI;
var guiholder:MovieClip;
stats=new Stats();
stats.x = 1200
stats.y = 0;
addChild(stats);
gui = new SimpleGUI(this,"Parameters","h",1000,0);
gui.show();
/*
Stores the base coordinates
*/
var c:Coordinates;
c=new Coordinates();
/*
Holds the lines
*/
var holder:MovieClip=new MovieClip
addChild(holder)
/*
Generic variables
*/
var i:uint;
var j:uint;
var line:Shape;
var lines:Array = [];
var bmd:BitmapData;
var brightness = 0;
var sinus=0;
/**
*
Parameters used to control the animaitons and extrusions
*
**/
/*
How many pixels do we draw in each loop?
*/
var canvaswidth:Number = 999;
var linecount:Number=35
var res=2//Skip res-1 pixels per loop to lower the resolution
/*
Displacement map properties
*/
var extrusion:Number = 1;
var extrusiontarget:Number = .1;
var tolerance:Number = 1;
var smoothness = 10;
//Sinewave
var lasti = 0;
var sinedirection = -1;
var sineamplitude:Number = 3;
var sinespeed = 0.5;
var sinedensity = 100;
/*
Breathing animation
*/
var inhale:Number = 2;
var exhale:Number = 2;
var beforeInhale:Number = 0;
var beforeExhale:Number = 0;
/*
Add sliders to control the above variables
*/
gui.addGroup("Pixels being drawn")
gui.addSlider("linecount", 5, 35);
gui.addSlider("canvaswidth",30,999);
gui.addSlider("res",1,10);
gui.addGroup("Displacement Map")
gui.addSlider("smoothness", 1, 100,{callback:setblur});
gui.addSlider("tolerance", 1, 255);
gui.addSlider("extrusiontarget", 0.1, 3);
gui.addGroup("Sinwave")
gui.addSlider("sinedirection",-1,1);
gui.addSlider("sineamplitude",0,30);
gui.addSlider("sinespeed",0,10);
gui.addGroup("Breathing")
gui.addSlider("beforeInhale",0,5);
gui.addSlider("inhale",0,5);
gui.addSlider("beforeExhale",0,5);
gui.addSlider("exhale",0,5);
/**
Loop
**/
function myEnterFrame(event:Event):void {
/*
Start a new iteration of line drawing, triggered when you click anywhere ons tage
*/
initdraw();
}
/**
Clear the lines
Clear the bmp data
Redraw the bitmpa data
Redraw the lines
**/
function initdraw():void {
/*
Clear previous lines and displacement map data
Lance drawing of 35 lines
*/
for (i=0; i<lines.length; i++) {
holder.removeChild(lines[i]);
lines[i] = null;
}
bmd = null;
bmd = new BitmapData(canvaswidth,400);
bmd.draw(mc);
lines = [];
for (i=0; i<35; i++) {
// for (i=0; i<c.coords.length; i++) {
drawlines(i);
}
}
/**
plot the cordinates of each point absed on sin data and bmp brihgtness
**/
function drawlines(linenumber):void {
/*
Start to draw a line
*/
line =new Shape();
line.graphics.lineStyle(1, 0xdddddd);
line.graphics.beginFill(0x000000);
line.graphics.moveTo(-1,0);
/*
Increase length by 1 * times resolution and
Adjust y values based on displacement map and sinewave data
*/
for (j=0; j<canvaswidth; j+=res) {
if (c.coords[linenumber][j] ==1100) {
line.graphics.lineStyle(1, 0x000000);
} else {
line.graphics.lineStyle(1, 0xFFffff);
}
brightness = Math.ceil(getbrightness(getcolor(j,c.coords[linenumber][j]))/tolerance) ;
sinus= Math.sin((j + (lasti * sinespeed)) / sinedensity) * sineamplitude;
line.graphics.lineTo(j,c.coords[linenumber][j]-sinus-(brightness*extrusion));
}
/*
Close the path that the line is drawing
*/
lasti -= sinedirection;
line.graphics.lineTo(500,1100);
line.graphics.lineTo(-1,1100);
line.graphics.endFill();
lines.push(line);
holder.addChild(line);
}
/*
Smoothness of displacement map
*/
var blur:BlurFilter = new BlurFilter();
function setblur():void {
trace("sb");
blur.blurX = smoothness;
blur.blurY = smoothness;
blur.quality = BitmapFilterQuality.HIGH;
mc.word.filters = [blur];
}
/*
Functions to retrieve brightness of displacement map
*/
function getcolor(xx,yy):uint {
var pixelValue:uint = bmd.getPixel(xx,yy);
return pixelValue;
}
function getbrightness(colour):Number {
var R:Number = 0;
var G:Number = 0;
var B:Number = 0;
R += colour >> 16 & 0xFF;
G += colour >> 8 & 0xFF;
B += colour & 0xFF;
var br = Math.sqrt(R * R * .241 + G * G * .691 + B * B * .068);
return br;
}
/*
Makes the displacment map stringer then weaker
*/
function grow():void {
TweenLite.to(this,inhale,{extrusion:extrusiontarget,onComplete:shrink,delay:beforeInhale});
}
function shrink():void {
TweenLite.to(this,exhale,{extrusion:0,onComplete:grow,delay:beforeExhale});
}
function mouseDownHandler(e){
grow();
addEventListener(Event.ENTER_FRAME,myEnterFrame);
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
//Draws lines
initdraw();
setblur()
```
|
2012/07/05
|
[
"https://Stackoverflow.com/questions/11353545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471866/"
] |
Try this(not tested):
```
WITH FullData AS
(
SELECT a.*,
ROW_NUMBER() OVER(PARTITION BY acc_id2 ORDER BY acc_grp_id1 DESC) AS Position
FROM <YOUR-TABLE> a
), FilteredData AS
(
SELECT *
FROM FullData
WHERE Position = 1
AND acc_parameter_1 = 2
AND acc_parameter_2 = 166
)
SELECT a.*
FROM FullData a LEFT JOIN FilteredData b
ON a.acc_id2 = b.acc_id2
WHERE (b.acc_id2 IS NULL AND a.Position = 1) -- Should be a.Position instead of b.Position
OR b.acc_id2 IS NOT NULL
```
|
This should work :
```
SELECT AC.*
FROM (
SELECT T.acc_id1,max(acc_grp_id1) maxacc_grp_id1
FROM tbl T
GROUP by t.acc_id1
) M
INNER JOIN tbl Last on Last.acc_id1=M.acc_id1
AND Last.acc_grp_id1=M.maxacc_grp_id1
INNER JOIN tbl AC on AC.acc_id1=M.acc_id1
and ((Last.acc_parameter1 =2 and Last.acc_parameter2=166)
OR ac.acc_grp_id1=M.maxacc_grp_id1)
```
|
11,353,545 |
I have attached a zip with an FLA that you can run in CS 5.5. The animation contains a performance analyser and sliders to control various parameters.
Demo:
<http://sephardi.ehclients.com/alivetest/index.html>
Click anywhere to start the animation
Files:
<https://www.dropbox.com/s/4rcpvzo1h7br8fh/alivesource.zip>
I have written a program that draws lines pixel by pixel and animates them in a wave-like manner, and displaces certain pixels using a displacement map.
This is what happens on each loop:
1. Display objects and variables from previous loop are cleared
2. Displacement map is stored in a bitmap data object
3. A line is drawn pixel by pixel by reading the y coordinates stored in an array. It's value is also altered using corresponding displacement map and sine wave data.
I have setup sliders with which you can control how many lines are drawn (linecount), the width of each line (canvaswidth), and the resolution of each line (res).
The performance is pretty poor, and I would like your help in optimising it. Maybe there is nothing I can do to optimise my code, please let me know.
I don't think caching as bitmap data is possible because the lines are in permanent motion
Keep in mind, I would really like to preserve 35 lines and a resolution of 1 pixel per iteration
Many thanks
UPDATE:
I am now using drawPath to draw the line rather than drawing pixel by pixel.
```
/*
Click anywhere on the stage to start anim
*/
import flash.display.BitmapData;
import com.greensock.*;
import flash.display.Shape;
import uk.co.soulwire.*;
import net.hires.debug.Stats;
import uk.co.soulwire.gui.SimpleGUI;
import flash.display.MovieClip;
import flash.display.Sprite;
/*
Performance analyser and variable sliders
*/
var stats:Stats;
var gui:SimpleGUI;
var guiholder:MovieClip;
stats=new Stats();
stats.x = 1200;
stats.y = 0;
addChild(stats);
gui = new SimpleGUI(this,"Parameters","h",1000,0);
gui.show();
/*
Stores the base coordinates
*/
var c:Coordinates;
c=new Coordinates();
/*
Holds the lines
*/
var holder:MovieClip = new MovieClip ;
addChild(holder);
/*
Generic variables
*/
var i:uint;
var j:uint;
var line:Sprite;
var lines:Array = [];
var bmd:BitmapData;
var brightness = 0;
var sinus = 0;
/**
*
Parameters used to control the animaitons and extrusions
*
**/
/*
How many pixels do we draw in each loop?
*/
var scaleFactor:Number=2
var canvasWidth:Number = 999;
var lineCount:Number = 35;
var res = 1;//Skip res-1 pixels per loop to lower the resolution
/*
Displacement map properties
*/
var extrusion:Number = 1;
var extrusiontarget:Number = .1;
var tolerance:Number = 1;
var smoothness = 10;
//Sinewave
var lasti = 0;
var sinedirection = -1;
var sineamplitude:Number = 3;
var sinespeed = 0.5;
var sinedensity = 100;
/*
Breathing animation
*/
var inhale:Number = 2;
var exhale:Number = 2;
var beforeInhale:Number = 0;
var beforeExhale:Number = 0;
/*
Add sliders to control the above variables
*/
gui.addGroup("Pixels being drawn");
gui.addSlider("lineCount", 5, 35);
gui.addSlider("canvasWidth",30,999);
gui.addSlider("res",1,10);
gui.addGroup("Displacement Map");
gui.addSlider("smoothness", 1, 100,{callback:setBlur});
gui.addSlider("tolerance", 1, 255);
gui.addSlider("extrusiontarget", 0.1, 3);
gui.addGroup("Sinwave");
gui.addSlider("sinedirection",-1,1);
gui.addSlider("sineamplitude",0,30);
gui.addSlider("sinespeed",0,10);
gui.addGroup("Breathing");
gui.addSlider("beforeInhale",0,5);
gui.addSlider("inhale",0,5);
gui.addSlider("beforeExhale",0,5);
gui.addSlider("exhale",0,5);
/**
Loop
**/
function myEnterFrame(event:Event):void {
/*
Start a new iteration of line drawing, triggered when you click anywhere ons tage
*/
drawLines();
}
function drawLines():void {
for (i=0; i<lines.length; i++) {
holder.removeChild(lines[i]);
lines[i] = null;
}
lines = [];
for (i=0; i<lineCount; i++) {
drawLine(i);
}
}
function resetBitmapData(){
bmd = null;
bmd = new BitmapData(canvasWidth,1000);
bmd.draw(mc);
mc.visible = false;
}
/**
plot the cordinates of each point absed on sin data and bmp brihgtness
**/
var targety:Number;
var myPath:GraphicsPath;
var myStroke:GraphicsStroke;
var myDrawing:Vector.<IGraphicsData > ;
var myFill:GraphicsSolidFill;
myFill= new GraphicsSolidFill();
myFill.color = 0x000000;
function drawLine(linenumber):void {
line=new Sprite();
holder.addChild(line);
myPath= new GraphicsPath(new Vector.<int>(), new Vector.<Number>());
myStroke = new GraphicsStroke(res);
myStroke.fill = new GraphicsSolidFill(0xff0000);// solid stroke
for (j=0; j<canvasWidth; j+=res) {
brightness = Math.ceil(getbrightness(getcolor(j,c.coords[linenumber][j]))/tolerance) ;
sinus= Math.sin((j + (lasti * sinespeed)) / sinedensity) * sineamplitude;
targety=c.coords[linenumber][j]-(sinus*0)-(brightness*extrusion)-(sinus*(linenumber-15)*1);
myPath.commands.push(2);
myPath.data.push(j,targety);
}
myPath.commands.push(2);
myPath.data.push(0,1000);
myDrawing = new Vector.<IGraphicsData>();
myDrawing.push(myStroke,myFill, myPath);
line.graphics.drawGraphicsData(myDrawing);
lines.push(line);
lasti -= sinedirection;
}
/*
Functions to retrieve brightness of displacement map
*/
function getcolor(xx,targety):uint {
var pixelValue:uint = bmd.getPixel(xx,targety);
return pixelValue;
}
function getbrightness(colour):Number {
var R:Number = 0;
var G:Number = 0;
var B:Number = 0;
R += colour >> 16 & 0xFF;
G += colour >> 8 & 0xFF;
B += colour & 0xFF;
var br = Math.sqrt(R * R * .241 + G * G * .691 + B * B * .068);
return br;
}
/*
Makes the displacment map "breathe"
*/
function grow():void {
TweenLite.to(this,inhale,{extrusion:extrusiontarget,onComplete:shrink,delay:beforeInhale});
}
function shrink():void {
TweenLite.to(this,exhale,{extrusion:0,onComplete:grow,delay:beforeExhale});
}
/*
Smoothness of displacement map
*/
var blur:BlurFilter = new BlurFilter();
function setBlur():void {
trace("sb");
blur.blurX = smoothness;
blur.blurY = smoothness;
blur.quality = BitmapFilterQuality.HIGH;
mc.word.filters = [blur];
//reset the bitmap data
resetBitmapData()
}
function mouseDownHandler(e) {
grow();
addEventListener(Event.ENTER_FRAME,myEnterFrame);
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
//Draws lines;
setBlur();
drawLines();
```
OLD CODE:
```
/*
Click anywhere on the stage to start anim
*/
import flash.display.BitmapData;
import com.greensock.*;
import flash.display.Shape;
import uk.co.soulwire.*;
import net.hires.debug.Stats;
import uk.co.soulwire.gui.SimpleGUI;
import flash.display.MovieClip;
/*
Performance analyser and variable sliders
*/
var stats:Stats;
var gui:SimpleGUI;
var guiholder:MovieClip;
stats=new Stats();
stats.x = 1200
stats.y = 0;
addChild(stats);
gui = new SimpleGUI(this,"Parameters","h",1000,0);
gui.show();
/*
Stores the base coordinates
*/
var c:Coordinates;
c=new Coordinates();
/*
Holds the lines
*/
var holder:MovieClip=new MovieClip
addChild(holder)
/*
Generic variables
*/
var i:uint;
var j:uint;
var line:Shape;
var lines:Array = [];
var bmd:BitmapData;
var brightness = 0;
var sinus=0;
/**
*
Parameters used to control the animaitons and extrusions
*
**/
/*
How many pixels do we draw in each loop?
*/
var canvaswidth:Number = 999;
var linecount:Number=35
var res=2//Skip res-1 pixels per loop to lower the resolution
/*
Displacement map properties
*/
var extrusion:Number = 1;
var extrusiontarget:Number = .1;
var tolerance:Number = 1;
var smoothness = 10;
//Sinewave
var lasti = 0;
var sinedirection = -1;
var sineamplitude:Number = 3;
var sinespeed = 0.5;
var sinedensity = 100;
/*
Breathing animation
*/
var inhale:Number = 2;
var exhale:Number = 2;
var beforeInhale:Number = 0;
var beforeExhale:Number = 0;
/*
Add sliders to control the above variables
*/
gui.addGroup("Pixels being drawn")
gui.addSlider("linecount", 5, 35);
gui.addSlider("canvaswidth",30,999);
gui.addSlider("res",1,10);
gui.addGroup("Displacement Map")
gui.addSlider("smoothness", 1, 100,{callback:setblur});
gui.addSlider("tolerance", 1, 255);
gui.addSlider("extrusiontarget", 0.1, 3);
gui.addGroup("Sinwave")
gui.addSlider("sinedirection",-1,1);
gui.addSlider("sineamplitude",0,30);
gui.addSlider("sinespeed",0,10);
gui.addGroup("Breathing")
gui.addSlider("beforeInhale",0,5);
gui.addSlider("inhale",0,5);
gui.addSlider("beforeExhale",0,5);
gui.addSlider("exhale",0,5);
/**
Loop
**/
function myEnterFrame(event:Event):void {
/*
Start a new iteration of line drawing, triggered when you click anywhere ons tage
*/
initdraw();
}
/**
Clear the lines
Clear the bmp data
Redraw the bitmpa data
Redraw the lines
**/
function initdraw():void {
/*
Clear previous lines and displacement map data
Lance drawing of 35 lines
*/
for (i=0; i<lines.length; i++) {
holder.removeChild(lines[i]);
lines[i] = null;
}
bmd = null;
bmd = new BitmapData(canvaswidth,400);
bmd.draw(mc);
lines = [];
for (i=0; i<35; i++) {
// for (i=0; i<c.coords.length; i++) {
drawlines(i);
}
}
/**
plot the cordinates of each point absed on sin data and bmp brihgtness
**/
function drawlines(linenumber):void {
/*
Start to draw a line
*/
line =new Shape();
line.graphics.lineStyle(1, 0xdddddd);
line.graphics.beginFill(0x000000);
line.graphics.moveTo(-1,0);
/*
Increase length by 1 * times resolution and
Adjust y values based on displacement map and sinewave data
*/
for (j=0; j<canvaswidth; j+=res) {
if (c.coords[linenumber][j] ==1100) {
line.graphics.lineStyle(1, 0x000000);
} else {
line.graphics.lineStyle(1, 0xFFffff);
}
brightness = Math.ceil(getbrightness(getcolor(j,c.coords[linenumber][j]))/tolerance) ;
sinus= Math.sin((j + (lasti * sinespeed)) / sinedensity) * sineamplitude;
line.graphics.lineTo(j,c.coords[linenumber][j]-sinus-(brightness*extrusion));
}
/*
Close the path that the line is drawing
*/
lasti -= sinedirection;
line.graphics.lineTo(500,1100);
line.graphics.lineTo(-1,1100);
line.graphics.endFill();
lines.push(line);
holder.addChild(line);
}
/*
Smoothness of displacement map
*/
var blur:BlurFilter = new BlurFilter();
function setblur():void {
trace("sb");
blur.blurX = smoothness;
blur.blurY = smoothness;
blur.quality = BitmapFilterQuality.HIGH;
mc.word.filters = [blur];
}
/*
Functions to retrieve brightness of displacement map
*/
function getcolor(xx,yy):uint {
var pixelValue:uint = bmd.getPixel(xx,yy);
return pixelValue;
}
function getbrightness(colour):Number {
var R:Number = 0;
var G:Number = 0;
var B:Number = 0;
R += colour >> 16 & 0xFF;
G += colour >> 8 & 0xFF;
B += colour & 0xFF;
var br = Math.sqrt(R * R * .241 + G * G * .691 + B * B * .068);
return br;
}
/*
Makes the displacment map stringer then weaker
*/
function grow():void {
TweenLite.to(this,inhale,{extrusion:extrusiontarget,onComplete:shrink,delay:beforeInhale});
}
function shrink():void {
TweenLite.to(this,exhale,{extrusion:0,onComplete:grow,delay:beforeExhale});
}
function mouseDownHandler(e){
grow();
addEventListener(Event.ENTER_FRAME,myEnterFrame);
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
//Draws lines
initdraw();
setblur()
```
|
2012/07/05
|
[
"https://Stackoverflow.com/questions/11353545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471866/"
] |
Try this solution:
```
SELECT
a.*
FROM
tbl a
INNER JOIN
(
SELECT
bb.*
FROM
(
SELECT acc_id2, MAX(acc_grp_id1) AS maxgrpid
FROM tbl
GROUP BY acc_id2
) aa
INNER JOIN
tbl bb ON
aa.acc_id2 = bb.acc_id2 AND
aa.maxgrpid = bb.acc_grp_id1
) b ON
a.acc_id2 = b.acc_id2 AND
(
(b.acc_parameter1 = 2 AND b.acc_parameter2 = 166) OR
a.acc_grp_id1 = b.acc_grp_id1
)
ORDER BY
a.acc_id1,
a.acc_id2,
a.acc_grp_id1
```
[SQLFiddle Demo](http://sqlfiddle.com/#!4/c35fd/8/0)
|
This should work :
```
SELECT AC.*
FROM (
SELECT T.acc_id1,max(acc_grp_id1) maxacc_grp_id1
FROM tbl T
GROUP by t.acc_id1
) M
INNER JOIN tbl Last on Last.acc_id1=M.acc_id1
AND Last.acc_grp_id1=M.maxacc_grp_id1
INNER JOIN tbl AC on AC.acc_id1=M.acc_id1
and ((Last.acc_parameter1 =2 and Last.acc_parameter2=166)
OR ac.acc_grp_id1=M.maxacc_grp_id1)
```
|
26,503,862 |
I have this jQuery that is displaying content when a div is clicked...
Link 1
Link 2
Link 3
Link 4
Link 5
```
<div class="content-container">
<div id="content1">This is the test content for part 1</div>
<div id="content2">This is the test content for part 2</div>
<div id="content3">This is the test content for part 3</div>
<div id="content4">This is the test content for part 4</div>
<div id="content5">This is the test content for part 5</div>
</div>
```
```js
$(".link").click(function() {
$('.content-container div').fadeOut('slow');
$('#' + $(this).data('rel')).fadeIn('slow');
});
```
<http://jsfiddle.net/Wqc9N/6/>
It is working great, what i want to do now though is add a class to whichever tab is active so that I can style it. Does anyone have an example I can look at to try and apply to my code?
|
2014/10/22
|
[
"https://Stackoverflow.com/questions/26503862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779681/"
] |
There are a few problems here, but firstly, you have not said in what way your code isn’t working. Perhaps we can help more if you provide more information.
I would not recommend using `NSData`’s `dataWithContentsOfURL:`. This method loads data synchronously (code execution in the current function stops until it finishes). This method should typically only be used for local files (with the `file://` URL scheme), not for remote URLs. Look into loading the data asynchronously with [`NSURLSession`](https://developer.apple.com/library/ios/Documentation/Foundation/Reference/NSURLSession_class/index.html) or [`NSURLConnection`](https://developer.apple.com/library/ios/documentation/cocoa/reference/Foundation/Classes/NSURLConnection_Class/index.html), and read Apple’s [*URL Loading System Programming Guide*](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html).
The URL loading system has built-in support for caching, so you should use that if possible and abandon this code entirely. Read [*Understanding Cache Access*](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Concepts/CachePolicies.html#//apple_ref/doc/uid/20001843-BAJEAIEE) in the *URL Loading System Programming Guide* and also the [*NSURLCache* article on *HSHipster*](http://nshipster.com/nsurlcache/).
If you do want to write your own caching system (which I do not recommended) then at least:
* Use the Caches directory instead of the Documents directory (see ev0lution’s comment).
* Avoid `NSFileManager`’s `fileExistsAtPath:` (see [the note in the documentation](https://developer.apple.com/Library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/index.html#//apple_ref/occ/instm/NSFileManager/fileExistsAtPath:)). Instead try loading the image from disk and see if that fails (returns `nil`).
|
In the else part you are just returning image location path. Here you need to pass image name with that path.
So your `else` part should be like this
```
else {
// Load the Image From The File But Update If Needed
NSLog(@"Loading Image From Cache");
// e.g Some image name
NSString *imageName = @"Image1.png";
[imagePath stringByAppendingPathComponent:imageName];
return [UIImage imageWithContentsOfFile:imagePath];
}
```
|
13,647,644 |
I would like to create a package using package maker that when installed adds the .app to the dock.I have tried the below code which works fine when executed from the terminal:-
```
Apples-MacBook-Pro-2:~ apple$ defaults write com.apple.dock persistent-apps -array-add "<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>/Applications/MyApp.app</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>"
Apples-MacBook-Pro-2:~ apple$ killall Dock
```
I want to add the above script on the package maker.Can anybody please tell me how to do so?
Thanks a lot!
|
2012/11/30
|
[
"https://Stackoverflow.com/questions/13647644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632189/"
] |
You can use a tool known as "packages" it comes with pre installed script with an option of adding the software to dock.
[use the following link for packages](http://s.sudre.free.fr/Software/Packages/about.html)
|
You can perform any additional actions from the `postinstall` script of your package. All you need to do is to include a postinstall script (shell script in your case) and add the command you mentioned in your question.
This will be executed after all the files are installed in the system and your dock icon will get added after that.
You can check below link for any additional info regarding packagemaker.
<http://macinstallers.blogspot.in/>
|
1,138,313 |
I am stuck on this related rates question:
The relation between distance $s$ and velocity $v$ is given by $v=\dfrac {150s} {3+s}$. Find the acceleration in terms of s.
So far I have:
$$\dfrac {dv} {dt}=\dfrac {\left( 3+s\right) \dfrac {d} {dt}\left( 150s\right) -150s\dfrac {d} {d t}\left( 3+s\right) } {\left( 3+s\right) ^{2}}$$
$$\dfrac {dv} {dt}=\dfrac {\left( 3+s\right) \left( 150\right)\dfrac {ds} {dt}-150s\left( 1\right) \dfrac {ds} {dt}} {\left( 3+s\right) ^{2}}$$
Let $a=\dfrac{dv}{dt}$ and $v=\dfrac{ds}{dt}$
$$a=\dfrac {450v+150sv-150sv} {\left( 3+s\right) ^{2}}$$
$$a=\dfrac {450v} {\left( 3+s\right) ^{2}}[m/s^2]$$
Is my solution correct? Am I close?
|
2015/02/07
|
[
"https://math.stackexchange.com/questions/1138313",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/30074/"
] |
here is another way to do this. $$ v = \frac{150s}{3+s} = 150 - \frac{450}{s+3}$$
now use chain rule $$\frac{dv}{dt} = \frac{dv}{ds} \frac{ds}{dt} =
\frac{450}{(s+3)^2} v = \frac{450\*150s}{(s+3)^3}$$
|
The relation between distance s and velocity v is given by v=150s/(3+s). Find the acceleration in terms of s.
In order to find acceleration, a = dv/dt
$$v = 150s/(3+s)$$
Using the Quotient Rule:
$$dv/dt = ((150s)'\*(3+s)-150s\*(3+s)')/(3+s)^2$$
$$dv/dt = (150s'\*(3+s)-150s\*(s)')/(3+s)^2$$
and s'=v so:
$$dv/dt = (150v\*(3+s)-150s\*v)/(3+s)^2$$
$$dv/dt = (450v+150s\*v-150s\*v)/(3+s)^2$$
$$dv/dt = (450v)/(3+s)^2$$
So yeah looks like you are right.
|
5,972 |
There are lots of small / mid sized software companies and there are lot of small / mid sized projects in this world.
The project management techniques we read in books are best suited for bigger projects. As we can not spend much time in PM related stuff that much, what technique best suits small / mid sized projects and takes less time for management. (Risk management part can be tolerated)
|
2012/06/15
|
[
"https://pm.stackexchange.com/questions/5972",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4116/"
] |
"The project management techniques we read in books [sic] are best suited for bigger projects." I think you made an erroneous conclusion here. The PM techniques are size and industry agnostic. What you seem to be missing is the tailoring of these techniques to fit the project and the environment in which you are working. What might change with size is the formality with which you would implement a PM capability, or perhaps the rigor. But the PM work is still performed. For a large project, I may develop a Project Management Plan and subordinate PMPs with over 200 pages. For a small project, the plan might be resident in my head. But in both cases, I planned my work. For a large project, I may deploy an ANSI compliant EVMS capability. For something small, I may use MS Project and an excel sheet to do the same thing.
The techniques and methods are scalable and tailorable. You need to do both always.
|
All successful projects comply with a relatively short list of principles/themes:
1. Does the project make sense from a business point of view? If no then the project should be terminated.
2. Are team roles and responsibilities clearly defined? If no then confusion will ensue.
3. Are plans in place that are feasible, achievable and realistic? If no then expect stakeholders to be annoyed and the team to be frustrated.
4. Are plans, risks and issues reviewed regularly in a controlled manner? If no then expect to be putting out fires because of issues you didn't see coming.
5. Is the team clear on what the end goal/product of the project has to look like? If no then expect scope creep and dissatisfaction with the end result.
6. Does the team apply lessons learned from this and other projects? If no then expect wasted effort as you reinvent the wheel.
7. Is there open, proactive communication between the stakeholders, PM and project team members? If no then expect differences in assumptions, delays, rework and added costs.
In terms of the details of tools, techniques, methods, processes, etc in order to implement these principles and themes see David's excellent answer.
|
5,972 |
There are lots of small / mid sized software companies and there are lot of small / mid sized projects in this world.
The project management techniques we read in books are best suited for bigger projects. As we can not spend much time in PM related stuff that much, what technique best suits small / mid sized projects and takes less time for management. (Risk management part can be tolerated)
|
2012/06/15
|
[
"https://pm.stackexchange.com/questions/5972",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4116/"
] |
"The project management techniques we read in books [sic] are best suited for bigger projects." I think you made an erroneous conclusion here. The PM techniques are size and industry agnostic. What you seem to be missing is the tailoring of these techniques to fit the project and the environment in which you are working. What might change with size is the formality with which you would implement a PM capability, or perhaps the rigor. But the PM work is still performed. For a large project, I may develop a Project Management Plan and subordinate PMPs with over 200 pages. For a small project, the plan might be resident in my head. But in both cases, I planned my work. For a large project, I may deploy an ANSI compliant EVMS capability. For something small, I may use MS Project and an excel sheet to do the same thing.
The techniques and methods are scalable and tailorable. You need to do both always.
|
Project management really boils down to a few simple concepts.
Decide what needs to be done (scope).
How much do we have to spend (cost).
When does it have to be done by (schedule).
Anything beyond this is defined by your individual project.
Estimating, risk management, change control; all of it is dependent on your situation. Short term project where you control most of the input? Probably not a lot of risk or risk management to worry about. History of similar projects? Estimating (both cost and task duration) is probably going to be straightforward. Requirements and/or scope fairly well defined, or limited number of stakeholders? Change control will be pretty easy.
It's as each of these factors increases in complexity that you have to start getting more in-depth in terms of processes. But at the base level, if you have a way to track tasks, cost, and schedule, that's all you need.
|
5,972 |
There are lots of small / mid sized software companies and there are lot of small / mid sized projects in this world.
The project management techniques we read in books are best suited for bigger projects. As we can not spend much time in PM related stuff that much, what technique best suits small / mid sized projects and takes less time for management. (Risk management part can be tolerated)
|
2012/06/15
|
[
"https://pm.stackexchange.com/questions/5972",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4116/"
] |
All successful projects comply with a relatively short list of principles/themes:
1. Does the project make sense from a business point of view? If no then the project should be terminated.
2. Are team roles and responsibilities clearly defined? If no then confusion will ensue.
3. Are plans in place that are feasible, achievable and realistic? If no then expect stakeholders to be annoyed and the team to be frustrated.
4. Are plans, risks and issues reviewed regularly in a controlled manner? If no then expect to be putting out fires because of issues you didn't see coming.
5. Is the team clear on what the end goal/product of the project has to look like? If no then expect scope creep and dissatisfaction with the end result.
6. Does the team apply lessons learned from this and other projects? If no then expect wasted effort as you reinvent the wheel.
7. Is there open, proactive communication between the stakeholders, PM and project team members? If no then expect differences in assumptions, delays, rework and added costs.
In terms of the details of tools, techniques, methods, processes, etc in order to implement these principles and themes see David's excellent answer.
|
Project management really boils down to a few simple concepts.
Decide what needs to be done (scope).
How much do we have to spend (cost).
When does it have to be done by (schedule).
Anything beyond this is defined by your individual project.
Estimating, risk management, change control; all of it is dependent on your situation. Short term project where you control most of the input? Probably not a lot of risk or risk management to worry about. History of similar projects? Estimating (both cost and task duration) is probably going to be straightforward. Requirements and/or scope fairly well defined, or limited number of stakeholders? Change control will be pretty easy.
It's as each of these factors increases in complexity that you have to start getting more in-depth in terms of processes. But at the base level, if you have a way to track tasks, cost, and schedule, that's all you need.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.