qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
10,262,114 | I need to script my app (not a game) and I have a problem, choosing a script lang for this.
Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used.
Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib).
Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app.
So, I'd like to know is there a scripting lang, which satisfies this conditions:
* unicode strings
* I can import C++ functions and then call them from
script
* Can be embedded to app (no dll's) without any problems
Reinventing the wheel is not a good idea, so I don't want to develop my own lang.
Or there is a way to write unicode strings in Lua's source? Like in C++ L"Unicode string" | 2012/04/21 | ['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/'] | There isn't really such a thing as a "unicode string". Strings are a sequence of bytes that can contain anything. Knowing the encoding of the data in the string matters, though.
I use Lua with [UTF-8 strings](http://en.wikipedia.org/wiki/UTF-8), which just works for all the operations I care about. I do not use any Unicode string library, though those are available for Lua ([ICU4Lua](http://luaforge.net/projects/icu-lua/), [slnunicode](http://luaforge.net/projects/sln/), etc.).
Some notes about using UTF-8 strings in Lua:
* String length (# operator) returns the string length in bytes, not characters or codepoints (non-ASCII characters may be sequences of multiple bytes).
* String splitting (e.g. string.sub) must not split up UTF-8 sequences.
* String matching works (string.find, string.match) fine with ASCII patterns.
* Substring searching (such as string.find in 'plain' mode) works with UTF-8 as the needle or the haystack.
Counting codepoints in UTF-8 is quite straightforward, if slightly less efficient than other encodings. For example in Lua:
```
function utf8_length(str)
return select(2, string.gsub(str, "[^\128-\193]", ""));
end
```
If you need more than this kind of thing, the unicode libraries I mentioned give you APIs for everything, including conversion between encodings.
Personally I prefer this straightforward approach to any of the languages that force a certain flavour of unicode on you (such as Javascript) or try and be clever by having multiple encodings built into the language (such as Python). In my experience they only cause headaches and performance bottlenecks.
In any case, I think every developer should have a good basic understanding of how unicode works, and the principle differences between different encodings so that they can make the best choice about how to handle unicode in their application.
For example if all your existing strings in your application are in a wide-char encoding, it would be much less convenient to use Lua as you would have to add a conversion to every string in and out of Lua. This is entirely possible, but if your app might be CPU-bound (as in a game) then it would be a negative point performance-wise. | Take look at [Jim Tcl](http://jim.tcl.tk). It's small, easily embeddable and extendable, supports UTF-8 strings, and it's pretty powerful |
43,979,563 | We have code that loads html to div with class content. We have div element with link class which has data-href and some other data-\* properties. The code looks like:
```
$(document).on('click', '.link', linkClick);
linkClick: function (event) {
event.stopPropagation();
$('.content').load($(this).data('href'), function (response, status) {
if (status == 'error') {
$('.content').html("Something went wrong. Please try again later");
}
});
}
```
I want to access $(this) inside this callback of load function to get values of all other data-\* properties of link clicked, how can i do that? | 2017/05/15 | ['https://Stackoverflow.com/questions/43979563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4930231/'] | Create a scoped reference to it before the load call:
```
function (event) {
event.stopPropagation();
var $that = $(this); // <- Like this
$('.content').load($(this).data('href'), function (response, status) {
// You can use $that here
if (status == 'error') {
$('.content').html("Something went wrong. Please try again later");
}
});
}
``` | ```
$(document).on('click', '.link', linkClick);
var href = $(this).data('href');
linkClick: function (event) {
event.stopPropagation();
$('.content').load(href, function (response, status) {
if (status == 'error') {
$('.content').html("Something went wrong. Please try again later");
}
});
}
``` |
43,979,563 | We have code that loads html to div with class content. We have div element with link class which has data-href and some other data-\* properties. The code looks like:
```
$(document).on('click', '.link', linkClick);
linkClick: function (event) {
event.stopPropagation();
$('.content').load($(this).data('href'), function (response, status) {
if (status == 'error') {
$('.content').html("Something went wrong. Please try again later");
}
});
}
```
I want to access $(this) inside this callback of load function to get values of all other data-\* properties of link clicked, how can i do that? | 2017/05/15 | ['https://Stackoverflow.com/questions/43979563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4930231/'] | Create a scoped reference to it before the load call:
```
function (event) {
event.stopPropagation();
var $that = $(this); // <- Like this
$('.content').load($(this).data('href'), function (response, status) {
// You can use $that here
if (status == 'error') {
$('.content').html("Something went wrong. Please try again later");
}
});
}
``` | You can use `event.target` to access clicked element. Most common way is to store it under *that* or *self* variable.
```
$(document).on('click', '.link', linkClick);
linkClick = function (event) {
event.stopPropagation();
var that = event.target;
$('.content').load($(that).data('href'), function (response, status) {
if (status == 'error') {
$('.content').html("Something went wrong. Please try again later");
}
});
}
``` |
14,465,060 | Ok so I have a map loaded with pins from a remote JSON feed which is loaded into the app. This all works fine.
Now from initial experimenting `regionDidChangeAnimated` gets called multiple times and so I moved my post request to a method that uses a drag map gesture recogniser which then performs a post request to get data from a JSON feed and reload my map pins after removing them. This also works perfectly.
Now the only issue I have left is if I select an annotation that is close to the edge of the screen the map moves slightly to accommodate the display of the annotation callout. The problem is `regionDidChangeAnimated` gets called when this happens however my post request doesn't as I call it using the gesture recogniser and so the map was not moved by user intervention but the OS. I don't want to move my Post request to the `regionDidChangeAnimated` as this gets called multiple times but I would like to know if there is a way to do a test if user caused map to move or it did it its-self to accommodate the callout as explained above. The `regionDidChangeAnimated` from the research I have looked at may get called more times than necessary so some guidance would be good on how to prevent that or detect user interaction vs OS moving the map. | 2013/01/22 | ['https://Stackoverflow.com/questions/14465060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/652028/'] | I have a similar problem: I want do distinguish if the displayed part of a map has been changed by program or by user interaction. Apparently, `MKMapView` objects do not tell me so, i.e. `regionDidChangeAnimated` is called in both cases without an indication why.
But since `MKMapView` is a subclass of `UIView`, and this one of `UIResponder`, one can implement the methods `touchesBegan:withEvent:` and `touchesEnded:withEvent:` to find out, if the map has been touched during the change of the displayed region.
If so, one can assume that the change in the displayed region was caused by user interaction. Of course you can be more specific if you investigate the set of touches and the event type of these methods more precisely. | I am such a plank sometimes writing problems can help. I simply removed the regionDidChangeAnimated as I have no need for it and the code that was present there I moved to my gesture which was to removeAnnotations before re-adding them doh! |
6,394,968 | Yet another template issue ! I'm trying to get a template method that will output an object if it has an overload for the operator <<.
I have pretty much everything working, and implemented an enable\_if in order to make g++ choose the intended specialization for each type of objects.
Thing is, with a non-overloaded object, it works quite fine. But with an overloaded one, both of my specialization are reasonable choices for g++, and instead of compiling it outputs me an ambiguous overload error.
Here's the code :
```
template<typename T>
static void Print(Stream& out, T& param, typename enable_if<CanPrint<T>::value>::type = 0)
{
out << param;
}
template<typename T>
static void Print(Stream& out, T& param)
{
out << "/!\\" << typeid(param).name() << " does not have any overload for <<.\n";
}
```
I understand why such a thing is ambiguous. Yet I can't think of a way to make it more obvious... how do I make the compiler understand that the second overload is to be chosen only when the first cannot be ? | 2011/06/18 | ['https://Stackoverflow.com/questions/6394968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/538377/'] | You'll get the ambiguity because in both cases you have a function that takes a stream followed by your type `T` as the first two arguments. This works though:
```
#include <iostream>
#include <boost/utility/enable_if.hpp>
#include <typeinfo>
template <class T>
struct CanPrint { enum { value = 0 }; };
template <>
struct CanPrint<int> { enum { value = 1 }; };
template<typename T>
typename boost::enable_if<CanPrint<T>, void>::type
Print(std::ostream& out, T& param)
{
out << param << std::endl;
}
template<typename T>
typename boost::disable_if<CanPrint<T>, void>::type
Print(std::ostream& out, T& param)
{
out << "/!\\" << typeid(param).name() << " does not have any overload for <<.\n";
}
int main()
{
int i = 1;
double d = 2;
Print(std::cout, i);
Print(std::cout, d);
}
``` | The ambiguity is because of the default parameter value.
Calling `Print(stream, whatever)` can be resolved to either the first version with the default third parameter or the second version with no third parameter.
Remove the default value, and the compiler will understand. Otherwise both of them can be chosen always. |
6,394,968 | Yet another template issue ! I'm trying to get a template method that will output an object if it has an overload for the operator <<.
I have pretty much everything working, and implemented an enable\_if in order to make g++ choose the intended specialization for each type of objects.
Thing is, with a non-overloaded object, it works quite fine. But with an overloaded one, both of my specialization are reasonable choices for g++, and instead of compiling it outputs me an ambiguous overload error.
Here's the code :
```
template<typename T>
static void Print(Stream& out, T& param, typename enable_if<CanPrint<T>::value>::type = 0)
{
out << param;
}
template<typename T>
static void Print(Stream& out, T& param)
{
out << "/!\\" << typeid(param).name() << " does not have any overload for <<.\n";
}
```
I understand why such a thing is ambiguous. Yet I can't think of a way to make it more obvious... how do I make the compiler understand that the second overload is to be chosen only when the first cannot be ? | 2011/06/18 | ['https://Stackoverflow.com/questions/6394968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/538377/'] | You'll get the ambiguity because in both cases you have a function that takes a stream followed by your type `T` as the first two arguments. This works though:
```
#include <iostream>
#include <boost/utility/enable_if.hpp>
#include <typeinfo>
template <class T>
struct CanPrint { enum { value = 0 }; };
template <>
struct CanPrint<int> { enum { value = 1 }; };
template<typename T>
typename boost::enable_if<CanPrint<T>, void>::type
Print(std::ostream& out, T& param)
{
out << param << std::endl;
}
template<typename T>
typename boost::disable_if<CanPrint<T>, void>::type
Print(std::ostream& out, T& param)
{
out << "/!\\" << typeid(param).name() << " does not have any overload for <<.\n";
}
int main()
{
int i = 1;
double d = 2;
Print(std::cout, i);
Print(std::cout, d);
}
``` | I believe this has nothing to do with templates. A free function overloaded in this fashion would give the same ambigious error.
check this simple code example, It is similar to what you are doing in your template example:
```
void doSomething(int i, int j, int k );
void doSomething(int i, int j, int k = 10);
void doSomething(int i, int j, int k)
{
}
void doSomething(int i, int j)
{
}
int main()
{
doSomething(10,20);
return 0;
}
```
The error is:
```
prog.cpp:18: error: call of overloaded ‘doSomething(int, int)’ is ambiguous
prog.cpp:5: note: candidates are: void doSomething(int, int, int)
prog.cpp:10: note: void doSomething(int, int)
```
***Clearly, You cannot overload the functions this way on just the basis of default arguments.*** |
53,596,009 | I am trying to remove the last `","` of a string however i am getting an error stating that
>
> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.
>
>
>
the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated.
the code I am using is as follows
```
for (int z = 0; z <= totalNumberOfCaves; z++)
{
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
connectionData.Add(int.Parse(connectionStack.Pop()));
}
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
using (StreamWriter sw = File.AppendText(fileName2))
{
string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);
sw.Write("{ " + writeData + " }," + Environment.NewLine);
}
connectionData.Clear();
}
``` | 2018/12/03 | ['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/'] | Appending `string` in a loop:
```
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
```
is *not* a good idea. Put `Join`:
```
writeUnEditedData = string.Join(",", connectionData);
```
Having this done, you don't have to remove anything:
```
using (StreamWriter sw = File.AppendText(fileName2))
{
// No Remove here
string writeData = writeUnEditedData;
...
``` | This usually means that the string is empty.
Try to put this guard code in:
```
string writeData = string.IsNullOrEmpty(writeUnEditedData)
? string.Empty
: writeUnEditedData.Remove(writeUnEditedData.Length - 1);
``` |
53,596,009 | I am trying to remove the last `","` of a string however i am getting an error stating that
>
> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.
>
>
>
the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated.
the code I am using is as follows
```
for (int z = 0; z <= totalNumberOfCaves; z++)
{
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
connectionData.Add(int.Parse(connectionStack.Pop()));
}
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
using (StreamWriter sw = File.AppendText(fileName2))
{
string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);
sw.Write("{ " + writeData + " }," + Environment.NewLine);
}
connectionData.Clear();
}
``` | 2018/12/03 | ['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/'] | Add a check to see if writeUnEditedData is not an empty string before you do the Remove. An empty string will results in a Remove(-1) which I would assume would throw an error that the StartIndex cannot be less then 0. | This usually means that the string is empty.
Try to put this guard code in:
```
string writeData = string.IsNullOrEmpty(writeUnEditedData)
? string.Empty
: writeUnEditedData.Remove(writeUnEditedData.Length - 1);
``` |
53,596,009 | I am trying to remove the last `","` of a string however i am getting an error stating that
>
> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.
>
>
>
the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated.
the code I am using is as follows
```
for (int z = 0; z <= totalNumberOfCaves; z++)
{
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
connectionData.Add(int.Parse(connectionStack.Pop()));
}
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
using (StreamWriter sw = File.AppendText(fileName2))
{
string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);
sw.Write("{ " + writeData + " }," + Environment.NewLine);
}
connectionData.Clear();
}
``` | 2018/12/03 | ['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/'] | Try `string.TrimEnd()`:
```
writeUnEditedData = writeUnEditedData.TrimEnd(',');
``` | This usually means that the string is empty.
Try to put this guard code in:
```
string writeData = string.IsNullOrEmpty(writeUnEditedData)
? string.Empty
: writeUnEditedData.Remove(writeUnEditedData.Length - 1);
``` |
53,596,009 | I am trying to remove the last `","` of a string however i am getting an error stating that
>
> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.
>
>
>
the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated.
the code I am using is as follows
```
for (int z = 0; z <= totalNumberOfCaves; z++)
{
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
connectionData.Add(int.Parse(connectionStack.Pop()));
}
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
using (StreamWriter sw = File.AppendText(fileName2))
{
string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);
sw.Write("{ " + writeData + " }," + Environment.NewLine);
}
connectionData.Clear();
}
``` | 2018/12/03 | ['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/'] | Appending `string` in a loop:
```
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
```
is *not* a good idea. Put `Join`:
```
writeUnEditedData = string.Join(",", connectionData);
```
Having this done, you don't have to remove anything:
```
using (StreamWriter sw = File.AppendText(fileName2))
{
// No Remove here
string writeData = writeUnEditedData;
...
``` | Add a check to see if writeUnEditedData is not an empty string before you do the Remove. An empty string will results in a Remove(-1) which I would assume would throw an error that the StartIndex cannot be less then 0. |
53,596,009 | I am trying to remove the last `","` of a string however i am getting an error stating that
>
> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.
>
>
>
the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated.
the code I am using is as follows
```
for (int z = 0; z <= totalNumberOfCaves; z++)
{
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
connectionData.Add(int.Parse(connectionStack.Pop()));
}
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
using (StreamWriter sw = File.AppendText(fileName2))
{
string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);
sw.Write("{ " + writeData + " }," + Environment.NewLine);
}
connectionData.Clear();
}
``` | 2018/12/03 | ['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/'] | Appending `string` in a loop:
```
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
```
is *not* a good idea. Put `Join`:
```
writeUnEditedData = string.Join(",", connectionData);
```
Having this done, you don't have to remove anything:
```
using (StreamWriter sw = File.AppendText(fileName2))
{
// No Remove here
string writeData = writeUnEditedData;
...
``` | Try `string.TrimEnd()`:
```
writeUnEditedData = writeUnEditedData.TrimEnd(',');
``` |
53,596,009 | I am trying to remove the last `","` of a string however i am getting an error stating that
>
> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.
>
>
>
the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated.
the code I am using is as follows
```
for (int z = 0; z <= totalNumberOfCaves; z++)
{
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
connectionData.Add(int.Parse(connectionStack.Pop()));
}
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
using (StreamWriter sw = File.AppendText(fileName2))
{
string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);
sw.Write("{ " + writeData + " }," + Environment.NewLine);
}
connectionData.Clear();
}
``` | 2018/12/03 | ['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/'] | Appending `string` in a loop:
```
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
```
is *not* a good idea. Put `Join`:
```
writeUnEditedData = string.Join(",", connectionData);
```
Having this done, you don't have to remove anything:
```
using (StreamWriter sw = File.AppendText(fileName2))
{
// No Remove here
string writeData = writeUnEditedData;
...
``` | You can improve on this pattern:
```
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
```
to avoid adding the comma in the first place:
```
string delimiter = "";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += $"{delimiter}{s}";
delimiter = ",";
}
```
or with a `StringBuilder`... though contrary to popular belief this only helps if the `connectionData` collection is kinda big:
```
string delimiter = "";
var writeUnEditedData = new StringBuilder();
foreach (int s in connectionData)
{
writeUnEditedData.Append(delimiter).Append(s);
delimiter = ",";
}
```
Even better still, stream the whole thing, to avoid needing all that extra memory and processing:
```
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
using (var sw = new StreamWriter(fileName2, true))
{
for (int z = 0; z <= totalNumberOfCaves; z++)
{
string delimiter = "";
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
sw.Write(delimiter);
sw.Write(connectionStack.Pop());
delimiter = ",";
}
sw.Write(Environment.NewLine);
}
}
``` |
53,596,009 | I am trying to remove the last `","` of a string however i am getting an error stating that
>
> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.
>
>
>
the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated.
the code I am using is as follows
```
for (int z = 0; z <= totalNumberOfCaves; z++)
{
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
connectionData.Add(int.Parse(connectionStack.Pop()));
}
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
using (StreamWriter sw = File.AppendText(fileName2))
{
string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);
sw.Write("{ " + writeData + " }," + Environment.NewLine);
}
connectionData.Clear();
}
``` | 2018/12/03 | ['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/'] | Try `string.TrimEnd()`:
```
writeUnEditedData = writeUnEditedData.TrimEnd(',');
``` | Add a check to see if writeUnEditedData is not an empty string before you do the Remove. An empty string will results in a Remove(-1) which I would assume would throw an error that the StartIndex cannot be less then 0. |
53,596,009 | I am trying to remove the last `","` of a string however i am getting an error stating that
>
> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.
>
>
>
the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated.
the code I am using is as follows
```
for (int z = 0; z <= totalNumberOfCaves; z++)
{
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
connectionData.Add(int.Parse(connectionStack.Pop()));
}
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
using (StreamWriter sw = File.AppendText(fileName2))
{
string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);
sw.Write("{ " + writeData + " }," + Environment.NewLine);
}
connectionData.Clear();
}
``` | 2018/12/03 | ['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/'] | Add a check to see if writeUnEditedData is not an empty string before you do the Remove. An empty string will results in a Remove(-1) which I would assume would throw an error that the StartIndex cannot be less then 0. | You can improve on this pattern:
```
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
```
to avoid adding the comma in the first place:
```
string delimiter = "";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += $"{delimiter}{s}";
delimiter = ",";
}
```
or with a `StringBuilder`... though contrary to popular belief this only helps if the `connectionData` collection is kinda big:
```
string delimiter = "";
var writeUnEditedData = new StringBuilder();
foreach (int s in connectionData)
{
writeUnEditedData.Append(delimiter).Append(s);
delimiter = ",";
}
```
Even better still, stream the whole thing, to avoid needing all that extra memory and processing:
```
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
using (var sw = new StreamWriter(fileName2, true))
{
for (int z = 0; z <= totalNumberOfCaves; z++)
{
string delimiter = "";
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
sw.Write(delimiter);
sw.Write(connectionStack.Pop());
delimiter = ",";
}
sw.Write(Environment.NewLine);
}
}
``` |
53,596,009 | I am trying to remove the last `","` of a string however i am getting an error stating that
>
> System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.
>
>
>
the string is written to the file fine but it breaks when running with the above error. I'm unsure as to why this is happening, any suggestions would be appreciated.
the code I am using is as follows
```
for (int z = 0; z <= totalNumberOfCaves; z++)
{
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
connectionData.Add(int.Parse(connectionStack.Pop()));
}
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
using (StreamWriter sw = File.AppendText(fileName2))
{
string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);
sw.Write("{ " + writeData + " }," + Environment.NewLine);
}
connectionData.Clear();
}
``` | 2018/12/03 | ['https://Stackoverflow.com/questions/53596009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424254/'] | Try `string.TrimEnd()`:
```
writeUnEditedData = writeUnEditedData.TrimEnd(',');
``` | You can improve on this pattern:
```
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
```
to avoid adding the comma in the first place:
```
string delimiter = "";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += $"{delimiter}{s}";
delimiter = ",";
}
```
or with a `StringBuilder`... though contrary to popular belief this only helps if the `connectionData` collection is kinda big:
```
string delimiter = "";
var writeUnEditedData = new StringBuilder();
foreach (int s in connectionData)
{
writeUnEditedData.Append(delimiter).Append(s);
delimiter = ",";
}
```
Even better still, stream the whole thing, to avoid needing all that extra memory and processing:
```
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
using (var sw = new StreamWriter(fileName2, true))
{
for (int z = 0; z <= totalNumberOfCaves; z++)
{
string delimiter = "";
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
sw.Write(delimiter);
sw.Write(connectionStack.Pop());
delimiter = ",";
}
sw.Write(Environment.NewLine);
}
}
``` |
49,182 | The question goes:
Expand $(1-2x)^{1/2}-(1-3x)^{2/3}$ as far as the 4th term.
Ans: $x + x^2/2 + 5x^3/6 + 41x^4/24$
How should I do it? | 2011/07/03 | ['https://math.stackexchange.com/questions/49182', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11103/'] | You can translate the inequality to $\frac{y^2 \cdot y'}{1+y^6} \leq x^{2011}$ and then integrate from $x\_00$ to $s$ with respect to $x$.
$$ \int\_{x\_0}^s \frac{y(x)^2 \cdot y(x)'}{1+y(x)^6} dx \leq \frac{s^{2012}}{2012}-\frac{x\_0^{2012}}{2012}$$
$$ \frac{1}{3} \arctan y^3(s) -\frac{1}{3}\arctan y^3(x\_0) \leq \frac{s^{2012}}{2012}-\frac{x\_0^{2012}}{2012}$$
In your case, take $x\_0=\frac{\pi}{4}$ | What you basically have is this:
\begin{align\*}
\frac{dy}{dx} & \leq \frac{x^{2011}\cdot (1+y^{6})}{y^{2}} \\ \Longrightarrow \int\frac{y^{2}}{1+y^{6}}\ dy &\leq \int x^{2011} \ dx
\end{align\*} |
52,074,170 | I've got two data frames: `zerowy_nazwa5`, `zatwierdzony_nazwa5`,
and working 2 lines:
```
setdiff(zatwierdzony_nazwa5, zerowy_nazwa5)
setdiff(zerowy_nazwa5, zatwierdzony_nazwa5)
```
how I implement this in PowerBi?
Thanks for help | 2018/08/29 | ['https://Stackoverflow.com/questions/52074170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2298197/'] | If you remove the `seleniumAddress` from your protractor `conf.js`, protractor will start the selenium automatically. Example:
**With the `seleniumAddress` on the `conf.js`:**
```
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: [ 'spec.js' ]
};
```
**Removing the `seleniumAddress` on the `conf.js`:**
```
exports.config = {
specs: [ 'spec.js' ]
};
```
Now, using the `protractor conf.js`, protractor will start the selenium server automatically as you need. | You can archive your goal with npm packages: [concurrently](https://www.npmjs.com/package/concurrently) and [delay-cli](https://www.npmjs.com/package/delay-cli).
Add them as dependencies.
```
// package.json
"scripts": [
"wstart": "webdriver-manager update && webdriver-manager start",
"test": "concurrently --kill-others \"npm run wstart\" \"delay 10 && protractor conf.js\""
]
```
execute `npm run test` |
12,803,508 | I have a program that recevice message in udp in visual studio.
sometime I miss a message.I want to use select to see udp buffer used size if udp rec buffer is full.
How I can use select for this purpose?
where can I see a example? | 2012/10/09 | ['https://Stackoverflow.com/questions/12803508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598470/'] | Post-fact discovery that your receive buffer is full will not do you any good - packets have already been dropped. Even more - you need to set your buffer sizes before `connect()` or `bind()`, they will not change after that.
What you should do is pre-set socket receive buffer to some large value that would accommodate your traffic spikes, and try to process your network input faster. That usually means doing `select()` on non-blocking sockets (or even better - some advanced API like Linux `epoll(7)` in edge-triggered mode), and draining socket input until you get `EWOULDBLOCK`.
### Edit 0:
You cannot discover that you missed a UDP packet by using `select()` or any other socket API. This has to be done in the **application-level protocol**, i.e. one layer up from the transport. Common practice is including sequence numbers in application message header. | I think one of the main properties of UDP (as opposed to TCP) is that you will sometimes lose messages. You have to design your protocol to account for that. I'm not an expert in UDP, but I don't understand how seeing the size of the buffer will help you, and I don't understand why you want to use `select` to do it. |
12,803,508 | I have a program that recevice message in udp in visual studio.
sometime I miss a message.I want to use select to see udp buffer used size if udp rec buffer is full.
How I can use select for this purpose?
where can I see a example? | 2012/10/09 | ['https://Stackoverflow.com/questions/12803508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598470/'] | Post-fact discovery that your receive buffer is full will not do you any good - packets have already been dropped. Even more - you need to set your buffer sizes before `connect()` or `bind()`, they will not change after that.
What you should do is pre-set socket receive buffer to some large value that would accommodate your traffic spikes, and try to process your network input faster. That usually means doing `select()` on non-blocking sockets (or even better - some advanced API like Linux `epoll(7)` in edge-triggered mode), and draining socket input until you get `EWOULDBLOCK`.
### Edit 0:
You cannot discover that you missed a UDP packet by using `select()` or any other socket API. This has to be done in the **application-level protocol**, i.e. one layer up from the transport. Common practice is including sequence numbers in application message header. | You can use [`getsockopt`](http://linux.die.net/man/3/getsockopt) to get socket options, including receive buffer size. Use [`setsockopt`](http://linux.die.net/man/3/setsockopt) to set the size.
Example of getting the size:
```
int size;
getsockopt(socket_fd, SOL_SOCKET, SO_RCVBUF, &size);
std::cout << "Buffer size is currently " << size << " bytes\n";
``` |
1,569,238 | I am having performance problem when truing to fill typed list. Below is my simplified code:
```
public static List<Product> GetProducts()
{
List<Product> products = new List<Product>();
using (DbQuery query = new DbQuery()) //this is database access class
{
query.CommandText = "SELECT ProdID, ProdName,Price FROM SomeTable " ;+
using (IDataReader rdr = query.ExecuteReader())
{
while (rdr.Read())
{
Product prd = new Product();
prd.ProdID = DbQuery.ReadInt ( rdr, "ProdID", -1 );
prd.ProdName = DbQuery.ReadString(rdr, "ProdName", "");
prd.Price = DbQuery.ReadDouble(rdr, "Price", 0);
products.Add(prd);
}
}
}
}
```
I also have simple struct Product (ProdID, ProdName,Price).
my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help.
Thanks,
Gerda | 2009/10/14 | ['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/'] | Have you tried to put an index on the fields you're filtering on? This will definitely speed up your queries versus not having indices. | I would be surprised if that is your bottleneck. I would try making a little test app that has a mock database connection.
You can usually do a little bit better if you can pre-size the list. If there is a reasonable minimum size for the query, or if you have some other way of knowing (or reasonably guessing) a good initial size you might get a tiny boost. |
1,569,238 | I am having performance problem when truing to fill typed list. Below is my simplified code:
```
public static List<Product> GetProducts()
{
List<Product> products = new List<Product>();
using (DbQuery query = new DbQuery()) //this is database access class
{
query.CommandText = "SELECT ProdID, ProdName,Price FROM SomeTable " ;+
using (IDataReader rdr = query.ExecuteReader())
{
while (rdr.Read())
{
Product prd = new Product();
prd.ProdID = DbQuery.ReadInt ( rdr, "ProdID", -1 );
prd.ProdName = DbQuery.ReadString(rdr, "ProdName", "");
prd.Price = DbQuery.ReadDouble(rdr, "Price", 0);
products.Add(prd);
}
}
}
}
```
I also have simple struct Product (ProdID, ProdName,Price).
my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help.
Thanks,
Gerda | 2009/10/14 | ['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/'] | Have you tried to put an index on the fields you're filtering on? This will definitely speed up your queries versus not having indices. | Just from the sounds of it, this has to be a database performance or latency issue (if connecting remotely.) |
1,569,238 | I am having performance problem when truing to fill typed list. Below is my simplified code:
```
public static List<Product> GetProducts()
{
List<Product> products = new List<Product>();
using (DbQuery query = new DbQuery()) //this is database access class
{
query.CommandText = "SELECT ProdID, ProdName,Price FROM SomeTable " ;+
using (IDataReader rdr = query.ExecuteReader())
{
while (rdr.Read())
{
Product prd = new Product();
prd.ProdID = DbQuery.ReadInt ( rdr, "ProdID", -1 );
prd.ProdName = DbQuery.ReadString(rdr, "ProdName", "");
prd.Price = DbQuery.ReadDouble(rdr, "Price", 0);
products.Add(prd);
}
}
}
}
```
I also have simple struct Product (ProdID, ProdName,Price).
my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help.
Thanks,
Gerda | 2009/10/14 | ['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/'] | List insertion is very fast. Something else must be going on here. Try timing it with and without `products.Add(prd)` commented out. I suspect you'll find they're almost identical.
Here's how I'd solve this: comment out one line at a time until you see a big jump in performance-- then you'll have found your culprit.
Another thing to watch out for: database performance is not static. For example, a query which takes 4 seconds to execute the first time might only take 100 msecs to execute the second time, because all the data is cached into RAM so no physical I/O needs to be done the second time. And the very first query to a database will be slow as SQL spins up lots of things. My suggestion: always start with a warm cache, meaning run the code once and then run it again, and only consider the second timing real. Even better, run the code 10 times, then time it 10 times, and throw out the first 10 and average the second. | I would be surprised if that is your bottleneck. I would try making a little test app that has a mock database connection.
You can usually do a little bit better if you can pre-size the list. If there is a reasonable minimum size for the query, or if you have some other way of knowing (or reasonably guessing) a good initial size you might get a tiny boost. |
1,569,238 | I am having performance problem when truing to fill typed list. Below is my simplified code:
```
public static List<Product> GetProducts()
{
List<Product> products = new List<Product>();
using (DbQuery query = new DbQuery()) //this is database access class
{
query.CommandText = "SELECT ProdID, ProdName,Price FROM SomeTable " ;+
using (IDataReader rdr = query.ExecuteReader())
{
while (rdr.Read())
{
Product prd = new Product();
prd.ProdID = DbQuery.ReadInt ( rdr, "ProdID", -1 );
prd.ProdName = DbQuery.ReadString(rdr, "ProdName", "");
prd.Price = DbQuery.ReadDouble(rdr, "Price", 0);
products.Add(prd);
}
}
}
}
```
I also have simple struct Product (ProdID, ProdName,Price).
my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help.
Thanks,
Gerda | 2009/10/14 | ['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/'] | List insertion is very fast. Something else must be going on here. Try timing it with and without `products.Add(prd)` commented out. I suspect you'll find they're almost identical.
Here's how I'd solve this: comment out one line at a time until you see a big jump in performance-- then you'll have found your culprit.
Another thing to watch out for: database performance is not static. For example, a query which takes 4 seconds to execute the first time might only take 100 msecs to execute the second time, because all the data is cached into RAM so no physical I/O needs to be done the second time. And the very first query to a database will be slow as SQL spins up lots of things. My suggestion: always start with a warm cache, meaning run the code once and then run it again, and only consider the second timing real. Even better, run the code 10 times, then time it 10 times, and throw out the first 10 and average the second. | Just from the sounds of it, this has to be a database performance or latency issue (if connecting remotely.) |
1,569,238 | I am having performance problem when truing to fill typed list. Below is my simplified code:
```
public static List<Product> GetProducts()
{
List<Product> products = new List<Product>();
using (DbQuery query = new DbQuery()) //this is database access class
{
query.CommandText = "SELECT ProdID, ProdName,Price FROM SomeTable " ;+
using (IDataReader rdr = query.ExecuteReader())
{
while (rdr.Read())
{
Product prd = new Product();
prd.ProdID = DbQuery.ReadInt ( rdr, "ProdID", -1 );
prd.ProdName = DbQuery.ReadString(rdr, "ProdName", "");
prd.Price = DbQuery.ReadDouble(rdr, "Price", 0);
products.Add(prd);
}
}
}
}
```
I also have simple struct Product (ProdID, ProdName,Price).
my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help.
Thanks,
Gerda | 2009/10/14 | ['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/'] | As Justin recommends, I personally would start commenting out sections of code until I found what was causing the bottleneck. For example, I might start by making the routine only run the database-centric code:
```
public static List<Product> GetProducts()
{
List<Product> products = new List<Product>();
using (DbQuery query = new DbQuery())
{
query.CommandText = "SELECT ProdID, ProdName,Price FROM SomeTable ";
using (IDataReader rdr = query.ExecuteReader())
{
while (rdr.Read())
{
//Product prd = new Product();
//prd.ProdID = DbQuery.ReadInt(rdr, "ProdID", -1);
//prd.ProdName = DbQuery.ReadString(rdr, "ProdName", "");
//prd.Price = DbQuery.ReadDouble(rdr, "Price", 0);
//products.Add(prd);
}
}
}
return products;
}
```
By commenting out the section which creates the Product objects and adds them to the list, I can see how fast the database related code runs. If that runs quicker then 4 seconds then I know that it's something to do with the Product object creation and/or the calls to DBQuery which are taking a long time to complete.
It's trial and error, but since this routine if very simple, it should not take long to do this type of analysis. | I would be surprised if that is your bottleneck. I would try making a little test app that has a mock database connection.
You can usually do a little bit better if you can pre-size the list. If there is a reasonable minimum size for the query, or if you have some other way of knowing (or reasonably guessing) a good initial size you might get a tiny boost. |
1,569,238 | I am having performance problem when truing to fill typed list. Below is my simplified code:
```
public static List<Product> GetProducts()
{
List<Product> products = new List<Product>();
using (DbQuery query = new DbQuery()) //this is database access class
{
query.CommandText = "SELECT ProdID, ProdName,Price FROM SomeTable " ;+
using (IDataReader rdr = query.ExecuteReader())
{
while (rdr.Read())
{
Product prd = new Product();
prd.ProdID = DbQuery.ReadInt ( rdr, "ProdID", -1 );
prd.ProdName = DbQuery.ReadString(rdr, "ProdName", "");
prd.Price = DbQuery.ReadDouble(rdr, "Price", 0);
products.Add(prd);
}
}
}
}
```
I also have simple struct Product (ProdID, ProdName,Price).
my problem is that it takes 4 seconds to execute GetProducts(). The query returns about 600 records and it takes miliseconds to return result, so I am perrty sure that filling up products collection takes all this time. Am I doing something inefficient here? Please, help.
Thanks,
Gerda | 2009/10/14 | ['https://Stackoverflow.com/questions/1569238', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190204/'] | As Justin recommends, I personally would start commenting out sections of code until I found what was causing the bottleneck. For example, I might start by making the routine only run the database-centric code:
```
public static List<Product> GetProducts()
{
List<Product> products = new List<Product>();
using (DbQuery query = new DbQuery())
{
query.CommandText = "SELECT ProdID, ProdName,Price FROM SomeTable ";
using (IDataReader rdr = query.ExecuteReader())
{
while (rdr.Read())
{
//Product prd = new Product();
//prd.ProdID = DbQuery.ReadInt(rdr, "ProdID", -1);
//prd.ProdName = DbQuery.ReadString(rdr, "ProdName", "");
//prd.Price = DbQuery.ReadDouble(rdr, "Price", 0);
//products.Add(prd);
}
}
}
return products;
}
```
By commenting out the section which creates the Product objects and adds them to the list, I can see how fast the database related code runs. If that runs quicker then 4 seconds then I know that it's something to do with the Product object creation and/or the calls to DBQuery which are taking a long time to complete.
It's trial and error, but since this routine if very simple, it should not take long to do this type of analysis. | Just from the sounds of it, this has to be a database performance or latency issue (if connecting remotely.) |
9,866,679 | I came across `html>body` in one of the stylesheets and wanted to know as to why it is used.
```
html>body {
font-size: 16px;
font-size: 78.75%;
}
``` | 2012/03/26 | ['https://Stackoverflow.com/questions/9866679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184100/'] | It's called a [Child Selector](http://www.w3.org/TR/CSS2/selector.html#child-selectors).
The reason it's being used is likely because it's a hack to exclude IE6 and below. Those browsers don't understand the `>` selector.
**[More Information](http://en.wikipedia.org/wiki/CSS_filter#Child_selector_hack)** | Child selector, more info here: <http://www.w3.org/TR/CSS2/selector.html#child-selectors>
So in your code it would be any body child of html |
9,866,679 | I came across `html>body` in one of the stylesheets and wanted to know as to why it is used.
```
html>body {
font-size: 16px;
font-size: 78.75%;
}
``` | 2012/03/26 | ['https://Stackoverflow.com/questions/9866679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184100/'] | It's called a [Child Selector](http://www.w3.org/TR/CSS2/selector.html#child-selectors).
The reason it's being used is likely because it's a hack to exclude IE6 and below. Those browsers don't understand the `>` selector.
**[More Information](http://en.wikipedia.org/wiki/CSS_filter#Child_selector_hack)** | '> symbol indicates `child of`
Above code means
The style applies to all the tag body which is a child of html
```
#sample>div
```
above applies to all divs which are children of the element with id sample |
9,866,679 | I came across `html>body` in one of the stylesheets and wanted to know as to why it is used.
```
html>body {
font-size: 16px;
font-size: 78.75%;
}
``` | 2012/03/26 | ['https://Stackoverflow.com/questions/9866679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184100/'] | It's called a [Child Selector](http://www.w3.org/TR/CSS2/selector.html#child-selectors).
The reason it's being used is likely because it's a hack to exclude IE6 and below. Those browsers don't understand the `>` selector.
**[More Information](http://en.wikipedia.org/wiki/CSS_filter#Child_selector_hack)** | the '>' means that it is referencing on child elements of the parent (in this case 'html')
so for example I could have an arrangement of divs that look like so
```
<div id="outermost">
<div class="inner">
<div class="inner">
</div>
</div>
</div>
```
and i wrote some css like so
```
#outermost>.inner { background-color: #CCC; }
```
it would only apply the rules to the first level '#inner'
Obviously there is only one body tag however it used to be a hack to exclude ie6 and below to write different rules for ie7+ ;) |
9,866,679 | I came across `html>body` in one of the stylesheets and wanted to know as to why it is used.
```
html>body {
font-size: 16px;
font-size: 78.75%;
}
``` | 2012/03/26 | ['https://Stackoverflow.com/questions/9866679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184100/'] | the '>' means that it is referencing on child elements of the parent (in this case 'html')
so for example I could have an arrangement of divs that look like so
```
<div id="outermost">
<div class="inner">
<div class="inner">
</div>
</div>
</div>
```
and i wrote some css like so
```
#outermost>.inner { background-color: #CCC; }
```
it would only apply the rules to the first level '#inner'
Obviously there is only one body tag however it used to be a hack to exclude ie6 and below to write different rules for ie7+ ;) | Child selector, more info here: <http://www.w3.org/TR/CSS2/selector.html#child-selectors>
So in your code it would be any body child of html |
9,866,679 | I came across `html>body` in one of the stylesheets and wanted to know as to why it is used.
```
html>body {
font-size: 16px;
font-size: 78.75%;
}
``` | 2012/03/26 | ['https://Stackoverflow.com/questions/9866679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1184100/'] | the '>' means that it is referencing on child elements of the parent (in this case 'html')
so for example I could have an arrangement of divs that look like so
```
<div id="outermost">
<div class="inner">
<div class="inner">
</div>
</div>
</div>
```
and i wrote some css like so
```
#outermost>.inner { background-color: #CCC; }
```
it would only apply the rules to the first level '#inner'
Obviously there is only one body tag however it used to be a hack to exclude ie6 and below to write different rules for ie7+ ;) | '> symbol indicates `child of`
Above code means
The style applies to all the tag body which is a child of html
```
#sample>div
```
above applies to all divs which are children of the element with id sample |
124,342 | When a singer asks to tune a song a half step down from Gbm would that be Fminor or Gb? | 2022/08/12 | ['https://music.stackexchange.com/questions/124342', 'https://music.stackexchange.com', 'https://music.stackexchange.com/users/88138/'] | It means F minor.
Singers frequently change the key of (transpose) a song in order to best fit their vocal range.
Changing to Gb major would be a change of mode, which would entirely change the character of the music.
The below video is timed to a performance of the Beatles's "Here Comes the Sun", first in major, then shifted to minor. | I'd be surprised if the original key was G♭m - F♯m is far more the common way to call it. But you wouldn't change the key of any song from minor to major - or vice versa, just to suit someone's range. In fact, merely dropping a semitone is unusual. if it's that awkward to sing in G♭m, Em could be even better! (And probably easier to play...)
So, basic premise - if the original is in minor, change key to another minor, if major, new key needs to be also major. |
108,713 | I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
I'm new in this community, so I'm not sure if this is the right place to ask this question. | 2019/06/05 | ['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/'] | If you read the other answers, it should be apparent that the qualities you seek such as (a) better portraits and (b) the desire to have a blurred background ... aren't really one thing, but a combination of many factors.
There are some nuances but the short answer is ... portraits do not require advanced DSLRs (so entry level is fine) but... there are nuances to consider. I discuss these below.
The advantage of the DSLR isn't that the camera is 'better' per se, but rather that it allows interchangeable accessories (such as lenses, lighting, etc.) to create the right conditions in order to capture the results you want.
Much of this is based on the knowledge & skill of the photographer. Buying a more expensive musical instrument doesn't make a person a better musician... learning music and practicing makes a person a better musician. The camera can't propel you forward ... but a camera with limited capabilities might hold you back.
If I buy a better guitar than anything Peter Frampton uses ... I will *still* not be a better musician than Peter Frampton (nowhere even close). His knowledge and skill in that area of music is legendary and mine ... not so much.
**Better portraits**
We're getting into a subjective area, but flip through portraits you like and try to notice why you like them. Inspect the posing of the model, the composition of the frame and how foreground or background elements are used. Check out the lighting (*especially* check out the lighting).
My personal thoughts are that:
1. Photographer knowledge & experience (skill) is probably the most important factor to influence the results. There's no getting around the notion that there will be a lot of learning and a lot of practice. The camera itself isn't a substitute for those considerations ... no matter how much a person pays for the equipment. Compositional skills, posing skills, exposure skills, lighting skills, etc. all require knowledge & experience ... regardless of how good the gear is. The camera will offer an 'automatic' mode and while that mode will capture adequate shots, they probably will not be the artistic results you were hoping to get.
2. Lighting is next. I put this ahead of lens selection. A key idea here is that you cannot have good light ... without good shadow. An image of a full moon never looks as good as an image of a 1st Quarter moon. The difference is that one has 'flat' lighting and the other has the light coming from the side. When the light comes from the side, any 3D textures produce shadows. It's the interplay of those highlights and shadows that causes the subject to appear three-dimensional with loads of textures. This isn't just true of the moon... it's true of anything you photograph. Shadows queue the eye (and the human brain) and provide information about the textures and contours. Another consideration is whether the transition from highlight to shadow is an abrupt line ... or a gentle transition. Is it 'hard' lighting or 'soft' lighting (hard & soft refer to those transitions... a hard-edge has an abrupt transition with a sharp line separating light & shadow. A soft-edge is a very gentle transition from one to the other.) Lighting can create moods... you can use light to convey emotions such as joy or peace or despair. In my opinion this is one of the most powerful tools a photographer has (and yet so very many photographers seem to be obsessed with just their camera.) The best lighting is the lighting that does what you want ... and this often means you may need ways to control the lighting (which is why advanced photographers own auxiliary lighting and lighting modifiers).
3. Lens selection is next on my personal list of priorities. A helpful way to think of lenses isn't so much by focal length ... but by *angle-of-view*. A lens can be *wide*, *normal*, or *narrow*. A normal angle of view is one that matches roughly what a human eye would perceive. A technical point to keep in mind (it's not hard to remember this) is that a lens will provide a *normal* angle of view if the focal length of the lens is the same as the diagonal measure of the sensor. For most DSLRs with an APS-C size sensor this is roughly 28mm (that's not exact). A 28mm lens on such a camera will offer a normal angle of view. If you use a shorter focal length (e.g. 20mm) you will have a moderately wide angle of view. If you use a much lower focal length (e.g. 10mm) you will have a very wide angle of view. A 50mm focal length will offer a moderately narrow angle of view. A 200mm lens will offer a very narrow angle of view. These angles-of-view create some interesting and useful side-effects. Wide angle lenses do not just shoot wider scenes... they also *stretch* the sense of the depth in a scene (want to make a room look larger or make a subject appear farther away... use a wider lens). The opposite happens with a narrow lens. Narrow lenses (long focal lengths) produce *compression*. Far away subjects don't look so far. The sense of depth in a scene is 'compressed'.
4. The camera body is in last place on my list. It isn't that it is not important... it is important. But it wields less influence than the three factors above it. There are many instances where the physical sensor used in an entry level body is actually the *same* sensor used in a higher-end body. So what's the difference? Usually the difference is other features such as the number and type of focus points used ... or how quickly the camera can rapidly burst shots ... or the size of the camera's internal memory buffer. If you're doing a lot of action photography, there are features a camera might have that optimizes it toward action photography. But if you're shooting a landscape on a tripod using a remote shutter release and you have all the time in the world to get that shot... having loads of auto-focus points and high-speed burst isn't really going to help you. On the other hand if you are a sports/action photographer ... the lack of those features might mean you get fewer 'keepers' as the camera struggles to have the focus system and shutter keep up with the action.
The above is my priority list. A different photographer might give you a different order. I don't get to hung up on brand names or equipment. Loads of companies make fantastic cameras. It is possible to select a camera that may not be ideal for a particular type of photography ... and it is possible to select a lens that isn't ideal.
**Blurred Backgrounds**
Ultimately the ability to have one thing in sharp focus and another thing far out of focus (to make that thing blurry) is based on an idea called the **Depth of Field** (you'll often see this abbreviated as DoF).
If my subject is 10 feet away and I point the lens at the subject, we'll need to focus the lens on the subject. In reality we are adjusting the focus for a 10 foot distance. If something is not *precisely* 10' away... suppose something is 9'11" or 10'1" -- will being fractionally nearer or farther make a difference? Probably not when you consider the ratios... 10' = 10 x 12 inches or 120 inches away. So a 1" difference works out to a difference of just 0.8% (not even 1%). But what if a lens was focused to 10' and something else was 100' away... now the difference is more significant.
DoF is the idea that there's a range of distances at which you will judge the subject to be ... more or less ... acceptably focused (I didn't say perfectly focused). How you judge this will also be affected by how closely you inspect the image.
There are a few factors that ... when added together ... affect the overall depth-of-field.
This include things such as:
* Focal length of the lens where short focal length lenses tend to produce much broader depth of field and very long focal length lenses tend to produce much narrower depth of field.
* Focal ratio of the lens. The focal ratio considers the size of the physical opening in the lens through which light may pass. But instead of being a simple diameter ... it is expressed as a *ratio* of the lens' overall focal length divided by that physical diameter. If a lens with a 100mm focal length has an aperture opening 50mm across than that lens has a focal ratio of 2 ... since 100 ÷ 50 = 2. That would be expressed as f/2 (the 'f/' is short-hand for *focal ratio*). If we adjust the opening so that it has a diameter of 25mm then the focal ratio becomes f/4 because 100 ÷ 25 = 4. One take-away is notice that the lower-focal ratio example (f/2) had the larger physical diameter opening in the lens (50mm opening on a 100mm lens). If the lens had a very tiny opening (a pin-hole) then all the light has to pass through just that one very tiny point. Such a lens would have and extremely large depth-of-field. If you use a lens with a very large opening, the photons have a choice of many different paths through the lens. This reduces the overall depth-of-field.
* Subject distance is another factor. If a subject is very far away a lens needs to be focused to near the *infinity* point. Of course everything in the background is even farther ... so *also* focused to near the infinity point. Since there isn't much difference ... the background seems to be more or less just as well focused as the subject. Foreground subjects might appear blurry. But if the subject were close to you... and the background was quite far away, the background will probably appear to be more blurred. As a photographer I *rarely* place a subject against a wall for a portrait shoot... unless that wall is *extremely* interesting and will add to the overall value of the shot. Better to pull them away from the wall so that the wall can fall begins to get farther outside the depth-of-field.
All of these factors have to be combined... each one simply influences the overall depth of field. None of them completely rule the depth of field.
A camera with a long focal length lens using a very low focal ratio and a subject placed somewhat close to the camera with a background placed much farther away ... will result in strong background blur. Doing the opposite ... short-focal length lens, high focal ratio, and a more distant subject ... will produce very large DoF and you won't notice much blur in the background.
**Other Considerations for Blur**
There is a term used in photography called 'bokeh'. This term refers to the *quality* of the blur... not the *strength* of the blur.
Once upon a time, Canon produce a particular 50mm f/1.8 lens that had merely 5 aperture blades inside the lens and these were not well-rounded blades. This means the opening in the lens was a pentagon instead of a circle. As points of light blur, they blur with the geometry of the aperture opening. This means that as pentagons overlap pentagons it created a rather strange effect ... the quality of the blur was not very smooth. It was somewhat jagged ... jittery ... almost nervous looking. It did not evoke emotions of peace and beauty that will add to the effect most photographers were going for.
Canon replaced that lens with a lens that has identical optics (not similar... identical!) But that newer lens has 7 aperture blades instead of 5 and the blades on the newer lens do a bit better w.r.t. to being more well-rounded. This produces a more circular opening and the results in images produce a much better quality in the background blur (the blur appears more smooth).
The lenses are optically identical and they have identical focal ratios. But one lens produce a poor quality blur. The other produces a higher quality blur.
*This* is what the term 'bokeh' is meant to convey... the quality (over quantity).
This means that even if you combine the conditions such as focal length, focal ratio, and subject distance (relative to background distance) to try to maximize the background blur... it is possible to have a blur ... but a blur that you may not enjoy.
**Summary**
* An entry-level DSLR body is fine for portrait work. Portraits usually do not require advanced camera features.
* You'll need to pair it with an appropriate lens to achieve the results you want (blurred background portraits). A DSLR is often packaged with a 'kit' lens and this is usually a standard zoom offering a bit of wide angle and a bit of narrow angle but not a particularly low focal ratio (manufacturers try to pair the camera body with an affordable lens to put them with financial reach of more consumers). Using a 50mm lens would be better ... using an 85mm lens would be even better still.
* Your skill will be very important ... the equipment alone wont be enough. If you use the 'automatic' setting mode it will tend to go for 'safe' exposures ... not artistic exposures. Skill is needed to learn which settings produce the results you want.
* Lighting will also be an important factor. Good lighting isn't just natural lighting... it's lighting that does what you want. Photographers with deeper pockets invest in equipment (although a lot of lighting gear can be surprisingly cheap when you compare lighting costs to lens costs and other equipment costs) ... but they invest in this gear specifically because it lets them control the lighting. | I had an entry level for years (Canon 550D) and I have taken really good shots on it. Although lenses are important, I would like to enumerate a few other factors (sorted from the most important to the less important) that will influence on your results
1. **The subject**: This is by far the most important of all. Your cellphone can make a much better picture than your camera if you point it to the right subject. I have wasted a lot of time taking pictures of not so interesting subjects and thinking about saving money to buy a better camera until I finally discovered that it is a much better investment to spend that money on short travels to parks with view-sights and animals, or neighborhoods with cute streets and interesting people, etc etc.
2. **Light and weather conditions**: Remember the park I said you should go? If you really want good results, you should check the forecast, go really early in the morning or maybe after rains, it depends on what you want, but this the right conditions will add the right "life" to your photos
3. **The lenses**: You may be in the right place but maybe the right light you want is something that just doesn't occur naturally. Or maybe you want to be much closer to some animal, or to take a much wider picture. For this, you have the lenses. An f/4 outside in a clear day can make really good pictures, but an f/2.8 will let you work under more severe light conditions. However, an f/4 is much lighter than an f/2.8 and this may allow you to make longer journeys. An 70-200mm will make you fell amazed on how much close you can get to some subjects and a 16mm will let you make excellent wide photos. And good lens are forever. They will always do their job and you can sell them well if in good condition. They are an instant change in possibilities: you change the lens, everything changes
4. **How you use your camera and lenses**: You have to know your equipment. To know where are the button, the limitations, which possibilities do you have and so on. After upgrading for a better camera, you will feel for a while that you were more capable with your old camera until you get to know your new one
5. **The camera**: Finally, the camera. In my experience, a better camera gives you a better ISO, better shutter, more durable components, more functionalities, more photos per second, etc. Not necessarily a better sensor, for example. The better camera will make it easier for you to go further, but if you don't have what I told you above, there will be not a lot of difference in your results.
Best thing I can recommend in order to achieve maturity as a photographer so you finally feel that your entry level camera is limiting you is to go outside and take pictures. Just go out for it every weekend and you will start to understand the places, the lights, your equipment. After that, the day will come where you will know exactly why you need a better camera and what camera you need. And you will probably keep the entry level, because they are good anyway. |
108,713 | I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
I'm new in this community, so I'm not sure if this is the right place to ask this question. | 2019/06/05 | ['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/'] | **It's not the camera, it's the lens.**
If you want a cheap and good option for shooting portrait pictures, you should definitely purchase in addition to a DSLR, a 50mm f/1.8 "nifty fifty" lens. Do expect to spend $100-$200 for the lens.
50mm is about optimal for portraits, because the relatively long 50mm focal length on crop sensor cameras is long enough to obtain blurred background while being short enough that the distance to the subject need not be excessive.
At 50mm, the kit zoom probably has f/5.6 aperture. A nifty fifty has f/1.8 aperture, which is more than 3x the difference. Three times the background blur with a nifty fifty.
Even an expensive (and heavy and large!) zoom (17-55mm f/2.8, $700-$1000) cannot match a nifty fifty (50mm f/1.8, $100-$200).
Also, the f/1.8 aperture is useful in low light no flash situations: the f/1.8 collects 9.68x the amount of light than the f/5.6 (@50mm) zoom. | A DX sensor has a crop factor of 2/3. You are presumably talking about the 18-55mm kit lens. For portrait work, you'd likely use it at its long end, giving you about 83mm equivalent focal length with an aperture of 1:5.6. That will give you the same depth of field as an 1:8 aperture setting on a 35mm film camera with the same kind of effective focal length which is quite discernible but not terribly strong. You'll want to arrange your scene appropriately so that the background is indeed some distance away.
The computational blurring on a smartphone aims to emulate the visuals of quite smaller depth of field, namely larger sensors/aperture. If your viewing device ends up being a smartphone, you'll not likely be able to appreciate the much more natural action of optical object isolation (but due to camera and lens parameters, more subtle) over computational approaches, particularly since the small display scale increases the perceived depth of field.
If you are going for print, things will look different already, however.
Is it worth the money? It depends on your purpose. If you don't intend to throw further money at the problem of doing portraits (namely buying a suitable prime lens or a less basic zoom lens), you'd likely be better off with a 15-year old Sony DSC-R1. It has about the same sensor size, goes to 120mm equivalent at 1:4.8 aperture. Its age has definite implications for handling (no image stabilisation, so tripod wanted), speed, storage media, convenience, autofocus, sensor resolution (10MP) and sensitivity (ISO400 is where noise starts) and so on. But for your principal criterion of a small depth of field at reasonable image quality in portrait situations, it will deliver more than the D3500 with a kit lens, but you will be left without an upgrade path.
Of course, analog cameras will deliver effortlessly in that category at quite cheaper secondhand prices but handling film is a hassle in comparison. Even if you do want to end up using film, learning your photographic skills using digital first is going to save you a lot of time and money.
To summarize: you want to throw money at a problem. The direction you are planning to throw it in is a good starting point but you'll need to throw more in that direction before achieving your goals. Partial goals may be achieved cheaper by throwing in a different direction first and thus getting a good idea how and where to throw larger wads of money for best effect at some later point of time.
Buying your learning gear preowned often means that as you develop a good idea where you want to be heading for real, the gear retains most of its resale value. Newer gear often is more supportive with regard to getting good results with moderate effort, however. |
108,713 | I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
I'm new in this community, so I'm not sure if this is the right place to ask this question. | 2019/06/05 | ['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/'] | Is an entry level DSLR going to shoot nice portrait pictures? By itself, *no*, absolutely not.
It's easy to make the joke that the camera by itself just sits there and doesn't take pictures at all, being an inanimate object and all. Of course, we know what you actually mean, but there's really some truth to that. A DSLR is by nature a flexible tool, and that includes the flexibility to *get bad results* as well as good ones. So, in a very real way, whether you get nice pictures is up to you, not the camera.
If you put some time, effort, and brain-power into learning how to operate a DSLR *and to understand fundamental concepts about light and composition*, you can **absolutely** get better results with a DSLR (entry level or above) than with a phone camera.
However, if you just want to snap pictures without learning anything or working for each shot, a high-end smartphone is guaranteed to produce results you'll be happier with 99% of the time.
**Spending your money on a DSLR (or other interchangeable lens camera) and hoping that that alone will produce good photographs is a recipe for frustration and disappointment.**
You say:
>
> Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
>
>
>
and fundamentally, to answer this, you need to know if you want to actually be a *beginner in photography* — that is, someone who is *starting on the path to something bigger*. Do you want to be an *amateur* in the true sense of "someone who does something because they love it"?
If the answer is yes, then it's probably worth quite a bit of money (and in fact, I'd suggest starting beyond so-called "entry level" cameras — see [Are there disadvantages to a prosumer camera for a beginner, aside from cost?](https://photo.stackexchange.com/questions/5883/are-there-disadvantages-to-a-prosumer-camera-for-a-beginner-aside-from-cost)).
On the other hand, if you mean "someone who doesn't know much and doesn't care to" (a [dabbler](https://english.stackexchange.com/questions/319354/whats-a-word-for-someone-with-low-level-of-knowledge-in-an-area-and-no-intenti), perhaps), then without even knowing your financial situation I can say that no, it would not be worth the money. | Yes, low-end DSLRs can get you nice photos. But it depends a lot on the photographer, not just the camera.
The main thing to keep in mind for blurry backgrounds is the ratio between two distances:
* camera to the point of focus; and
* camera to background.
The further the background relative to the subject, the blurrier the background.
Also, the bigger the aperture opens, the more pronounced the effect. The size of the opening is represented by the f-stop. The smaller the number, the wider the aperture (harder to focus). So f/16 will give you a much sharper overall picture than f/4. Much of the time, f/8 is pretty sharp all around, and if your lens can reach it, f/1.8 will give you good subject isolation with a blurry background. But you’ll need to experiment to see what *you* like. |
108,713 | I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
I'm new in this community, so I'm not sure if this is the right place to ask this question. | 2019/06/05 | ['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/'] | **It's not the camera, it's the lens.**
If you want a cheap and good option for shooting portrait pictures, you should definitely purchase in addition to a DSLR, a 50mm f/1.8 "nifty fifty" lens. Do expect to spend $100-$200 for the lens.
50mm is about optimal for portraits, because the relatively long 50mm focal length on crop sensor cameras is long enough to obtain blurred background while being short enough that the distance to the subject need not be excessive.
At 50mm, the kit zoom probably has f/5.6 aperture. A nifty fifty has f/1.8 aperture, which is more than 3x the difference. Three times the background blur with a nifty fifty.
Even an expensive (and heavy and large!) zoom (17-55mm f/2.8, $700-$1000) cannot match a nifty fifty (50mm f/1.8, $100-$200).
Also, the f/1.8 aperture is useful in low light no flash situations: the f/1.8 collects 9.68x the amount of light than the f/5.6 (@50mm) zoom. | Is an entry level DSLR going to shoot nice portrait pictures? By itself, *no*, absolutely not.
It's easy to make the joke that the camera by itself just sits there and doesn't take pictures at all, being an inanimate object and all. Of course, we know what you actually mean, but there's really some truth to that. A DSLR is by nature a flexible tool, and that includes the flexibility to *get bad results* as well as good ones. So, in a very real way, whether you get nice pictures is up to you, not the camera.
If you put some time, effort, and brain-power into learning how to operate a DSLR *and to understand fundamental concepts about light and composition*, you can **absolutely** get better results with a DSLR (entry level or above) than with a phone camera.
However, if you just want to snap pictures without learning anything or working for each shot, a high-end smartphone is guaranteed to produce results you'll be happier with 99% of the time.
**Spending your money on a DSLR (or other interchangeable lens camera) and hoping that that alone will produce good photographs is a recipe for frustration and disappointment.**
You say:
>
> Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
>
>
>
and fundamentally, to answer this, you need to know if you want to actually be a *beginner in photography* — that is, someone who is *starting on the path to something bigger*. Do you want to be an *amateur* in the true sense of "someone who does something because they love it"?
If the answer is yes, then it's probably worth quite a bit of money (and in fact, I'd suggest starting beyond so-called "entry level" cameras — see [Are there disadvantages to a prosumer camera for a beginner, aside from cost?](https://photo.stackexchange.com/questions/5883/are-there-disadvantages-to-a-prosumer-camera-for-a-beginner-aside-from-cost)).
On the other hand, if you mean "someone who doesn't know much and doesn't care to" (a [dabbler](https://english.stackexchange.com/questions/319354/whats-a-word-for-someone-with-low-level-of-knowledge-in-an-area-and-no-intenti), perhaps), then without even knowing your financial situation I can say that no, it would not be worth the money. |
108,713 | I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
I'm new in this community, so I'm not sure if this is the right place to ask this question. | 2019/06/05 | ['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/'] | If you read the other answers, it should be apparent that the qualities you seek such as (a) better portraits and (b) the desire to have a blurred background ... aren't really one thing, but a combination of many factors.
There are some nuances but the short answer is ... portraits do not require advanced DSLRs (so entry level is fine) but... there are nuances to consider. I discuss these below.
The advantage of the DSLR isn't that the camera is 'better' per se, but rather that it allows interchangeable accessories (such as lenses, lighting, etc.) to create the right conditions in order to capture the results you want.
Much of this is based on the knowledge & skill of the photographer. Buying a more expensive musical instrument doesn't make a person a better musician... learning music and practicing makes a person a better musician. The camera can't propel you forward ... but a camera with limited capabilities might hold you back.
If I buy a better guitar than anything Peter Frampton uses ... I will *still* not be a better musician than Peter Frampton (nowhere even close). His knowledge and skill in that area of music is legendary and mine ... not so much.
**Better portraits**
We're getting into a subjective area, but flip through portraits you like and try to notice why you like them. Inspect the posing of the model, the composition of the frame and how foreground or background elements are used. Check out the lighting (*especially* check out the lighting).
My personal thoughts are that:
1. Photographer knowledge & experience (skill) is probably the most important factor to influence the results. There's no getting around the notion that there will be a lot of learning and a lot of practice. The camera itself isn't a substitute for those considerations ... no matter how much a person pays for the equipment. Compositional skills, posing skills, exposure skills, lighting skills, etc. all require knowledge & experience ... regardless of how good the gear is. The camera will offer an 'automatic' mode and while that mode will capture adequate shots, they probably will not be the artistic results you were hoping to get.
2. Lighting is next. I put this ahead of lens selection. A key idea here is that you cannot have good light ... without good shadow. An image of a full moon never looks as good as an image of a 1st Quarter moon. The difference is that one has 'flat' lighting and the other has the light coming from the side. When the light comes from the side, any 3D textures produce shadows. It's the interplay of those highlights and shadows that causes the subject to appear three-dimensional with loads of textures. This isn't just true of the moon... it's true of anything you photograph. Shadows queue the eye (and the human brain) and provide information about the textures and contours. Another consideration is whether the transition from highlight to shadow is an abrupt line ... or a gentle transition. Is it 'hard' lighting or 'soft' lighting (hard & soft refer to those transitions... a hard-edge has an abrupt transition with a sharp line separating light & shadow. A soft-edge is a very gentle transition from one to the other.) Lighting can create moods... you can use light to convey emotions such as joy or peace or despair. In my opinion this is one of the most powerful tools a photographer has (and yet so very many photographers seem to be obsessed with just their camera.) The best lighting is the lighting that does what you want ... and this often means you may need ways to control the lighting (which is why advanced photographers own auxiliary lighting and lighting modifiers).
3. Lens selection is next on my personal list of priorities. A helpful way to think of lenses isn't so much by focal length ... but by *angle-of-view*. A lens can be *wide*, *normal*, or *narrow*. A normal angle of view is one that matches roughly what a human eye would perceive. A technical point to keep in mind (it's not hard to remember this) is that a lens will provide a *normal* angle of view if the focal length of the lens is the same as the diagonal measure of the sensor. For most DSLRs with an APS-C size sensor this is roughly 28mm (that's not exact). A 28mm lens on such a camera will offer a normal angle of view. If you use a shorter focal length (e.g. 20mm) you will have a moderately wide angle of view. If you use a much lower focal length (e.g. 10mm) you will have a very wide angle of view. A 50mm focal length will offer a moderately narrow angle of view. A 200mm lens will offer a very narrow angle of view. These angles-of-view create some interesting and useful side-effects. Wide angle lenses do not just shoot wider scenes... they also *stretch* the sense of the depth in a scene (want to make a room look larger or make a subject appear farther away... use a wider lens). The opposite happens with a narrow lens. Narrow lenses (long focal lengths) produce *compression*. Far away subjects don't look so far. The sense of depth in a scene is 'compressed'.
4. The camera body is in last place on my list. It isn't that it is not important... it is important. But it wields less influence than the three factors above it. There are many instances where the physical sensor used in an entry level body is actually the *same* sensor used in a higher-end body. So what's the difference? Usually the difference is other features such as the number and type of focus points used ... or how quickly the camera can rapidly burst shots ... or the size of the camera's internal memory buffer. If you're doing a lot of action photography, there are features a camera might have that optimizes it toward action photography. But if you're shooting a landscape on a tripod using a remote shutter release and you have all the time in the world to get that shot... having loads of auto-focus points and high-speed burst isn't really going to help you. On the other hand if you are a sports/action photographer ... the lack of those features might mean you get fewer 'keepers' as the camera struggles to have the focus system and shutter keep up with the action.
The above is my priority list. A different photographer might give you a different order. I don't get to hung up on brand names or equipment. Loads of companies make fantastic cameras. It is possible to select a camera that may not be ideal for a particular type of photography ... and it is possible to select a lens that isn't ideal.
**Blurred Backgrounds**
Ultimately the ability to have one thing in sharp focus and another thing far out of focus (to make that thing blurry) is based on an idea called the **Depth of Field** (you'll often see this abbreviated as DoF).
If my subject is 10 feet away and I point the lens at the subject, we'll need to focus the lens on the subject. In reality we are adjusting the focus for a 10 foot distance. If something is not *precisely* 10' away... suppose something is 9'11" or 10'1" -- will being fractionally nearer or farther make a difference? Probably not when you consider the ratios... 10' = 10 x 12 inches or 120 inches away. So a 1" difference works out to a difference of just 0.8% (not even 1%). But what if a lens was focused to 10' and something else was 100' away... now the difference is more significant.
DoF is the idea that there's a range of distances at which you will judge the subject to be ... more or less ... acceptably focused (I didn't say perfectly focused). How you judge this will also be affected by how closely you inspect the image.
There are a few factors that ... when added together ... affect the overall depth-of-field.
This include things such as:
* Focal length of the lens where short focal length lenses tend to produce much broader depth of field and very long focal length lenses tend to produce much narrower depth of field.
* Focal ratio of the lens. The focal ratio considers the size of the physical opening in the lens through which light may pass. But instead of being a simple diameter ... it is expressed as a *ratio* of the lens' overall focal length divided by that physical diameter. If a lens with a 100mm focal length has an aperture opening 50mm across than that lens has a focal ratio of 2 ... since 100 ÷ 50 = 2. That would be expressed as f/2 (the 'f/' is short-hand for *focal ratio*). If we adjust the opening so that it has a diameter of 25mm then the focal ratio becomes f/4 because 100 ÷ 25 = 4. One take-away is notice that the lower-focal ratio example (f/2) had the larger physical diameter opening in the lens (50mm opening on a 100mm lens). If the lens had a very tiny opening (a pin-hole) then all the light has to pass through just that one very tiny point. Such a lens would have and extremely large depth-of-field. If you use a lens with a very large opening, the photons have a choice of many different paths through the lens. This reduces the overall depth-of-field.
* Subject distance is another factor. If a subject is very far away a lens needs to be focused to near the *infinity* point. Of course everything in the background is even farther ... so *also* focused to near the infinity point. Since there isn't much difference ... the background seems to be more or less just as well focused as the subject. Foreground subjects might appear blurry. But if the subject were close to you... and the background was quite far away, the background will probably appear to be more blurred. As a photographer I *rarely* place a subject against a wall for a portrait shoot... unless that wall is *extremely* interesting and will add to the overall value of the shot. Better to pull them away from the wall so that the wall can fall begins to get farther outside the depth-of-field.
All of these factors have to be combined... each one simply influences the overall depth of field. None of them completely rule the depth of field.
A camera with a long focal length lens using a very low focal ratio and a subject placed somewhat close to the camera with a background placed much farther away ... will result in strong background blur. Doing the opposite ... short-focal length lens, high focal ratio, and a more distant subject ... will produce very large DoF and you won't notice much blur in the background.
**Other Considerations for Blur**
There is a term used in photography called 'bokeh'. This term refers to the *quality* of the blur... not the *strength* of the blur.
Once upon a time, Canon produce a particular 50mm f/1.8 lens that had merely 5 aperture blades inside the lens and these were not well-rounded blades. This means the opening in the lens was a pentagon instead of a circle. As points of light blur, they blur with the geometry of the aperture opening. This means that as pentagons overlap pentagons it created a rather strange effect ... the quality of the blur was not very smooth. It was somewhat jagged ... jittery ... almost nervous looking. It did not evoke emotions of peace and beauty that will add to the effect most photographers were going for.
Canon replaced that lens with a lens that has identical optics (not similar... identical!) But that newer lens has 7 aperture blades instead of 5 and the blades on the newer lens do a bit better w.r.t. to being more well-rounded. This produces a more circular opening and the results in images produce a much better quality in the background blur (the blur appears more smooth).
The lenses are optically identical and they have identical focal ratios. But one lens produce a poor quality blur. The other produces a higher quality blur.
*This* is what the term 'bokeh' is meant to convey... the quality (over quantity).
This means that even if you combine the conditions such as focal length, focal ratio, and subject distance (relative to background distance) to try to maximize the background blur... it is possible to have a blur ... but a blur that you may not enjoy.
**Summary**
* An entry-level DSLR body is fine for portrait work. Portraits usually do not require advanced camera features.
* You'll need to pair it with an appropriate lens to achieve the results you want (blurred background portraits). A DSLR is often packaged with a 'kit' lens and this is usually a standard zoom offering a bit of wide angle and a bit of narrow angle but not a particularly low focal ratio (manufacturers try to pair the camera body with an affordable lens to put them with financial reach of more consumers). Using a 50mm lens would be better ... using an 85mm lens would be even better still.
* Your skill will be very important ... the equipment alone wont be enough. If you use the 'automatic' setting mode it will tend to go for 'safe' exposures ... not artistic exposures. Skill is needed to learn which settings produce the results you want.
* Lighting will also be an important factor. Good lighting isn't just natural lighting... it's lighting that does what you want. Photographers with deeper pockets invest in equipment (although a lot of lighting gear can be surprisingly cheap when you compare lighting costs to lens costs and other equipment costs) ... but they invest in this gear specifically because it lets them control the lighting. | A DX sensor has a crop factor of 2/3. You are presumably talking about the 18-55mm kit lens. For portrait work, you'd likely use it at its long end, giving you about 83mm equivalent focal length with an aperture of 1:5.6. That will give you the same depth of field as an 1:8 aperture setting on a 35mm film camera with the same kind of effective focal length which is quite discernible but not terribly strong. You'll want to arrange your scene appropriately so that the background is indeed some distance away.
The computational blurring on a smartphone aims to emulate the visuals of quite smaller depth of field, namely larger sensors/aperture. If your viewing device ends up being a smartphone, you'll not likely be able to appreciate the much more natural action of optical object isolation (but due to camera and lens parameters, more subtle) over computational approaches, particularly since the small display scale increases the perceived depth of field.
If you are going for print, things will look different already, however.
Is it worth the money? It depends on your purpose. If you don't intend to throw further money at the problem of doing portraits (namely buying a suitable prime lens or a less basic zoom lens), you'd likely be better off with a 15-year old Sony DSC-R1. It has about the same sensor size, goes to 120mm equivalent at 1:4.8 aperture. Its age has definite implications for handling (no image stabilisation, so tripod wanted), speed, storage media, convenience, autofocus, sensor resolution (10MP) and sensitivity (ISO400 is where noise starts) and so on. But for your principal criterion of a small depth of field at reasonable image quality in portrait situations, it will deliver more than the D3500 with a kit lens, but you will be left without an upgrade path.
Of course, analog cameras will deliver effortlessly in that category at quite cheaper secondhand prices but handling film is a hassle in comparison. Even if you do want to end up using film, learning your photographic skills using digital first is going to save you a lot of time and money.
To summarize: you want to throw money at a problem. The direction you are planning to throw it in is a good starting point but you'll need to throw more in that direction before achieving your goals. Partial goals may be achieved cheaper by throwing in a different direction first and thus getting a good idea how and where to throw larger wads of money for best effect at some later point of time.
Buying your learning gear preowned often means that as you develop a good idea where you want to be heading for real, the gear retains most of its resale value. Newer gear often is more supportive with regard to getting good results with moderate effort, however. |
108,713 | I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
I'm new in this community, so I'm not sure if this is the right place to ask this question. | 2019/06/05 | ['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/'] | Is an entry level DSLR going to shoot nice portrait pictures? By itself, *no*, absolutely not.
It's easy to make the joke that the camera by itself just sits there and doesn't take pictures at all, being an inanimate object and all. Of course, we know what you actually mean, but there's really some truth to that. A DSLR is by nature a flexible tool, and that includes the flexibility to *get bad results* as well as good ones. So, in a very real way, whether you get nice pictures is up to you, not the camera.
If you put some time, effort, and brain-power into learning how to operate a DSLR *and to understand fundamental concepts about light and composition*, you can **absolutely** get better results with a DSLR (entry level or above) than with a phone camera.
However, if you just want to snap pictures without learning anything or working for each shot, a high-end smartphone is guaranteed to produce results you'll be happier with 99% of the time.
**Spending your money on a DSLR (or other interchangeable lens camera) and hoping that that alone will produce good photographs is a recipe for frustration and disappointment.**
You say:
>
> Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
>
>
>
and fundamentally, to answer this, you need to know if you want to actually be a *beginner in photography* — that is, someone who is *starting on the path to something bigger*. Do you want to be an *amateur* in the true sense of "someone who does something because they love it"?
If the answer is yes, then it's probably worth quite a bit of money (and in fact, I'd suggest starting beyond so-called "entry level" cameras — see [Are there disadvantages to a prosumer camera for a beginner, aside from cost?](https://photo.stackexchange.com/questions/5883/are-there-disadvantages-to-a-prosumer-camera-for-a-beginner-aside-from-cost)).
On the other hand, if you mean "someone who doesn't know much and doesn't care to" (a [dabbler](https://english.stackexchange.com/questions/319354/whats-a-word-for-someone-with-low-level-of-knowledge-in-an-area-and-no-intenti), perhaps), then without even knowing your financial situation I can say that no, it would not be worth the money. | I had an entry level for years (Canon 550D) and I have taken really good shots on it. Although lenses are important, I would like to enumerate a few other factors (sorted from the most important to the less important) that will influence on your results
1. **The subject**: This is by far the most important of all. Your cellphone can make a much better picture than your camera if you point it to the right subject. I have wasted a lot of time taking pictures of not so interesting subjects and thinking about saving money to buy a better camera until I finally discovered that it is a much better investment to spend that money on short travels to parks with view-sights and animals, or neighborhoods with cute streets and interesting people, etc etc.
2. **Light and weather conditions**: Remember the park I said you should go? If you really want good results, you should check the forecast, go really early in the morning or maybe after rains, it depends on what you want, but this the right conditions will add the right "life" to your photos
3. **The lenses**: You may be in the right place but maybe the right light you want is something that just doesn't occur naturally. Or maybe you want to be much closer to some animal, or to take a much wider picture. For this, you have the lenses. An f/4 outside in a clear day can make really good pictures, but an f/2.8 will let you work under more severe light conditions. However, an f/4 is much lighter than an f/2.8 and this may allow you to make longer journeys. An 70-200mm will make you fell amazed on how much close you can get to some subjects and a 16mm will let you make excellent wide photos. And good lens are forever. They will always do their job and you can sell them well if in good condition. They are an instant change in possibilities: you change the lens, everything changes
4. **How you use your camera and lenses**: You have to know your equipment. To know where are the button, the limitations, which possibilities do you have and so on. After upgrading for a better camera, you will feel for a while that you were more capable with your old camera until you get to know your new one
5. **The camera**: Finally, the camera. In my experience, a better camera gives you a better ISO, better shutter, more durable components, more functionalities, more photos per second, etc. Not necessarily a better sensor, for example. The better camera will make it easier for you to go further, but if you don't have what I told you above, there will be not a lot of difference in your results.
Best thing I can recommend in order to achieve maturity as a photographer so you finally feel that your entry level camera is limiting you is to go outside and take pictures. Just go out for it every weekend and you will start to understand the places, the lights, your equipment. After that, the day will come where you will know exactly why you need a better camera and what camera you need. And you will probably keep the entry level, because they are good anyway. |
108,713 | I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
I'm new in this community, so I'm not sure if this is the right place to ask this question. | 2019/06/05 | ['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/'] | Is an entry level DSLR going to shoot nice portrait pictures? By itself, *no*, absolutely not.
It's easy to make the joke that the camera by itself just sits there and doesn't take pictures at all, being an inanimate object and all. Of course, we know what you actually mean, but there's really some truth to that. A DSLR is by nature a flexible tool, and that includes the flexibility to *get bad results* as well as good ones. So, in a very real way, whether you get nice pictures is up to you, not the camera.
If you put some time, effort, and brain-power into learning how to operate a DSLR *and to understand fundamental concepts about light and composition*, you can **absolutely** get better results with a DSLR (entry level or above) than with a phone camera.
However, if you just want to snap pictures without learning anything or working for each shot, a high-end smartphone is guaranteed to produce results you'll be happier with 99% of the time.
**Spending your money on a DSLR (or other interchangeable lens camera) and hoping that that alone will produce good photographs is a recipe for frustration and disappointment.**
You say:
>
> Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
>
>
>
and fundamentally, to answer this, you need to know if you want to actually be a *beginner in photography* — that is, someone who is *starting on the path to something bigger*. Do you want to be an *amateur* in the true sense of "someone who does something because they love it"?
If the answer is yes, then it's probably worth quite a bit of money (and in fact, I'd suggest starting beyond so-called "entry level" cameras — see [Are there disadvantages to a prosumer camera for a beginner, aside from cost?](https://photo.stackexchange.com/questions/5883/are-there-disadvantages-to-a-prosumer-camera-for-a-beginner-aside-from-cost)).
On the other hand, if you mean "someone who doesn't know much and doesn't care to" (a [dabbler](https://english.stackexchange.com/questions/319354/whats-a-word-for-someone-with-low-level-of-knowledge-in-an-area-and-no-intenti), perhaps), then without even knowing your financial situation I can say that no, it would not be worth the money. | A DX sensor has a crop factor of 2/3. You are presumably talking about the 18-55mm kit lens. For portrait work, you'd likely use it at its long end, giving you about 83mm equivalent focal length with an aperture of 1:5.6. That will give you the same depth of field as an 1:8 aperture setting on a 35mm film camera with the same kind of effective focal length which is quite discernible but not terribly strong. You'll want to arrange your scene appropriately so that the background is indeed some distance away.
The computational blurring on a smartphone aims to emulate the visuals of quite smaller depth of field, namely larger sensors/aperture. If your viewing device ends up being a smartphone, you'll not likely be able to appreciate the much more natural action of optical object isolation (but due to camera and lens parameters, more subtle) over computational approaches, particularly since the small display scale increases the perceived depth of field.
If you are going for print, things will look different already, however.
Is it worth the money? It depends on your purpose. If you don't intend to throw further money at the problem of doing portraits (namely buying a suitable prime lens or a less basic zoom lens), you'd likely be better off with a 15-year old Sony DSC-R1. It has about the same sensor size, goes to 120mm equivalent at 1:4.8 aperture. Its age has definite implications for handling (no image stabilisation, so tripod wanted), speed, storage media, convenience, autofocus, sensor resolution (10MP) and sensitivity (ISO400 is where noise starts) and so on. But for your principal criterion of a small depth of field at reasonable image quality in portrait situations, it will deliver more than the D3500 with a kit lens, but you will be left without an upgrade path.
Of course, analog cameras will deliver effortlessly in that category at quite cheaper secondhand prices but handling film is a hassle in comparison. Even if you do want to end up using film, learning your photographic skills using digital first is going to save you a lot of time and money.
To summarize: you want to throw money at a problem. The direction you are planning to throw it in is a good starting point but you'll need to throw more in that direction before achieving your goals. Partial goals may be achieved cheaper by throwing in a different direction first and thus getting a good idea how and where to throw larger wads of money for best effect at some later point of time.
Buying your learning gear preowned often means that as you develop a good idea where you want to be heading for real, the gear retains most of its resale value. Newer gear often is more supportive with regard to getting good results with moderate effort, however. |
108,713 | I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
I'm new in this community, so I'm not sure if this is the right place to ask this question. | 2019/06/05 | ['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/'] | **It's not the camera, it's the lens.**
If you want a cheap and good option for shooting portrait pictures, you should definitely purchase in addition to a DSLR, a 50mm f/1.8 "nifty fifty" lens. Do expect to spend $100-$200 for the lens.
50mm is about optimal for portraits, because the relatively long 50mm focal length on crop sensor cameras is long enough to obtain blurred background while being short enough that the distance to the subject need not be excessive.
At 50mm, the kit zoom probably has f/5.6 aperture. A nifty fifty has f/1.8 aperture, which is more than 3x the difference. Three times the background blur with a nifty fifty.
Even an expensive (and heavy and large!) zoom (17-55mm f/2.8, $700-$1000) cannot match a nifty fifty (50mm f/1.8, $100-$200).
Also, the f/1.8 aperture is useful in low light no flash situations: the f/1.8 collects 9.68x the amount of light than the f/5.6 (@50mm) zoom. | I had an entry level for years (Canon 550D) and I have taken really good shots on it. Although lenses are important, I would like to enumerate a few other factors (sorted from the most important to the less important) that will influence on your results
1. **The subject**: This is by far the most important of all. Your cellphone can make a much better picture than your camera if you point it to the right subject. I have wasted a lot of time taking pictures of not so interesting subjects and thinking about saving money to buy a better camera until I finally discovered that it is a much better investment to spend that money on short travels to parks with view-sights and animals, or neighborhoods with cute streets and interesting people, etc etc.
2. **Light and weather conditions**: Remember the park I said you should go? If you really want good results, you should check the forecast, go really early in the morning or maybe after rains, it depends on what you want, but this the right conditions will add the right "life" to your photos
3. **The lenses**: You may be in the right place but maybe the right light you want is something that just doesn't occur naturally. Or maybe you want to be much closer to some animal, or to take a much wider picture. For this, you have the lenses. An f/4 outside in a clear day can make really good pictures, but an f/2.8 will let you work under more severe light conditions. However, an f/4 is much lighter than an f/2.8 and this may allow you to make longer journeys. An 70-200mm will make you fell amazed on how much close you can get to some subjects and a 16mm will let you make excellent wide photos. And good lens are forever. They will always do their job and you can sell them well if in good condition. They are an instant change in possibilities: you change the lens, everything changes
4. **How you use your camera and lenses**: You have to know your equipment. To know where are the button, the limitations, which possibilities do you have and so on. After upgrading for a better camera, you will feel for a while that you were more capable with your old camera until you get to know your new one
5. **The camera**: Finally, the camera. In my experience, a better camera gives you a better ISO, better shutter, more durable components, more functionalities, more photos per second, etc. Not necessarily a better sensor, for example. The better camera will make it easier for you to go further, but if you don't have what I told you above, there will be not a lot of difference in your results.
Best thing I can recommend in order to achieve maturity as a photographer so you finally feel that your entry level camera is limiting you is to go outside and take pictures. Just go out for it every weekend and you will start to understand the places, the lights, your equipment. After that, the day will come where you will know exactly why you need a better camera and what camera you need. And you will probably keep the entry level, because they are good anyway. |
108,713 | I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
I'm new in this community, so I'm not sure if this is the right place to ask this question. | 2019/06/05 | ['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/'] | If you read the other answers, it should be apparent that the qualities you seek such as (a) better portraits and (b) the desire to have a blurred background ... aren't really one thing, but a combination of many factors.
There are some nuances but the short answer is ... portraits do not require advanced DSLRs (so entry level is fine) but... there are nuances to consider. I discuss these below.
The advantage of the DSLR isn't that the camera is 'better' per se, but rather that it allows interchangeable accessories (such as lenses, lighting, etc.) to create the right conditions in order to capture the results you want.
Much of this is based on the knowledge & skill of the photographer. Buying a more expensive musical instrument doesn't make a person a better musician... learning music and practicing makes a person a better musician. The camera can't propel you forward ... but a camera with limited capabilities might hold you back.
If I buy a better guitar than anything Peter Frampton uses ... I will *still* not be a better musician than Peter Frampton (nowhere even close). His knowledge and skill in that area of music is legendary and mine ... not so much.
**Better portraits**
We're getting into a subjective area, but flip through portraits you like and try to notice why you like them. Inspect the posing of the model, the composition of the frame and how foreground or background elements are used. Check out the lighting (*especially* check out the lighting).
My personal thoughts are that:
1. Photographer knowledge & experience (skill) is probably the most important factor to influence the results. There's no getting around the notion that there will be a lot of learning and a lot of practice. The camera itself isn't a substitute for those considerations ... no matter how much a person pays for the equipment. Compositional skills, posing skills, exposure skills, lighting skills, etc. all require knowledge & experience ... regardless of how good the gear is. The camera will offer an 'automatic' mode and while that mode will capture adequate shots, they probably will not be the artistic results you were hoping to get.
2. Lighting is next. I put this ahead of lens selection. A key idea here is that you cannot have good light ... without good shadow. An image of a full moon never looks as good as an image of a 1st Quarter moon. The difference is that one has 'flat' lighting and the other has the light coming from the side. When the light comes from the side, any 3D textures produce shadows. It's the interplay of those highlights and shadows that causes the subject to appear three-dimensional with loads of textures. This isn't just true of the moon... it's true of anything you photograph. Shadows queue the eye (and the human brain) and provide information about the textures and contours. Another consideration is whether the transition from highlight to shadow is an abrupt line ... or a gentle transition. Is it 'hard' lighting or 'soft' lighting (hard & soft refer to those transitions... a hard-edge has an abrupt transition with a sharp line separating light & shadow. A soft-edge is a very gentle transition from one to the other.) Lighting can create moods... you can use light to convey emotions such as joy or peace or despair. In my opinion this is one of the most powerful tools a photographer has (and yet so very many photographers seem to be obsessed with just their camera.) The best lighting is the lighting that does what you want ... and this often means you may need ways to control the lighting (which is why advanced photographers own auxiliary lighting and lighting modifiers).
3. Lens selection is next on my personal list of priorities. A helpful way to think of lenses isn't so much by focal length ... but by *angle-of-view*. A lens can be *wide*, *normal*, or *narrow*. A normal angle of view is one that matches roughly what a human eye would perceive. A technical point to keep in mind (it's not hard to remember this) is that a lens will provide a *normal* angle of view if the focal length of the lens is the same as the diagonal measure of the sensor. For most DSLRs with an APS-C size sensor this is roughly 28mm (that's not exact). A 28mm lens on such a camera will offer a normal angle of view. If you use a shorter focal length (e.g. 20mm) you will have a moderately wide angle of view. If you use a much lower focal length (e.g. 10mm) you will have a very wide angle of view. A 50mm focal length will offer a moderately narrow angle of view. A 200mm lens will offer a very narrow angle of view. These angles-of-view create some interesting and useful side-effects. Wide angle lenses do not just shoot wider scenes... they also *stretch* the sense of the depth in a scene (want to make a room look larger or make a subject appear farther away... use a wider lens). The opposite happens with a narrow lens. Narrow lenses (long focal lengths) produce *compression*. Far away subjects don't look so far. The sense of depth in a scene is 'compressed'.
4. The camera body is in last place on my list. It isn't that it is not important... it is important. But it wields less influence than the three factors above it. There are many instances where the physical sensor used in an entry level body is actually the *same* sensor used in a higher-end body. So what's the difference? Usually the difference is other features such as the number and type of focus points used ... or how quickly the camera can rapidly burst shots ... or the size of the camera's internal memory buffer. If you're doing a lot of action photography, there are features a camera might have that optimizes it toward action photography. But if you're shooting a landscape on a tripod using a remote shutter release and you have all the time in the world to get that shot... having loads of auto-focus points and high-speed burst isn't really going to help you. On the other hand if you are a sports/action photographer ... the lack of those features might mean you get fewer 'keepers' as the camera struggles to have the focus system and shutter keep up with the action.
The above is my priority list. A different photographer might give you a different order. I don't get to hung up on brand names or equipment. Loads of companies make fantastic cameras. It is possible to select a camera that may not be ideal for a particular type of photography ... and it is possible to select a lens that isn't ideal.
**Blurred Backgrounds**
Ultimately the ability to have one thing in sharp focus and another thing far out of focus (to make that thing blurry) is based on an idea called the **Depth of Field** (you'll often see this abbreviated as DoF).
If my subject is 10 feet away and I point the lens at the subject, we'll need to focus the lens on the subject. In reality we are adjusting the focus for a 10 foot distance. If something is not *precisely* 10' away... suppose something is 9'11" or 10'1" -- will being fractionally nearer or farther make a difference? Probably not when you consider the ratios... 10' = 10 x 12 inches or 120 inches away. So a 1" difference works out to a difference of just 0.8% (not even 1%). But what if a lens was focused to 10' and something else was 100' away... now the difference is more significant.
DoF is the idea that there's a range of distances at which you will judge the subject to be ... more or less ... acceptably focused (I didn't say perfectly focused). How you judge this will also be affected by how closely you inspect the image.
There are a few factors that ... when added together ... affect the overall depth-of-field.
This include things such as:
* Focal length of the lens where short focal length lenses tend to produce much broader depth of field and very long focal length lenses tend to produce much narrower depth of field.
* Focal ratio of the lens. The focal ratio considers the size of the physical opening in the lens through which light may pass. But instead of being a simple diameter ... it is expressed as a *ratio* of the lens' overall focal length divided by that physical diameter. If a lens with a 100mm focal length has an aperture opening 50mm across than that lens has a focal ratio of 2 ... since 100 ÷ 50 = 2. That would be expressed as f/2 (the 'f/' is short-hand for *focal ratio*). If we adjust the opening so that it has a diameter of 25mm then the focal ratio becomes f/4 because 100 ÷ 25 = 4. One take-away is notice that the lower-focal ratio example (f/2) had the larger physical diameter opening in the lens (50mm opening on a 100mm lens). If the lens had a very tiny opening (a pin-hole) then all the light has to pass through just that one very tiny point. Such a lens would have and extremely large depth-of-field. If you use a lens with a very large opening, the photons have a choice of many different paths through the lens. This reduces the overall depth-of-field.
* Subject distance is another factor. If a subject is very far away a lens needs to be focused to near the *infinity* point. Of course everything in the background is even farther ... so *also* focused to near the infinity point. Since there isn't much difference ... the background seems to be more or less just as well focused as the subject. Foreground subjects might appear blurry. But if the subject were close to you... and the background was quite far away, the background will probably appear to be more blurred. As a photographer I *rarely* place a subject against a wall for a portrait shoot... unless that wall is *extremely* interesting and will add to the overall value of the shot. Better to pull them away from the wall so that the wall can fall begins to get farther outside the depth-of-field.
All of these factors have to be combined... each one simply influences the overall depth of field. None of them completely rule the depth of field.
A camera with a long focal length lens using a very low focal ratio and a subject placed somewhat close to the camera with a background placed much farther away ... will result in strong background blur. Doing the opposite ... short-focal length lens, high focal ratio, and a more distant subject ... will produce very large DoF and you won't notice much blur in the background.
**Other Considerations for Blur**
There is a term used in photography called 'bokeh'. This term refers to the *quality* of the blur... not the *strength* of the blur.
Once upon a time, Canon produce a particular 50mm f/1.8 lens that had merely 5 aperture blades inside the lens and these were not well-rounded blades. This means the opening in the lens was a pentagon instead of a circle. As points of light blur, they blur with the geometry of the aperture opening. This means that as pentagons overlap pentagons it created a rather strange effect ... the quality of the blur was not very smooth. It was somewhat jagged ... jittery ... almost nervous looking. It did not evoke emotions of peace and beauty that will add to the effect most photographers were going for.
Canon replaced that lens with a lens that has identical optics (not similar... identical!) But that newer lens has 7 aperture blades instead of 5 and the blades on the newer lens do a bit better w.r.t. to being more well-rounded. This produces a more circular opening and the results in images produce a much better quality in the background blur (the blur appears more smooth).
The lenses are optically identical and they have identical focal ratios. But one lens produce a poor quality blur. The other produces a higher quality blur.
*This* is what the term 'bokeh' is meant to convey... the quality (over quantity).
This means that even if you combine the conditions such as focal length, focal ratio, and subject distance (relative to background distance) to try to maximize the background blur... it is possible to have a blur ... but a blur that you may not enjoy.
**Summary**
* An entry-level DSLR body is fine for portrait work. Portraits usually do not require advanced camera features.
* You'll need to pair it with an appropriate lens to achieve the results you want (blurred background portraits). A DSLR is often packaged with a 'kit' lens and this is usually a standard zoom offering a bit of wide angle and a bit of narrow angle but not a particularly low focal ratio (manufacturers try to pair the camera body with an affordable lens to put them with financial reach of more consumers). Using a 50mm lens would be better ... using an 85mm lens would be even better still.
* Your skill will be very important ... the equipment alone wont be enough. If you use the 'automatic' setting mode it will tend to go for 'safe' exposures ... not artistic exposures. Skill is needed to learn which settings produce the results you want.
* Lighting will also be an important factor. Good lighting isn't just natural lighting... it's lighting that does what you want. Photographers with deeper pockets invest in equipment (although a lot of lighting gear can be surprisingly cheap when you compare lighting costs to lens costs and other equipment costs) ... but they invest in this gear specifically because it lets them control the lighting. | Is an entry level DSLR going to shoot nice portrait pictures? By itself, *no*, absolutely not.
It's easy to make the joke that the camera by itself just sits there and doesn't take pictures at all, being an inanimate object and all. Of course, we know what you actually mean, but there's really some truth to that. A DSLR is by nature a flexible tool, and that includes the flexibility to *get bad results* as well as good ones. So, in a very real way, whether you get nice pictures is up to you, not the camera.
If you put some time, effort, and brain-power into learning how to operate a DSLR *and to understand fundamental concepts about light and composition*, you can **absolutely** get better results with a DSLR (entry level or above) than with a phone camera.
However, if you just want to snap pictures without learning anything or working for each shot, a high-end smartphone is guaranteed to produce results you'll be happier with 99% of the time.
**Spending your money on a DSLR (or other interchangeable lens camera) and hoping that that alone will produce good photographs is a recipe for frustration and disappointment.**
You say:
>
> Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
>
>
>
and fundamentally, to answer this, you need to know if you want to actually be a *beginner in photography* — that is, someone who is *starting on the path to something bigger*. Do you want to be an *amateur* in the true sense of "someone who does something because they love it"?
If the answer is yes, then it's probably worth quite a bit of money (and in fact, I'd suggest starting beyond so-called "entry level" cameras — see [Are there disadvantages to a prosumer camera for a beginner, aside from cost?](https://photo.stackexchange.com/questions/5883/are-there-disadvantages-to-a-prosumer-camera-for-a-beginner-aside-from-cost)).
On the other hand, if you mean "someone who doesn't know much and doesn't care to" (a [dabbler](https://english.stackexchange.com/questions/319354/whats-a-word-for-someone-with-low-level-of-knowledge-in-an-area-and-no-intenti), perhaps), then without even knowing your financial situation I can say that no, it would not be worth the money. |
108,713 | I'm thinking of buying entry level DSLR Nikon D3500. I haven't used DSLR before, so I'm not sure if it is a good decision to buy DSLR. I would like to know if with this camera I can shoot portraits with blured background such as on the new smartphones with two cameras. Another thing I want to know if buying DSLR is good for beginners in photography and amateur photographers and is it worth the money.
I'm new in this community, so I'm not sure if this is the right place to ask this question. | 2019/06/05 | ['https://photo.stackexchange.com/questions/108713', 'https://photo.stackexchange.com', 'https://photo.stackexchange.com/users/85164/'] | I had an entry level for years (Canon 550D) and I have taken really good shots on it. Although lenses are important, I would like to enumerate a few other factors (sorted from the most important to the less important) that will influence on your results
1. **The subject**: This is by far the most important of all. Your cellphone can make a much better picture than your camera if you point it to the right subject. I have wasted a lot of time taking pictures of not so interesting subjects and thinking about saving money to buy a better camera until I finally discovered that it is a much better investment to spend that money on short travels to parks with view-sights and animals, or neighborhoods with cute streets and interesting people, etc etc.
2. **Light and weather conditions**: Remember the park I said you should go? If you really want good results, you should check the forecast, go really early in the morning or maybe after rains, it depends on what you want, but this the right conditions will add the right "life" to your photos
3. **The lenses**: You may be in the right place but maybe the right light you want is something that just doesn't occur naturally. Or maybe you want to be much closer to some animal, or to take a much wider picture. For this, you have the lenses. An f/4 outside in a clear day can make really good pictures, but an f/2.8 will let you work under more severe light conditions. However, an f/4 is much lighter than an f/2.8 and this may allow you to make longer journeys. An 70-200mm will make you fell amazed on how much close you can get to some subjects and a 16mm will let you make excellent wide photos. And good lens are forever. They will always do their job and you can sell them well if in good condition. They are an instant change in possibilities: you change the lens, everything changes
4. **How you use your camera and lenses**: You have to know your equipment. To know where are the button, the limitations, which possibilities do you have and so on. After upgrading for a better camera, you will feel for a while that you were more capable with your old camera until you get to know your new one
5. **The camera**: Finally, the camera. In my experience, a better camera gives you a better ISO, better shutter, more durable components, more functionalities, more photos per second, etc. Not necessarily a better sensor, for example. The better camera will make it easier for you to go further, but if you don't have what I told you above, there will be not a lot of difference in your results.
Best thing I can recommend in order to achieve maturity as a photographer so you finally feel that your entry level camera is limiting you is to go outside and take pictures. Just go out for it every weekend and you will start to understand the places, the lights, your equipment. After that, the day will come where you will know exactly why you need a better camera and what camera you need. And you will probably keep the entry level, because they are good anyway. | A DX sensor has a crop factor of 2/3. You are presumably talking about the 18-55mm kit lens. For portrait work, you'd likely use it at its long end, giving you about 83mm equivalent focal length with an aperture of 1:5.6. That will give you the same depth of field as an 1:8 aperture setting on a 35mm film camera with the same kind of effective focal length which is quite discernible but not terribly strong. You'll want to arrange your scene appropriately so that the background is indeed some distance away.
The computational blurring on a smartphone aims to emulate the visuals of quite smaller depth of field, namely larger sensors/aperture. If your viewing device ends up being a smartphone, you'll not likely be able to appreciate the much more natural action of optical object isolation (but due to camera and lens parameters, more subtle) over computational approaches, particularly since the small display scale increases the perceived depth of field.
If you are going for print, things will look different already, however.
Is it worth the money? It depends on your purpose. If you don't intend to throw further money at the problem of doing portraits (namely buying a suitable prime lens or a less basic zoom lens), you'd likely be better off with a 15-year old Sony DSC-R1. It has about the same sensor size, goes to 120mm equivalent at 1:4.8 aperture. Its age has definite implications for handling (no image stabilisation, so tripod wanted), speed, storage media, convenience, autofocus, sensor resolution (10MP) and sensitivity (ISO400 is where noise starts) and so on. But for your principal criterion of a small depth of field at reasonable image quality in portrait situations, it will deliver more than the D3500 with a kit lens, but you will be left without an upgrade path.
Of course, analog cameras will deliver effortlessly in that category at quite cheaper secondhand prices but handling film is a hassle in comparison. Even if you do want to end up using film, learning your photographic skills using digital first is going to save you a lot of time and money.
To summarize: you want to throw money at a problem. The direction you are planning to throw it in is a good starting point but you'll need to throw more in that direction before achieving your goals. Partial goals may be achieved cheaper by throwing in a different direction first and thus getting a good idea how and where to throw larger wads of money for best effect at some later point of time.
Buying your learning gear preowned often means that as you develop a good idea where you want to be heading for real, the gear retains most of its resale value. Newer gear often is more supportive with regard to getting good results with moderate effort, however. |
11,967,306 | I am trying to use the package doBy, which requires an installation of the package lme4.
I have found the CRAN for it here <http://cran.r-project.org/web/packages/lme4//index.html>
However when I try download the .zip version I get the error "Object not found!".
From what I gather it is not an out of date package (with it last been updated in June of this year).
Does anyone know a way to get around this, or do I just need to wait for lme4 to be fixed/find an alternative for doBy?
Thanks | 2012/08/15 | ['https://Stackoverflow.com/questions/11967306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1545812/'] | try
```
install.packages("lme4",repos="http://r-forge.r-project.org")
``` | Do you use R Studio? I was having the same issue but then I used R Studio's tab "Packages" -> Install tab --> write lme4 from th CRAN repository. |
5,738,073 | I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?) | 2011/04/21 | ['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/'] | No, I don't think so. The only time it can't figure things out is if you try to do something like
```
var product = null;
```
Which makes sense, and in this case you get a compile error. | In addition to the ambiguous:
```
var x = null;
```
the compiler will also not infer the type of overloaded method groups:
```
var m = String.Equals;
```
nor will it infer the type of lambda expressions, which can be either `Func<>` or `Expression<Func<>>`:
```
var l = (int x) => x + 1;
```
All that said, Anthony is right: the compiler will never do the wrong thing, though it might not do what you expect. When in doubt, hover over `var` in VS to see the static type. |
5,738,073 | I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?) | 2011/04/21 | ['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/'] | I don't believe the compiler will *guess the wrong type.* However, it might *infer a type you didn't intend*, but that's not the same.
Consider the perfectly legal
```
decimal foo = 10;
decimal bar = 4;
decimal baz = foo / bar;
```
In the code, `baz` will very clearly be 2.5. The integer literals will be converted to decimals prior to being stored and then the math takes place on the decimal values. Remove the explicit typing and the result is different.
```
var foo = 10;
var bar = 4;
var baz = foo / bar;
```
Now everything infers to int and `baz` is 2 because now the math is taking place with integers.
So, yes, code semantics could theoretically change if you introduce `var` where it was not before. So the key is to understand what type inference is really going to do with your code and if you want something to be a decimal (or any specific type X), declare it in such a way that it will be. For type inference, that would be
```
var foo = 10m;
``` | No, I don't think so. The only time it can't figure things out is if you try to do something like
```
var product = null;
```
Which makes sense, and in this case you get a compile error. |
5,738,073 | I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?) | 2011/04/21 | ['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/'] | No, I don't think so. The only time it can't figure things out is if you try to do something like
```
var product = null;
```
Which makes sense, and in this case you get a compile error. | ```
var x = 0
x = 0.10
```
`Cannot convert source type 'double' to target type 'int'`
An example:
```
double x = 0; //to initialize it
switch (something) {
case condition1:
x = 0.1;
break;
case condition2:
x = 0.2;
break;
}
```
Using `var` instead of `double` will give a compiler error. |
5,738,073 | I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?) | 2011/04/21 | ['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/'] | It won't cause any "issues", regarding code however you could have a regression issue...
```
IObject1
{
void DoSomething();
}
IObject2
{
void DoSomething();
}
var result = SomeMethod();
result.DoSomething();
```
Now, if SomeMethod returned IObject1 and then was changed to return IObject2 this would still compile. ***However***, if you expect DoSomething to execute particular code then this could potentially be a regression issue.
However, if you have
```
IObject1 result = SomeMethod();
```
If the return type of SomeMethod is changed you'll know it right away. | In addition to the ambiguous:
```
var x = null;
```
the compiler will also not infer the type of overloaded method groups:
```
var m = String.Equals;
```
nor will it infer the type of lambda expressions, which can be either `Func<>` or `Expression<Func<>>`:
```
var l = (int x) => x + 1;
```
All that said, Anthony is right: the compiler will never do the wrong thing, though it might not do what you expect. When in doubt, hover over `var` in VS to see the static type. |
5,738,073 | I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?) | 2011/04/21 | ['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/'] | I don't believe the compiler will *guess the wrong type.* However, it might *infer a type you didn't intend*, but that's not the same.
Consider the perfectly legal
```
decimal foo = 10;
decimal bar = 4;
decimal baz = foo / bar;
```
In the code, `baz` will very clearly be 2.5. The integer literals will be converted to decimals prior to being stored and then the math takes place on the decimal values. Remove the explicit typing and the result is different.
```
var foo = 10;
var bar = 4;
var baz = foo / bar;
```
Now everything infers to int and `baz` is 2 because now the math is taking place with integers.
So, yes, code semantics could theoretically change if you introduce `var` where it was not before. So the key is to understand what type inference is really going to do with your code and if you want something to be a decimal (or any specific type X), declare it in such a way that it will be. For type inference, that would be
```
var foo = 10m;
``` | It won't cause any "issues", regarding code however you could have a regression issue...
```
IObject1
{
void DoSomething();
}
IObject2
{
void DoSomething();
}
var result = SomeMethod();
result.DoSomething();
```
Now, if SomeMethod returned IObject1 and then was changed to return IObject2 this would still compile. ***However***, if you expect DoSomething to execute particular code then this could potentially be a regression issue.
However, if you have
```
IObject1 result = SomeMethod();
```
If the return type of SomeMethod is changed you'll know it right away. |
5,738,073 | I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?) | 2011/04/21 | ['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/'] | It won't cause any "issues", regarding code however you could have a regression issue...
```
IObject1
{
void DoSomething();
}
IObject2
{
void DoSomething();
}
var result = SomeMethod();
result.DoSomething();
```
Now, if SomeMethod returned IObject1 and then was changed to return IObject2 this would still compile. ***However***, if you expect DoSomething to execute particular code then this could potentially be a regression issue.
However, if you have
```
IObject1 result = SomeMethod();
```
If the return type of SomeMethod is changed you'll know it right away. | ```
var x = 0
x = 0.10
```
`Cannot convert source type 'double' to target type 'int'`
An example:
```
double x = 0; //to initialize it
switch (something) {
case condition1:
x = 0.1;
break;
case condition2:
x = 0.2;
break;
}
```
Using `var` instead of `double` will give a compiler error. |
5,738,073 | I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?) | 2011/04/21 | ['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/'] | I don't believe the compiler will *guess the wrong type.* However, it might *infer a type you didn't intend*, but that's not the same.
Consider the perfectly legal
```
decimal foo = 10;
decimal bar = 4;
decimal baz = foo / bar;
```
In the code, `baz` will very clearly be 2.5. The integer literals will be converted to decimals prior to being stored and then the math takes place on the decimal values. Remove the explicit typing and the result is different.
```
var foo = 10;
var bar = 4;
var baz = foo / bar;
```
Now everything infers to int and `baz` is 2 because now the math is taking place with integers.
So, yes, code semantics could theoretically change if you introduce `var` where it was not before. So the key is to understand what type inference is really going to do with your code and if you want something to be a decimal (or any specific type X), declare it in such a way that it will be. For type inference, that would be
```
var foo = 10m;
``` | In addition to the ambiguous:
```
var x = null;
```
the compiler will also not infer the type of overloaded method groups:
```
var m = String.Equals;
```
nor will it infer the type of lambda expressions, which can be either `Func<>` or `Expression<Func<>>`:
```
var l = (int x) => x + 1;
```
All that said, Anthony is right: the compiler will never do the wrong thing, though it might not do what you expect. When in doubt, hover over `var` in VS to see the static type. |
5,738,073 | I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?) | 2011/04/21 | ['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/'] | In addition to the ambiguous:
```
var x = null;
```
the compiler will also not infer the type of overloaded method groups:
```
var m = String.Equals;
```
nor will it infer the type of lambda expressions, which can be either `Func<>` or `Expression<Func<>>`:
```
var l = (int x) => x + 1;
```
All that said, Anthony is right: the compiler will never do the wrong thing, though it might not do what you expect. When in doubt, hover over `var` in VS to see the static type. | ```
var x = 0
x = 0.10
```
`Cannot convert source type 'double' to target type 'int'`
An example:
```
double x = 0; //to initialize it
switch (something) {
case condition1:
x = 0.1;
break;
case condition2:
x = 0.2;
break;
}
```
Using `var` instead of `double` will give a compiler error. |
5,738,073 | I know from [this question](https://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) that `var i = 1` and `int i = 1` are exactly the same in IL. The compiler simply replaces `var` with the actual type at compile time. But, are there any instances where `var` could cause problem behavior (maybe the compiler guesses the wrong type?) | 2011/04/21 | ['https://Stackoverflow.com/questions/5738073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/'] | I don't believe the compiler will *guess the wrong type.* However, it might *infer a type you didn't intend*, but that's not the same.
Consider the perfectly legal
```
decimal foo = 10;
decimal bar = 4;
decimal baz = foo / bar;
```
In the code, `baz` will very clearly be 2.5. The integer literals will be converted to decimals prior to being stored and then the math takes place on the decimal values. Remove the explicit typing and the result is different.
```
var foo = 10;
var bar = 4;
var baz = foo / bar;
```
Now everything infers to int and `baz` is 2 because now the math is taking place with integers.
So, yes, code semantics could theoretically change if you introduce `var` where it was not before. So the key is to understand what type inference is really going to do with your code and if you want something to be a decimal (or any specific type X), declare it in such a way that it will be. For type inference, that would be
```
var foo = 10m;
``` | ```
var x = 0
x = 0.10
```
`Cannot convert source type 'double' to target type 'int'`
An example:
```
double x = 0; //to initialize it
switch (something) {
case condition1:
x = 0.1;
break;
case condition2:
x = 0.2;
break;
}
```
Using `var` instead of `double` will give a compiler error. |
4,138 | I'd like to know whether the messages delivered to the ethereum network by my wallet are encrypted such that any identifying information about the wallet is inaccessible to the ISP?
in other words, can ownership of the wallet be traced to me via knowledge of the IP address I'm using at the time of the communication?
I can't seem to find an answer to this anywhere... | 2016/05/21 | ['https://ethereum.stackexchange.com/questions/4138', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/2164/'] | ### No, they cannot trace your IP from the data stored in ethereum network.
Your wallet, if it is Mist, it is actually writing the transaction data to your wn private Ethereum node and then only publishes to the live ethereum network.
So, it is traceable back to you if and only if they are logging all the requests or you have published your wallet address along with postal address somewhere :) | The network is public, messages across it aren't encrypted and your ISP can see the transactions you're sending.
Edit: I'm wrong, see @dbryson's comment. |
4,138 | I'd like to know whether the messages delivered to the ethereum network by my wallet are encrypted such that any identifying information about the wallet is inaccessible to the ISP?
in other words, can ownership of the wallet be traced to me via knowledge of the IP address I'm using at the time of the communication?
I can't seem to find an answer to this anywhere... | 2016/05/21 | ['https://ethereum.stackexchange.com/questions/4138', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/2164/'] | ### No, they cannot trace your IP from the data stored in ethereum network.
Your wallet, if it is Mist, it is actually writing the transaction data to your wn private Ethereum node and then only publishes to the live ethereum network.
So, it is traceable back to you if and only if they are logging all the requests or you have published your wallet address along with postal address somewhere :) | You mention your ISP. If you use a VPN, Tor or I2P you ISP may be able to see that but they cannot see what you are doing on those private networks.
Encryption of your message and the metadata you ask about (ip address, etc) are two separate issues. |
71,493,412 | I have elasticsearch and Kibana are up and running and I want to read logs using logstash so for that I have passed csv file as an input in logstash.conf file but its not reading logs and shutting down automatically.
This is how I am running logstash command:
```
D:\logstash-8.1.0\bin>logstash -f "D:/logstash.conf"
```
**logstash.conf**
```
input{
file{
path => "D:/unicorn.csv"
start_position => beginning
}
}
output{
elasticsearch{
hosts => "localhost:9200"
index => "indexforlogstash"
}
stdout{}
}
```
Below are the terminal output:
```
"Using bundled JDK: ."
OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and
will likely be removed in a future release.
Sending Logstash logs to D:/logstash-8.1.0/logs which is now configured via log4j2.properties
[2022-03-16T12:59:47,905][INFO ][logstash.runner ] Log4j configuration path used is:
D:\logstash-8.1.0\config\log4j2.properties
[2022-03-16T12:59:47,938][WARN ][logstash.runner ] The use of JAVA_HOME has been d
deprecated. Logstash 8.0 and later ignores JAVA_HOME and uses the bundled JDK. Running
Logstash with the bundled JDK is recommended. The bundled JDK has been verified to work with
each specific version of Logstash, and generally provides best performance and reliability. If
you have compelling reasons for using your own JDK (organizational-specific compliance
requirements, for example), you can configure LS_JAVA_HOME to use that version instead.
[2022-03-16T12:59:47,942][INFO ][logstash.runner ] Starting Logstash
{"logstash.version"=>"8.1.0", "jruby.version"=>"jruby 9.2.20.1 (2.5.8) 2021-11-30 2a2962fbd1
OpenJDK 64-Bit Server VM 11.0.13+8 on 11.0.13+8 +indy +jit [mswin32-x86_64]"}
[2022-03-16T12:59:47,947][INFO ][logstash.runner ] JVM bootstrap flags: [-Xms1g, -
Xmx1g, -XX:+UseConcMarkSweepGC, -XX:CMSInitiatingOccupancyFraction=75, -
XX:+UseCMSInitiatingOccupancyOnly, -Djava.awt.headless=true, -Dfile.encoding=UTF-8, -
Djruby.compile.invokedynamic=true, -Djruby.jit.threshold=0, -Djruby.regexp.interruptible=true,
-XX:+HeapDumpOnOutOfMemoryError, -Djava.security.egd=file:/dev/urandom, -
Dlog4j2.isThreadContextMapInheritable=true, --add-opens=java.base/java.security=ALL-UNNAMED, --
add-opens=java.base/java.io=ALL-UNNAMED, --add-opens=java.base/java.nio.channels=ALL-UNNAMED, -
-add-opens=java.base/sun.nio.ch=ALL-UNNAMED, --add-opens=java.management/sun.management=ALL-
UNNAMED]
[2022-03-16T12:59:48,058][INFO ][logstash.settings ] Creating directory
{:setting=>"path.queue", :path=>"D:/logstash-8.1.0/data/queue"}
[2022-03-16T12:59:48,104][INFO ][logstash.settings ] Creating directory
{:setting=>"path.dead_letter_queue", :path=>"D:/logstash-8.1.0/data/dead_letter_queue"}
[2022-03-16T12:59:48,285][WARN ][logstash.config.source.multilocal] Ignoring the
'pipelines.yml' file because modules or command line options are specified
[2022-03-16T12:59:48,347][INFO ][logstash.agent ] No persistent UUID file found.
Generating new UUID {:uuid=>"84410117-2fa7-499b-b55a-43a29192540e", :path=>"D:/logstash-
8.1.0/data/uuid"}
[2022-03-16T12:59:55,063][ERROR][logstash.config.sourceloader] No configuration found in the
configured sources.
[2022-03-16T12:59:55,424][INFO ][logstash.agent ] Successfully started Logstash API
endpoint {:port=>9600, :ssl_enabled=>false}
[2022-03-16T13:00:00,591][INFO ][logstash.runner ] Logstash shut down.
[2022-03-16T13:00:00,609][FATAL][org.logstash.Logstash ] Logstash stopped processing
because of an error: (SystemExit) exit
org.jruby.exceptions.SystemExit: (SystemExit) exit
at org.jruby.RubyKernel.exit(org/jruby/RubyKernel.java:747) ~[jruby.jar:?]
at org.jruby.RubyKernel.exit(org/jruby/RubyKernel.java:710) ~[jruby.jar:?]
at D_3a_.logstash_minus_8_dot_1_dot_0.lib.bootstrap.environment.<main>(D:\logstash-
8.1.0\lib\bootstrap\environment.rb:94) ~[?:?]
```
Someone let me know what I am doing wrong. | 2022/03/16 | ['https://Stackoverflow.com/questions/71493412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7780102/'] | It's actually very simple. Since you use `&&` as an operator, gcc can deduce that the condition always yields false.
If you use the bitwise and operator (`&`), gcc adds code for the if:
```
#include <stdio.h>
unsigned char c = 0xff;
int n = 1;
int main(){
if ((c & 0xc0) == 0xc0 ) {
n=0;
}
printf("%d\n", n);
}
```
yields:
```
ronald@oncilla:~/tmp$ cc -S x.c && cat x.s
.file "x.c"
.text
.globl c
.data
.type c, @object
.size c, 1
c:
.byte -1
.globl n
.align 4
.type n, @object
.size n, 4
n:
.long 1
.section .rodata
.LC0:
.string "%d\n"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
endbr64
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movzbl c(%rip), %eax
movzbl %al, %eax
andl $192, %eax
cmpl $192, %eax
jne .L2
movl $0, n(%rip)
.L2:
movl n(%rip), %eax
movl %eax, %esi
leaq .LC0(%rip), %rdi
movl $0, %eax
call printf@PLT
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0"
.section .note.GNU-stack,"",@progbits
.section .note.gnu.property,"a"
.align 8
.long 1f - 0f
.long 4f - 1f
.long 5
0:
.string "GNU"
1:
.align 8
.long 0xc0000002
.long 3f - 2f
2:
.long 0x3
3:
.align 8
4:
``` | In C `&&` casts operands to `bool` which even though its an `int`, it is changed to 1 meaning true, if nonzero.
`&` is a bitwise and, which returns the bits that are the same. If you combine this with `&&` it returns true if there are any bits left.
If you compile with `-Wall` you will get a warning when something gets optimized out at compile time. |
33,264,891 | I'm a new baby in Dapper. Trying to incorporate CRUD operations with Dapper and Dapper.SimpleCRUD lib. Here is the sample code...
My Data Model Looks like
```
Class Product
{
public string prodId {get;set;}
public string prodName {get;set;}
public string Location {get;set;}
}
```
Dapper Implementation - Insert
```
public void Insert(Product item)
{
using(var con = GetConnection())
{
con.Insert(item);
}
}
```
Since the ProdId in the Db is an Identity Column it fails. How does it indicate ProdId is an Identity Column in DB?
Dapper Implementation - Get
```
public IEnumerable<Product> GetAll()
{
IEnumerable<Product> item = null;
using (var con = GetConnection())
{
item = con.GetList<Product>();
}
return item;
}
```
It gives an exception:
>
> "Entity must have at least one [Key] property"!
>
>
> | 2015/10/21 | ['https://Stackoverflow.com/questions/33264891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2066540/'] | This is happening since you are using a Dapper Extension, which has implemented the `Insert` CRUD extension method. Ideally this can be achieved using simple
`con.Execute` in the Dapper, but since you want to pass an object and create an insert query automatically by the extension, you need to help it understand, which is the Primary Key for the given product entity, following modification shall help:
```
[Key]
public string prodId {get;set;}
```
where Key attribute shall be either implemented in `Dapper Extension` or the `Component Model`.
Alternatively you may rename `prodId` to `Id`, which will automatically make it the key. Also check the following [link](http://rnsx.co.uk/an-introduction-to-dapper-extensions/), where you can create a separate mapper for the entity, thus defining the key, whatever works in your case | Connecting to SQL Server 2016, I had this error with both Dapper.Contrib & Dapper.SimpleCRUD when I forgot to attach the Primary Key to the Id column of the table.
Primary Key added to the table, project rebuilt & published to clear cache and all is good with both [Key] & [ExplicitKey] ( the latter in DapperContrib). |
321,083 | I've got [DavMail](http://davmail.sourceforge.net/) running in Linux Mint so Thunderbird can access IMAP/SMTP/LDAP/CalDav. I've got everything working at this point except LDAP. Basically I can't figure out what the base DN should be. Where on my Windows XP box can I find this? I've tried a few things, and the address book always shows up blank once I add the LDAP server. | 2011/08/09 | ['https://superuser.com/questions/321083', 'https://superuser.com', 'https://superuser.com/users/75269/'] | The "Base DN" when adding a new LDAP directory in Thunderbird should be `ou=people` as specified on [this page](http://davmail.sourceforge.net/thunderbirddirectorysetup.html) [davmail.sourceforge.net].
Contrary to what the screenshot in those instructions shows (in French, no less), your "Bind DN" should might actually be **your email address**. At least this was the case for me, with the educational ("Live@edu") version of Office365.
Also, not sure if this is worth mentioning, but I did have a really annoying problem with Thunderbird on Mac OS X which caused me to think that the LDAP lookup wasn't working at all: the dialog box which prompted for the password (to access the DavMail server) got stuck **under** a bunch of other windows, **and** on the wrong virtual desktop (I believe Apple calls these "Spaces"). Once I "discovered" the password prompt and gave it my OWA password, LDAP lookups in the addressbook with Shift + ⌘ + F worked just fine. | The `base object` for searches is something that your directory server administrator tells you. It might be possible to discover the `namingContext` of the directory server if you know the hostname and port upon which the server listens by querying the root DSE. See *[The root DSE](http://bit.ly/osZXFG)* for more information.
The information regarding the `namingContext` might be protected by access control, in which case you must get the name of the `base object` from the directory server administrator. The directory server might master or shadow multiple naming contexts, in which case you must get the name of the `base object` from the directory server administrator. |
9,389,381 | In order to demonstrate the security feature of Oracle one has to call **OCIServerVersion()** or **OCIServerRelease()** when the user session has not yet been established.
While having the database parameter `sec_return_server_release_banner = false`.
I am using Python cx\_Oracle module for this, but I am not sure how to get the server version before establishing the connection. Any ideas? | 2012/02/22 | ['https://Stackoverflow.com/questions/9389381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1224977/'] | If you want the snapshot, make sure you have the repository tags for it as well, for wherever you are getting that build from. Otherwise use the latest release, `3.0.0-beta3`.
If you are building your own local copies, or deploying to an internal repo, then 3.0.0-SNAPSHOT should work - make sure the jar can be found in your repo, and that you aren't running as offline. | GXT 3.0.1 is on maven central
```
<dependency>
<groupId>com.sencha.gxt</groupId>
<artifactId>gxt</artifactId>
<version>3.0.1</version>
</dependency>
``` |
9,389,381 | In order to demonstrate the security feature of Oracle one has to call **OCIServerVersion()** or **OCIServerRelease()** when the user session has not yet been established.
While having the database parameter `sec_return_server_release_banner = false`.
I am using Python cx\_Oracle module for this, but I am not sure how to get the server version before establishing the connection. Any ideas? | 2012/02/22 | ['https://Stackoverflow.com/questions/9389381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1224977/'] | If you want the snapshot, make sure you have the repository tags for it as well, for wherever you are getting that build from. Otherwise use the latest release, `3.0.0-beta3`.
If you are building your own local copies, or deploying to an internal repo, then 3.0.0-SNAPSHOT should work - make sure the jar can be found in your repo, and that you aren't running as offline. | Use these dependencies:
```
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-servlet</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.sencha.gxt</groupId>
<artifactId>gxt</artifactId>
<version>3.0.1</version>
</dependency>
```
GXT does not require `uibinder-bridge` anymore [according to Sencha forum](http://www.sencha.com/forum/showthread.php?246246-uibinder-bridge-for-GWT-2.5.0).
All GXT uibinder features were incorporated into GWT 2.5.0 release. |
9,389,381 | In order to demonstrate the security feature of Oracle one has to call **OCIServerVersion()** or **OCIServerRelease()** when the user session has not yet been established.
While having the database parameter `sec_return_server_release_banner = false`.
I am using Python cx\_Oracle module for this, but I am not sure how to get the server version before establishing the connection. Any ideas? | 2012/02/22 | ['https://Stackoverflow.com/questions/9389381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1224977/'] | Use these dependencies:
```
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-servlet</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.sencha.gxt</groupId>
<artifactId>gxt</artifactId>
<version>3.0.1</version>
</dependency>
```
GXT does not require `uibinder-bridge` anymore [according to Sencha forum](http://www.sencha.com/forum/showthread.php?246246-uibinder-bridge-for-GWT-2.5.0).
All GXT uibinder features were incorporated into GWT 2.5.0 release. | GXT 3.0.1 is on maven central
```
<dependency>
<groupId>com.sencha.gxt</groupId>
<artifactId>gxt</artifactId>
<version>3.0.1</version>
</dependency>
``` |
40,585,550 | i want a make a feed reader...i want load politics news from multiple data dource in one tableview synchronously.
what do i do?
i went to this link: [table view with multiple data sources/nibs](https://stackoverflow.com/questions/35960403/ios-swift-table-view-with-multiple-data-sources-nibs)
but this solution is not synchronously
So basically what should be the approach when we have multiple data source but single instance of table view to show the data? | 2016/11/14 | ['https://Stackoverflow.com/questions/40585550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6856597/'] | you are sorting from the older to the newer date which is ok,
if you need upside down then do invert the comparation criteria by doing:
```
return date2.compareTo(date1);
```
another way to go is inverte the sorted list...
1st sort then do `Collections.reverse();`
Edit:
=====
I try your code and the reason is the format is not well defined, therefore the dates are wrong
try this:
```
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(o1);
date2 = format.parse(o2);
} catch (ParseException e) {
e.printStackTrace();
}
return date2.compareTo(date1);
``` | In java 8 you can write it in this way..
Please note that I have used apache CompareToBuilder.
```
Collections.sort(opportunities,
Collections.reverseOrder((item1, item2) -> new CompareToBuilder()
.append(item1.getExpires(), item2.getExpires()).toComparison()));
``` |
40,585,550 | i want a make a feed reader...i want load politics news from multiple data dource in one tableview synchronously.
what do i do?
i went to this link: [table view with multiple data sources/nibs](https://stackoverflow.com/questions/35960403/ios-swift-table-view-with-multiple-data-sources-nibs)
but this solution is not synchronously
So basically what should be the approach when we have multiple data source but single instance of table view to show the data? | 2016/11/14 | ['https://Stackoverflow.com/questions/40585550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6856597/'] | Because format "YYYY" in your `DateFormat`
Change `MM/DD/YYYY` to `MM/DD/yyyy` will work | you are sorting from the older to the newer date which is ok,
if you need upside down then do invert the comparation criteria by doing:
```
return date2.compareTo(date1);
```
another way to go is inverte the sorted list...
1st sort then do `Collections.reverse();`
Edit:
=====
I try your code and the reason is the format is not well defined, therefore the dates are wrong
try this:
```
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(o1);
date2 = format.parse(o2);
} catch (ParseException e) {
e.printStackTrace();
}
return date2.compareTo(date1);
``` |
40,585,550 | i want a make a feed reader...i want load politics news from multiple data dource in one tableview synchronously.
what do i do?
i went to this link: [table view with multiple data sources/nibs](https://stackoverflow.com/questions/35960403/ios-swift-table-view-with-multiple-data-sources-nibs)
but this solution is not synchronously
So basically what should be the approach when we have multiple data source but single instance of table view to show the data? | 2016/11/14 | ['https://Stackoverflow.com/questions/40585550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6856597/'] | Because format "YYYY" in your `DateFormat`
Change `MM/DD/YYYY` to `MM/DD/yyyy` will work | In java 8 you can write it in this way..
Please note that I have used apache CompareToBuilder.
```
Collections.sort(opportunities,
Collections.reverseOrder((item1, item2) -> new CompareToBuilder()
.append(item1.getExpires(), item2.getExpires()).toComparison()));
``` |
61,689,419 | I am trying to find the max and min of a line of text from a data file. Though there is plenty of lines of text in this data file.
**DATA**
```
-99 1 2 3 4 5 6 7 8 9 10 12345
10 9 8 7 6 5 4 3 2 1 -99
10 20 30 40 50 -11818 40 30 20 10
32767
255 255
9 10 -88 100 -555 1000
10 10 10 11 456
-111 1 2 3 9 11 20 30
9 8 7 6 5 4 3 2 0 -2 -989
12 15 18 21 23 1000
250 19 17 15 13 11 10 9 6 3 2 1 -455
9 10 -8 10000 -5000 1000
```
I have tried turning the lines into arrays and that has got me somewhere.
**HERE IS MY CODE**
```
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
// It is called "Average". Don't mind that.
public class Average
{
public static void main(String[] args) throws IOException
{
Scanner file = new Scanner(new File("average.dat"));
String[] array = null;
while(file.hasNextLine())
{
//Storing the ints from the data file into an array.
String line = file.nextLine();
String[] str = line.split("\\s+");
array = new String[str.length];
for (int i = 0; i < str.length; i++){
array[i] = (str[i]);
}
System.out.println("Max:" + Average.getMax(array));
System.out.println("Min:" + Average.getMin(array));
System.out.println();
}
}
//Simple way of getting max value. Nabbed it off google.
public static String getMax(String[] inputArray)
{
String maxValue = inputArray[0];
for(int i=1;i < inputArray.length;i++){
if(inputArray[i].compareTo(maxValue)>0){
maxValue = inputArray[i];
}
}
return maxValue;
}
//Simple way of getting min value. Took off google as well.
public static String getMin(String[] inputArray){
String minValue = inputArray[0];
for(int i=1;i<inputArray.length;i++){
if(inputArray[i].compareTo(minValue)<0){
minValue = inputArray[i];
}
}
return minValue;
}
}
```
**HERE IS MY OUTPUT**
```
Max:9
Min:-99
Max:9
Min:-99
Max:50
Min:-11818
Max:32767
Min:32767
Max:255
Min:255
Max:9
Min:-555
Max:456
Min:10
Max:9
Min:-111
Max:9
Min:-2
Max:23
Min:1000
Max:9
Min:-455
Max:9
Min:-5000
```
As you can see, the minimum value is correct. Though, the max value is not? It gives me 9 for no reason on some and I do not know why. You may ask "Why didn't you just make the array an int[] instead of a String[]?" I don't know how to copy the ints from the data file into an integer array. I only really know how to do it with a String array. Does anyone know the right way to do this? | 2020/05/08 | ['https://Stackoverflow.com/questions/61689419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11991346/'] | You can compare using int
```
public static String getMax(String[] inputArray) {
int maxValue = Integer.MIN_VALUE;
for(int i = 0; i < inputArray.length; i++) {
if(maxValue < Integer.parseInt(inputArray[i])){
maxValue = Integer.parseInt(inputArray[i]);
}
}
return String.valueOf(maxValue);
}
public static String getMin(String[] inputArray) {
int minValue = Integer.MAX_VALUE;
for(int i = 0; i < inputArray.length; i++) {
if(minValue > Integer.parseInt(inputArray[i])){
minValue = Integer.parseInt(inputArray[i]);
}
}
return String.valueOf(minValue);
}
``` | You should use: Integer.pharseToInt()
Then when you'll have an array of integers and you can find the max value easily:
```
int getMax(int [] array){
int max = INTEGER.MIN_VALUE;
for (int i=0: i<array.length; i++)
if (array[i]>max)
max = array[i];
return max;
}
```
Totally symetric function for finding min value. |
61,689,419 | I am trying to find the max and min of a line of text from a data file. Though there is plenty of lines of text in this data file.
**DATA**
```
-99 1 2 3 4 5 6 7 8 9 10 12345
10 9 8 7 6 5 4 3 2 1 -99
10 20 30 40 50 -11818 40 30 20 10
32767
255 255
9 10 -88 100 -555 1000
10 10 10 11 456
-111 1 2 3 9 11 20 30
9 8 7 6 5 4 3 2 0 -2 -989
12 15 18 21 23 1000
250 19 17 15 13 11 10 9 6 3 2 1 -455
9 10 -8 10000 -5000 1000
```
I have tried turning the lines into arrays and that has got me somewhere.
**HERE IS MY CODE**
```
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
// It is called "Average". Don't mind that.
public class Average
{
public static void main(String[] args) throws IOException
{
Scanner file = new Scanner(new File("average.dat"));
String[] array = null;
while(file.hasNextLine())
{
//Storing the ints from the data file into an array.
String line = file.nextLine();
String[] str = line.split("\\s+");
array = new String[str.length];
for (int i = 0; i < str.length; i++){
array[i] = (str[i]);
}
System.out.println("Max:" + Average.getMax(array));
System.out.println("Min:" + Average.getMin(array));
System.out.println();
}
}
//Simple way of getting max value. Nabbed it off google.
public static String getMax(String[] inputArray)
{
String maxValue = inputArray[0];
for(int i=1;i < inputArray.length;i++){
if(inputArray[i].compareTo(maxValue)>0){
maxValue = inputArray[i];
}
}
return maxValue;
}
//Simple way of getting min value. Took off google as well.
public static String getMin(String[] inputArray){
String minValue = inputArray[0];
for(int i=1;i<inputArray.length;i++){
if(inputArray[i].compareTo(minValue)<0){
minValue = inputArray[i];
}
}
return minValue;
}
}
```
**HERE IS MY OUTPUT**
```
Max:9
Min:-99
Max:9
Min:-99
Max:50
Min:-11818
Max:32767
Min:32767
Max:255
Min:255
Max:9
Min:-555
Max:456
Min:10
Max:9
Min:-111
Max:9
Min:-2
Max:23
Min:1000
Max:9
Min:-455
Max:9
Min:-5000
```
As you can see, the minimum value is correct. Though, the max value is not? It gives me 9 for no reason on some and I do not know why. You may ask "Why didn't you just make the array an int[] instead of a String[]?" I don't know how to copy the ints from the data file into an integer array. I only really know how to do it with a String array. Does anyone know the right way to do this? | 2020/05/08 | ['https://Stackoverflow.com/questions/61689419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11991346/'] | Compact solution with comments and explanations:
```
public static void main(String[] args) {
// Create an input stream
try (Stream<String> stream = Files.lines(Paths.get("average.dat"))) {
// Get each line from the stream
stream.forEach(line -> {
// Cut the line into peaces
String[] numbers = line.split(" ");
// Create a list of integers from the pieces
List<Integer> integers = Arrays.stream(numbers).map(Integer::parseInt).collect(Collectors.toList());
// Calculate max
System.out.println("Max:" + integers.stream().flatMapToInt(IntStream::of).max().orElseThrow());
// Calculate min
System.out.println("Min:" + integers.stream().flatMapToInt(IntStream::of).min().orElseThrow());
// Ouput a new line
System.out.println();
});
} catch (IOException e) {
e.printStackTrace();
}
``` | You should use: Integer.pharseToInt()
Then when you'll have an array of integers and you can find the max value easily:
```
int getMax(int [] array){
int max = INTEGER.MIN_VALUE;
for (int i=0: i<array.length; i++)
if (array[i]>max)
max = array[i];
return max;
}
```
Totally symetric function for finding min value. |
61,689,419 | I am trying to find the max and min of a line of text from a data file. Though there is plenty of lines of text in this data file.
**DATA**
```
-99 1 2 3 4 5 6 7 8 9 10 12345
10 9 8 7 6 5 4 3 2 1 -99
10 20 30 40 50 -11818 40 30 20 10
32767
255 255
9 10 -88 100 -555 1000
10 10 10 11 456
-111 1 2 3 9 11 20 30
9 8 7 6 5 4 3 2 0 -2 -989
12 15 18 21 23 1000
250 19 17 15 13 11 10 9 6 3 2 1 -455
9 10 -8 10000 -5000 1000
```
I have tried turning the lines into arrays and that has got me somewhere.
**HERE IS MY CODE**
```
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
// It is called "Average". Don't mind that.
public class Average
{
public static void main(String[] args) throws IOException
{
Scanner file = new Scanner(new File("average.dat"));
String[] array = null;
while(file.hasNextLine())
{
//Storing the ints from the data file into an array.
String line = file.nextLine();
String[] str = line.split("\\s+");
array = new String[str.length];
for (int i = 0; i < str.length; i++){
array[i] = (str[i]);
}
System.out.println("Max:" + Average.getMax(array));
System.out.println("Min:" + Average.getMin(array));
System.out.println();
}
}
//Simple way of getting max value. Nabbed it off google.
public static String getMax(String[] inputArray)
{
String maxValue = inputArray[0];
for(int i=1;i < inputArray.length;i++){
if(inputArray[i].compareTo(maxValue)>0){
maxValue = inputArray[i];
}
}
return maxValue;
}
//Simple way of getting min value. Took off google as well.
public static String getMin(String[] inputArray){
String minValue = inputArray[0];
for(int i=1;i<inputArray.length;i++){
if(inputArray[i].compareTo(minValue)<0){
minValue = inputArray[i];
}
}
return minValue;
}
}
```
**HERE IS MY OUTPUT**
```
Max:9
Min:-99
Max:9
Min:-99
Max:50
Min:-11818
Max:32767
Min:32767
Max:255
Min:255
Max:9
Min:-555
Max:456
Min:10
Max:9
Min:-111
Max:9
Min:-2
Max:23
Min:1000
Max:9
Min:-455
Max:9
Min:-5000
```
As you can see, the minimum value is correct. Though, the max value is not? It gives me 9 for no reason on some and I do not know why. You may ask "Why didn't you just make the array an int[] instead of a String[]?" I don't know how to copy the ints from the data file into an integer array. I only really know how to do it with a String array. Does anyone know the right way to do this? | 2020/05/08 | ['https://Stackoverflow.com/questions/61689419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11991346/'] | Actually, you don't need to compute the max and min separately. Consider the following:
* set the max and min to the first value.
* Check to see if the value is a `max`, if so, assign it to `max`.
* other wise, just compare to min and assign as appropriate.
```
while (file.hasNextLine()) {
// Storing the ints from the data file into an array.
String[] str = file.nextLine().split("\\s+");
int max = Integer.parseInt(str[0]);
int min = max;
for (int i = 1; i < str.length; i++) {
int v = Integer.parseInt(str[i]);
if (v > max) {
max = v;
} else if (v < min) {
min = v;
}
}
System.out.println("Max:" + max);
System.out.println("Min:" + min);
System.out.println();
}
``` | You should use: Integer.pharseToInt()
Then when you'll have an array of integers and you can find the max value easily:
```
int getMax(int [] array){
int max = INTEGER.MIN_VALUE;
for (int i=0: i<array.length; i++)
if (array[i]>max)
max = array[i];
return max;
}
```
Totally symetric function for finding min value. |
14,576 | for typesetting tables with design of experiments, I have to typeset strings like "+ - + +", - - - +", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain "a", "A" and "0" (zero)).
However, the width of the "+" and "-" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash....
So I'm searching for a way to easily typeset e. g. "+ - - - + -" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters ("+" or "-", "a", "A" and "0") would be aligned with each other, when they are in the same column of a table.
I hope I could make clear what I need, some examples how it shall NOT look are found here:
![bad example](https://i.stack.imgur.com/YZkQH.png)
in line 9 it should be "+ - -" and in 10 "- - +", line 5 should be "- - -"
It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned:
![enter image description here](https://i.stack.imgur.com/dC5x3.png)
Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns...
Does anybody have an idea how to solve that?
Maybe a command that parses the string like --+--++ and typesets it with a "constant spacing"?
------- edit:
added math mode for "+" and "-", looks better now, but not perfect:
![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png)
```
\documentclass[11pt, a4paper%, halfparskip
]{scrreprt}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{cccccccc}
\midrule
1 & $+$$+$$-$ \\
2 & $+$$-$$+$ \\
3 & $-$$+$$+$ \\
4 & 000 \\
5 & $-$$-$$-$ \\
6 & 000 \\
\midrule
7 & $-$$+$$-$ \\
8 & 000 \\
9 & $+$$-$$-$ \\
10 & $-$$-$$+$ \\
11 & $+$$+$$+$ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
```
---
example and further question about side-effects:
I used the solution of Michel and it looks good, but there is one thing I'm not sure about:
Is it possible that it changes the free space between columns?
I have the impression that the first 3 columns are closer together than the rest...
How can I fix that?
![solution with side effects?!](https://i.stack.imgur.com/25OVA.png) | 2011/03/30 | ['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/'] | Make sure you typeset them it **math-mode**, i.e. `$-$` and `$+$`.
Be aware that it makes a difference if you use a single math-mode or separate ones for them. The last sign has different spacing in the first case because it
is taken as an unary sign but the others are operators.
Compare the following:
```
\documentclass{article}
\begin{document}
$-$$-$$-$$+$$+$$+$
$+$$+$$+$$+$$+$$+$
$-$$-$$-$$-$$-$$-$
$---+++$
$++++++$
$------$
\end{document}
```
### Result:
![Result](https://i.stack.imgur.com/8AnbD.png)
---
For the alignment with the other signs `a`, `A` and `0` I would recommend that you make macros for all and set the width manually the one of the widest (should be `$+$`).
This can be done either with `\hbox to <length>{\hss <sign>\hss}` (TeX) or using `\makebox[<length>][c]{<sign>}` (LaTeX). The width is provided by `\settowidth{<length register>}{<content>}`.
```
\documentclass[11pt, a4paper]{scrreprt}
\usepackage{booktabs}
\newlength{\slength}
\settowidth{\slength}{$+$}
\newcommand*{\Sz}{\makebox[\slength][c]{0}}
\newcommand*{\SA}{\makebox[\slength][c]{A}}
\newcommand*{\Sa}{\makebox[\slength][c]{a}}
\newcommand*{\Sp}{\makebox[\slength][c]{$+$}}
\newcommand*{\Sm}{\makebox[\slength][c]{$-$}}
\begin{document}
\begin{tabular}{cc}
\toprule
1 & \Sp\Sp\Sm \\
2 & \Sp\Sm\Sp \\
3 & \Sm\Sp\Sp \\
4 & \Sz\Sz\Sz \\
5 & \Sm\Sm\Sm \\
6 & \Sz\Sz\Sz \\
\midrule
7 & \Sm\Sp\Sm \\
8 & \Sz\Sz\Sz \\
9 & \Sp\Sm\Sm \\
10 & \Sm\Sm\Sp \\
11 & \Sp\Sp\Sp \\
12 & \Sz\Sz\Sz \\
\midrule
13 & \Sz\Sz\Sz \\
14 & \Sz\Sz\Sa \\
15 & \Sz\Sz\SA \\
16 & \Sz\SA\Sz \\
17 & \SA\Sz\Sz \\
18 & \Sz\Sa\Sz \\
19 & \Sa\Sz\Sz \\
20 & \Sz\Sz\Sz \\
\bottomrule
\end{tabular}
\end{document}
```
### Result:
![Result 2](https://i.stack.imgur.com/1d879.png) | one possible form to typeset your table would be to use a table column for each character:
```
\documentclass[11pt, a4paper]{scrreprt}
\usepackage{booktabs}
\newcommand\Pl{${}+{}$}
\newcommand\Mi{${}-{}$}
\begin{document}
\begin{tabular}{cc@{\hspace{-2pt}}c@{\hspace{-2pt}}c}
\toprule
1 & \Pl & \Pl & \Mi \\
4 & 0 & 0 & 0 \\
12 & a & 0 & A \\
15 & 0 & 0 & A \\
\bottomrule
\end{tabular}
\end{document}
```
![](https://i.stack.imgur.com/RxGDb.png) |
14,576 | for typesetting tables with design of experiments, I have to typeset strings like "+ - + +", - - - +", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain "a", "A" and "0" (zero)).
However, the width of the "+" and "-" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash....
So I'm searching for a way to easily typeset e. g. "+ - - - + -" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters ("+" or "-", "a", "A" and "0") would be aligned with each other, when they are in the same column of a table.
I hope I could make clear what I need, some examples how it shall NOT look are found here:
![bad example](https://i.stack.imgur.com/YZkQH.png)
in line 9 it should be "+ - -" and in 10 "- - +", line 5 should be "- - -"
It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned:
![enter image description here](https://i.stack.imgur.com/dC5x3.png)
Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns...
Does anybody have an idea how to solve that?
Maybe a command that parses the string like --+--++ and typesets it with a "constant spacing"?
------- edit:
added math mode for "+" and "-", looks better now, but not perfect:
![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png)
```
\documentclass[11pt, a4paper%, halfparskip
]{scrreprt}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{cccccccc}
\midrule
1 & $+$$+$$-$ \\
2 & $+$$-$$+$ \\
3 & $-$$+$$+$ \\
4 & 000 \\
5 & $-$$-$$-$ \\
6 & 000 \\
\midrule
7 & $-$$+$$-$ \\
8 & 000 \\
9 & $+$$-$$-$ \\
10 & $-$$-$$+$ \\
11 & $+$$+$$+$ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
```
---
example and further question about side-effects:
I used the solution of Michel and it looks good, but there is one thing I'm not sure about:
Is it possible that it changes the free space between columns?
I have the impression that the first 3 columns are closer together than the rest...
How can I fix that?
![solution with side effects?!](https://i.stack.imgur.com/25OVA.png) | 2011/03/30 | ['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/'] | An easy way to achieve this would be to typeset the plusses and minuses in a monospace font with `\verb|+-+-|`
There are however [issues](https://tex.stackexchange.com/q/203/215) with verbatim text which you might run into...
Another solution might be to use `\texttt` and macros for your plusses etc. Here's an example:
```
\documentclass{article}
\usepackage[T1]{fontenc}
\newcommand\p{+}
\newcommand\m{-{}}
\begin{document}
\texttt{++---++}
\texttt{\p\p\m\m\m\p\p}
\texttt{++\m\m aA0}
\end{document}
```
You need to use a macro like this for the minus sign because otherwise they get turned into en-dashes if you use the `fontenc` package. This should also mono-space letters easily. | A quick and dirty solution might be to enclose the symbols in braces: `${-}{+}{+}{+}$` looks better than `$-+++$`, as LaTeX won't try to interpret each `+` or `-` as a binary operator. |
14,576 | for typesetting tables with design of experiments, I have to typeset strings like "+ - + +", - - - +", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain "a", "A" and "0" (zero)).
However, the width of the "+" and "-" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash....
So I'm searching for a way to easily typeset e. g. "+ - - - + -" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters ("+" or "-", "a", "A" and "0") would be aligned with each other, when they are in the same column of a table.
I hope I could make clear what I need, some examples how it shall NOT look are found here:
![bad example](https://i.stack.imgur.com/YZkQH.png)
in line 9 it should be "+ - -" and in 10 "- - +", line 5 should be "- - -"
It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned:
![enter image description here](https://i.stack.imgur.com/dC5x3.png)
Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns...
Does anybody have an idea how to solve that?
Maybe a command that parses the string like --+--++ and typesets it with a "constant spacing"?
------- edit:
added math mode for "+" and "-", looks better now, but not perfect:
![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png)
```
\documentclass[11pt, a4paper%, halfparskip
]{scrreprt}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{cccccccc}
\midrule
1 & $+$$+$$-$ \\
2 & $+$$-$$+$ \\
3 & $-$$+$$+$ \\
4 & 000 \\
5 & $-$$-$$-$ \\
6 & 000 \\
\midrule
7 & $-$$+$$-$ \\
8 & 000 \\
9 & $+$$-$$-$ \\
10 & $-$$-$$+$ \\
11 & $+$$+$$+$ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
```
---
example and further question about side-effects:
I used the solution of Michel and it looks good, but there is one thing I'm not sure about:
Is it possible that it changes the free space between columns?
I have the impression that the first 3 columns are closer together than the rest...
How can I fix that?
![solution with side effects?!](https://i.stack.imgur.com/25OVA.png) | 2011/03/30 | ['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/'] | Make sure you typeset them it **math-mode**, i.e. `$-$` and `$+$`.
Be aware that it makes a difference if you use a single math-mode or separate ones for them. The last sign has different spacing in the first case because it
is taken as an unary sign but the others are operators.
Compare the following:
```
\documentclass{article}
\begin{document}
$-$$-$$-$$+$$+$$+$
$+$$+$$+$$+$$+$$+$
$-$$-$$-$$-$$-$$-$
$---+++$
$++++++$
$------$
\end{document}
```
### Result:
![Result](https://i.stack.imgur.com/8AnbD.png)
---
For the alignment with the other signs `a`, `A` and `0` I would recommend that you make macros for all and set the width manually the one of the widest (should be `$+$`).
This can be done either with `\hbox to <length>{\hss <sign>\hss}` (TeX) or using `\makebox[<length>][c]{<sign>}` (LaTeX). The width is provided by `\settowidth{<length register>}{<content>}`.
```
\documentclass[11pt, a4paper]{scrreprt}
\usepackage{booktabs}
\newlength{\slength}
\settowidth{\slength}{$+$}
\newcommand*{\Sz}{\makebox[\slength][c]{0}}
\newcommand*{\SA}{\makebox[\slength][c]{A}}
\newcommand*{\Sa}{\makebox[\slength][c]{a}}
\newcommand*{\Sp}{\makebox[\slength][c]{$+$}}
\newcommand*{\Sm}{\makebox[\slength][c]{$-$}}
\begin{document}
\begin{tabular}{cc}
\toprule
1 & \Sp\Sp\Sm \\
2 & \Sp\Sm\Sp \\
3 & \Sm\Sp\Sp \\
4 & \Sz\Sz\Sz \\
5 & \Sm\Sm\Sm \\
6 & \Sz\Sz\Sz \\
\midrule
7 & \Sm\Sp\Sm \\
8 & \Sz\Sz\Sz \\
9 & \Sp\Sm\Sm \\
10 & \Sm\Sm\Sp \\
11 & \Sp\Sp\Sp \\
12 & \Sz\Sz\Sz \\
\midrule
13 & \Sz\Sz\Sz \\
14 & \Sz\Sz\Sa \\
15 & \Sz\Sz\SA \\
16 & \Sz\SA\Sz \\
17 & \SA\Sz\Sz \\
18 & \Sz\Sa\Sz \\
19 & \Sa\Sz\Sz \\
20 & \Sz\Sz\Sz \\
\bottomrule
\end{tabular}
\end{document}
```
### Result:
![Result 2](https://i.stack.imgur.com/1d879.png) | An easy way to achieve this would be to typeset the plusses and minuses in a monospace font with `\verb|+-+-|`
There are however [issues](https://tex.stackexchange.com/q/203/215) with verbatim text which you might run into...
Another solution might be to use `\texttt` and macros for your plusses etc. Here's an example:
```
\documentclass{article}
\usepackage[T1]{fontenc}
\newcommand\p{+}
\newcommand\m{-{}}
\begin{document}
\texttt{++---++}
\texttt{\p\p\m\m\m\p\p}
\texttt{++\m\m aA0}
\end{document}
```
You need to use a macro like this for the minus sign because otherwise they get turned into en-dashes if you use the `fontenc` package. This should also mono-space letters easily. |
14,576 | for typesetting tables with design of experiments, I have to typeset strings like "+ - + +", - - - +", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain "a", "A" and "0" (zero)).
However, the width of the "+" and "-" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash....
So I'm searching for a way to easily typeset e. g. "+ - - - + -" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters ("+" or "-", "a", "A" and "0") would be aligned with each other, when they are in the same column of a table.
I hope I could make clear what I need, some examples how it shall NOT look are found here:
![bad example](https://i.stack.imgur.com/YZkQH.png)
in line 9 it should be "+ - -" and in 10 "- - +", line 5 should be "- - -"
It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned:
![enter image description here](https://i.stack.imgur.com/dC5x3.png)
Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns...
Does anybody have an idea how to solve that?
Maybe a command that parses the string like --+--++ and typesets it with a "constant spacing"?
------- edit:
added math mode for "+" and "-", looks better now, but not perfect:
![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png)
```
\documentclass[11pt, a4paper%, halfparskip
]{scrreprt}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{cccccccc}
\midrule
1 & $+$$+$$-$ \\
2 & $+$$-$$+$ \\
3 & $-$$+$$+$ \\
4 & 000 \\
5 & $-$$-$$-$ \\
6 & 000 \\
\midrule
7 & $-$$+$$-$ \\
8 & 000 \\
9 & $+$$-$$-$ \\
10 & $-$$-$$+$ \\
11 & $+$$+$$+$ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
```
---
example and further question about side-effects:
I used the solution of Michel and it looks good, but there is one thing I'm not sure about:
Is it possible that it changes the free space between columns?
I have the impression that the first 3 columns are closer together than the rest...
How can I fix that?
![solution with side effects?!](https://i.stack.imgur.com/25OVA.png) | 2011/03/30 | ['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/'] | ```
\documentclass{minimal}
\begin{document}
\setlength{\parindent}{0pt}
\newlength{\stretchlen}\setlength{\stretchlen}{1em}
\def\splitterm{\_}
\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_}
\def\realstretch#1{%
\def\temp{#1}%
\ifx\temp\splitterm
\else
\hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch
\fi}
\stretchit{abcd}\par
\stretchit{----}\par
\stretchit{++++}\par
\stretchit{-+-+}\par
\stretchit{0aA+}\par
\end{document}
```
`\stretchit` appends an underscore to its argument and passes it to `\realstretch`, which recursively 'eats' one letter at a time, and typesets it centered in an `\hbox` stretched to `\stretchlen`. All letters are thus equally wide, and since they are centered, aligned nicely.
--- **solution for the question:**
```
\documentclass[10pt, a4paper ]{scrreprt}
\usepackage{booktabs}
\usepackage{collcell}
\usepackage{array}
\begin{document}
\setlength{\parindent}{0pt}
\newlength{\stretchlen}\setlength{\stretchlen}{1em}
\def\splitterm{\_}
\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_}
\def\realstretch#1{%
\def\temp{#1}%
\ifx\temp\splitterm
\else
\hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch
\fi}
without the stretchit command
\begin{tabular}{cccccccc}
\midrule
1 & ++- \\
2 & +-+ \\
3 & -++ \\
4 & 000 \\
5 & --- \\
6 & 000 \\
\midrule
7 & -+- \\
8 & 000 \\
9 & +-- \\
10 & --+ \\
11 & +++ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\medskip
\emph{with} the stretchit command
\begin{tabular}{c>{\collectcell\stretchit}c<{\endcollectcell}ccccccc}
\midrule
1 & ++- \\
2 & +-+ \\
3 & -++ \\
4 & 000 \\
5 & --- \\
6 & 000 \\
\midrule
7 & -+- \\
8 & 000 \\
9 & +-- \\
10 & --+ \\
11 & +++ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
``` | Make sure you typeset them it **math-mode**, i.e. `$-$` and `$+$`.
Be aware that it makes a difference if you use a single math-mode or separate ones for them. The last sign has different spacing in the first case because it
is taken as an unary sign but the others are operators.
Compare the following:
```
\documentclass{article}
\begin{document}
$-$$-$$-$$+$$+$$+$
$+$$+$$+$$+$$+$$+$
$-$$-$$-$$-$$-$$-$
$---+++$
$++++++$
$------$
\end{document}
```
### Result:
![Result](https://i.stack.imgur.com/8AnbD.png)
---
For the alignment with the other signs `a`, `A` and `0` I would recommend that you make macros for all and set the width manually the one of the widest (should be `$+$`).
This can be done either with `\hbox to <length>{\hss <sign>\hss}` (TeX) or using `\makebox[<length>][c]{<sign>}` (LaTeX). The width is provided by `\settowidth{<length register>}{<content>}`.
```
\documentclass[11pt, a4paper]{scrreprt}
\usepackage{booktabs}
\newlength{\slength}
\settowidth{\slength}{$+$}
\newcommand*{\Sz}{\makebox[\slength][c]{0}}
\newcommand*{\SA}{\makebox[\slength][c]{A}}
\newcommand*{\Sa}{\makebox[\slength][c]{a}}
\newcommand*{\Sp}{\makebox[\slength][c]{$+$}}
\newcommand*{\Sm}{\makebox[\slength][c]{$-$}}
\begin{document}
\begin{tabular}{cc}
\toprule
1 & \Sp\Sp\Sm \\
2 & \Sp\Sm\Sp \\
3 & \Sm\Sp\Sp \\
4 & \Sz\Sz\Sz \\
5 & \Sm\Sm\Sm \\
6 & \Sz\Sz\Sz \\
\midrule
7 & \Sm\Sp\Sm \\
8 & \Sz\Sz\Sz \\
9 & \Sp\Sm\Sm \\
10 & \Sm\Sm\Sp \\
11 & \Sp\Sp\Sp \\
12 & \Sz\Sz\Sz \\
\midrule
13 & \Sz\Sz\Sz \\
14 & \Sz\Sz\Sa \\
15 & \Sz\Sz\SA \\
16 & \Sz\SA\Sz \\
17 & \SA\Sz\Sz \\
18 & \Sz\Sa\Sz \\
19 & \Sa\Sz\Sz \\
20 & \Sz\Sz\Sz \\
\bottomrule
\end{tabular}
\end{document}
```
### Result:
![Result 2](https://i.stack.imgur.com/1d879.png) |
14,576 | for typesetting tables with design of experiments, I have to typeset strings like "+ - + +", - - - +", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain "a", "A" and "0" (zero)).
However, the width of the "+" and "-" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash....
So I'm searching for a way to easily typeset e. g. "+ - - - + -" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters ("+" or "-", "a", "A" and "0") would be aligned with each other, when they are in the same column of a table.
I hope I could make clear what I need, some examples how it shall NOT look are found here:
![bad example](https://i.stack.imgur.com/YZkQH.png)
in line 9 it should be "+ - -" and in 10 "- - +", line 5 should be "- - -"
It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned:
![enter image description here](https://i.stack.imgur.com/dC5x3.png)
Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns...
Does anybody have an idea how to solve that?
Maybe a command that parses the string like --+--++ and typesets it with a "constant spacing"?
------- edit:
added math mode for "+" and "-", looks better now, but not perfect:
![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png)
```
\documentclass[11pt, a4paper%, halfparskip
]{scrreprt}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{cccccccc}
\midrule
1 & $+$$+$$-$ \\
2 & $+$$-$$+$ \\
3 & $-$$+$$+$ \\
4 & 000 \\
5 & $-$$-$$-$ \\
6 & 000 \\
\midrule
7 & $-$$+$$-$ \\
8 & 000 \\
9 & $+$$-$$-$ \\
10 & $-$$-$$+$ \\
11 & $+$$+$$+$ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
```
---
example and further question about side-effects:
I used the solution of Michel and it looks good, but there is one thing I'm not sure about:
Is it possible that it changes the free space between columns?
I have the impression that the first 3 columns are closer together than the rest...
How can I fix that?
![solution with side effects?!](https://i.stack.imgur.com/25OVA.png) | 2011/03/30 | ['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/'] | ```
\documentclass{minimal}
\begin{document}
\setlength{\parindent}{0pt}
\newlength{\stretchlen}\setlength{\stretchlen}{1em}
\def\splitterm{\_}
\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_}
\def\realstretch#1{%
\def\temp{#1}%
\ifx\temp\splitterm
\else
\hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch
\fi}
\stretchit{abcd}\par
\stretchit{----}\par
\stretchit{++++}\par
\stretchit{-+-+}\par
\stretchit{0aA+}\par
\end{document}
```
`\stretchit` appends an underscore to its argument and passes it to `\realstretch`, which recursively 'eats' one letter at a time, and typesets it centered in an `\hbox` stretched to `\stretchlen`. All letters are thus equally wide, and since they are centered, aligned nicely.
--- **solution for the question:**
```
\documentclass[10pt, a4paper ]{scrreprt}
\usepackage{booktabs}
\usepackage{collcell}
\usepackage{array}
\begin{document}
\setlength{\parindent}{0pt}
\newlength{\stretchlen}\setlength{\stretchlen}{1em}
\def\splitterm{\_}
\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_}
\def\realstretch#1{%
\def\temp{#1}%
\ifx\temp\splitterm
\else
\hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch
\fi}
without the stretchit command
\begin{tabular}{cccccccc}
\midrule
1 & ++- \\
2 & +-+ \\
3 & -++ \\
4 & 000 \\
5 & --- \\
6 & 000 \\
\midrule
7 & -+- \\
8 & 000 \\
9 & +-- \\
10 & --+ \\
11 & +++ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\medskip
\emph{with} the stretchit command
\begin{tabular}{c>{\collectcell\stretchit}c<{\endcollectcell}ccccccc}
\midrule
1 & ++- \\
2 & +-+ \\
3 & -++ \\
4 & 000 \\
5 & --- \\
6 & 000 \\
\midrule
7 & -+- \\
8 & 000 \\
9 & +-- \\
10 & --+ \\
11 & +++ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
``` | one possible form to typeset your table would be to use a table column for each character:
```
\documentclass[11pt, a4paper]{scrreprt}
\usepackage{booktabs}
\newcommand\Pl{${}+{}$}
\newcommand\Mi{${}-{}$}
\begin{document}
\begin{tabular}{cc@{\hspace{-2pt}}c@{\hspace{-2pt}}c}
\toprule
1 & \Pl & \Pl & \Mi \\
4 & 0 & 0 & 0 \\
12 & a & 0 & A \\
15 & 0 & 0 & A \\
\bottomrule
\end{tabular}
\end{document}
```
![](https://i.stack.imgur.com/RxGDb.png) |
14,576 | for typesetting tables with design of experiments, I have to typeset strings like "+ - + +", - - - +", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain "a", "A" and "0" (zero)).
However, the width of the "+" and "-" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash....
So I'm searching for a way to easily typeset e. g. "+ - - - + -" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters ("+" or "-", "a", "A" and "0") would be aligned with each other, when they are in the same column of a table.
I hope I could make clear what I need, some examples how it shall NOT look are found here:
![bad example](https://i.stack.imgur.com/YZkQH.png)
in line 9 it should be "+ - -" and in 10 "- - +", line 5 should be "- - -"
It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned:
![enter image description here](https://i.stack.imgur.com/dC5x3.png)
Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns...
Does anybody have an idea how to solve that?
Maybe a command that parses the string like --+--++ and typesets it with a "constant spacing"?
------- edit:
added math mode for "+" and "-", looks better now, but not perfect:
![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png)
```
\documentclass[11pt, a4paper%, halfparskip
]{scrreprt}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{cccccccc}
\midrule
1 & $+$$+$$-$ \\
2 & $+$$-$$+$ \\
3 & $-$$+$$+$ \\
4 & 000 \\
5 & $-$$-$$-$ \\
6 & 000 \\
\midrule
7 & $-$$+$$-$ \\
8 & 000 \\
9 & $+$$-$$-$ \\
10 & $-$$-$$+$ \\
11 & $+$$+$$+$ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
```
---
example and further question about side-effects:
I used the solution of Michel and it looks good, but there is one thing I'm not sure about:
Is it possible that it changes the free space between columns?
I have the impression that the first 3 columns are closer together than the rest...
How can I fix that?
![solution with side effects?!](https://i.stack.imgur.com/25OVA.png) | 2011/03/30 | ['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/'] | Make sure you typeset them it **math-mode**, i.e. `$-$` and `$+$`.
Be aware that it makes a difference if you use a single math-mode or separate ones for them. The last sign has different spacing in the first case because it
is taken as an unary sign but the others are operators.
Compare the following:
```
\documentclass{article}
\begin{document}
$-$$-$$-$$+$$+$$+$
$+$$+$$+$$+$$+$$+$
$-$$-$$-$$-$$-$$-$
$---+++$
$++++++$
$------$
\end{document}
```
### Result:
![Result](https://i.stack.imgur.com/8AnbD.png)
---
For the alignment with the other signs `a`, `A` and `0` I would recommend that you make macros for all and set the width manually the one of the widest (should be `$+$`).
This can be done either with `\hbox to <length>{\hss <sign>\hss}` (TeX) or using `\makebox[<length>][c]{<sign>}` (LaTeX). The width is provided by `\settowidth{<length register>}{<content>}`.
```
\documentclass[11pt, a4paper]{scrreprt}
\usepackage{booktabs}
\newlength{\slength}
\settowidth{\slength}{$+$}
\newcommand*{\Sz}{\makebox[\slength][c]{0}}
\newcommand*{\SA}{\makebox[\slength][c]{A}}
\newcommand*{\Sa}{\makebox[\slength][c]{a}}
\newcommand*{\Sp}{\makebox[\slength][c]{$+$}}
\newcommand*{\Sm}{\makebox[\slength][c]{$-$}}
\begin{document}
\begin{tabular}{cc}
\toprule
1 & \Sp\Sp\Sm \\
2 & \Sp\Sm\Sp \\
3 & \Sm\Sp\Sp \\
4 & \Sz\Sz\Sz \\
5 & \Sm\Sm\Sm \\
6 & \Sz\Sz\Sz \\
\midrule
7 & \Sm\Sp\Sm \\
8 & \Sz\Sz\Sz \\
9 & \Sp\Sm\Sm \\
10 & \Sm\Sm\Sp \\
11 & \Sp\Sp\Sp \\
12 & \Sz\Sz\Sz \\
\midrule
13 & \Sz\Sz\Sz \\
14 & \Sz\Sz\Sa \\
15 & \Sz\Sz\SA \\
16 & \Sz\SA\Sz \\
17 & \SA\Sz\Sz \\
18 & \Sz\Sa\Sz \\
19 & \Sa\Sz\Sz \\
20 & \Sz\Sz\Sz \\
\bottomrule
\end{tabular}
\end{document}
```
### Result:
![Result 2](https://i.stack.imgur.com/1d879.png) | Michel's solution is nice, but I'd like to present some improvements.
```
\newlength{\stretchlen}
\settowidth{\stretchlen}{+}
\newcommand{\stretchit}[1]{\realstretch#1\_}
\newcommand\realstretch[1]{%
\ifx#1\_%
\else
\makebox[\stretchlen]{\ifx#1-$-$\else#1\fi}%
%\hbox to \stretchlen{\hss\ifx#1-$-$\else#1\fi\hss}%
\expandafter\realstretch
\fi}
```
It's not necessary to have `\splitterm` and to define `\temp` at each stage, since we're collecting tokens one by one and those tokens are simple characters. It's best also to set `\stretchlen` to the widest character, in this case `+`. Finally, there's the particular case of `-` that should be treated differently with a `$-$`.
I've left commented the line with `\hbox`: with `\makebox` it's more in the LaTeX way of thinking; the two lines give the same result, but of course `\makebox` is a bit less efficient than `\hbox`.
---
Some years later, the solution can be made more robust, with the possibility of managing other characters that need special treatment.
```
\documentclass[10pt,a4paper]{scrreprt}
\usepackage{booktabs}
\usepackage{collcell}
\usepackage{array}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\stretchit}{m}
{
\tl_map_inline:nn { #1 }
{
\makebox[\stretchlen]
{
\str_case:nnF { ##1 }
{
{-}{$-$}
{+}{$+$}
{*}{$*$}
}
{##1}
}
}
}
\ExplSyntaxOff
\newlength{\stretchlen}
\AtBeginDocument{\settowidth{\stretchlen}{$-$}}
\begin{document}
\begin{tabular}{r >{\collectcell\stretchit}c<{\endcollectcell}}
\midrule
1 & ++- \\
2 & +-+ \\
3 & -++ \\
4 & 000 \\
5 & --- \\
6 & 000 \\
\midrule
7 & -+- \\
8 & -*x \\
9 & +-- \\
10 & --+ \\
11 & +++ \\
12 & 000 \\
\bottomrule
\end{tabular}
\end{document}
```
[![enter image description here](https://i.stack.imgur.com/mQ2VO.png)](https://i.stack.imgur.com/mQ2VO.png) |
14,576 | for typesetting tables with design of experiments, I have to typeset strings like "+ - + +", - - - +", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain "a", "A" and "0" (zero)).
However, the width of the "+" and "-" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash....
So I'm searching for a way to easily typeset e. g. "+ - - - + -" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters ("+" or "-", "a", "A" and "0") would be aligned with each other, when they are in the same column of a table.
I hope I could make clear what I need, some examples how it shall NOT look are found here:
![bad example](https://i.stack.imgur.com/YZkQH.png)
in line 9 it should be "+ - -" and in 10 "- - +", line 5 should be "- - -"
It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned:
![enter image description here](https://i.stack.imgur.com/dC5x3.png)
Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns...
Does anybody have an idea how to solve that?
Maybe a command that parses the string like --+--++ and typesets it with a "constant spacing"?
------- edit:
added math mode for "+" and "-", looks better now, but not perfect:
![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png)
```
\documentclass[11pt, a4paper%, halfparskip
]{scrreprt}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{cccccccc}
\midrule
1 & $+$$+$$-$ \\
2 & $+$$-$$+$ \\
3 & $-$$+$$+$ \\
4 & 000 \\
5 & $-$$-$$-$ \\
6 & 000 \\
\midrule
7 & $-$$+$$-$ \\
8 & 000 \\
9 & $+$$-$$-$ \\
10 & $-$$-$$+$ \\
11 & $+$$+$$+$ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
```
---
example and further question about side-effects:
I used the solution of Michel and it looks good, but there is one thing I'm not sure about:
Is it possible that it changes the free space between columns?
I have the impression that the first 3 columns are closer together than the rest...
How can I fix that?
![solution with side effects?!](https://i.stack.imgur.com/25OVA.png) | 2011/03/30 | ['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/'] | one possible form to typeset your table would be to use a table column for each character:
```
\documentclass[11pt, a4paper]{scrreprt}
\usepackage{booktabs}
\newcommand\Pl{${}+{}$}
\newcommand\Mi{${}-{}$}
\begin{document}
\begin{tabular}{cc@{\hspace{-2pt}}c@{\hspace{-2pt}}c}
\toprule
1 & \Pl & \Pl & \Mi \\
4 & 0 & 0 & 0 \\
12 & a & 0 & A \\
15 & 0 & 0 & A \\
\bottomrule
\end{tabular}
\end{document}
```
![](https://i.stack.imgur.com/RxGDb.png) | A quick and dirty solution might be to enclose the symbols in braces: `${-}{+}{+}{+}$` looks better than `$-+++$`, as LaTeX won't try to interpret each `+` or `-` as a binary operator. |
14,576 | for typesetting tables with design of experiments, I have to typeset strings like "+ - + +", - - - +", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain "a", "A" and "0" (zero)).
However, the width of the "+" and "-" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash....
So I'm searching for a way to easily typeset e. g. "+ - - - + -" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters ("+" or "-", "a", "A" and "0") would be aligned with each other, when they are in the same column of a table.
I hope I could make clear what I need, some examples how it shall NOT look are found here:
![bad example](https://i.stack.imgur.com/YZkQH.png)
in line 9 it should be "+ - -" and in 10 "- - +", line 5 should be "- - -"
It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned:
![enter image description here](https://i.stack.imgur.com/dC5x3.png)
Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns...
Does anybody have an idea how to solve that?
Maybe a command that parses the string like --+--++ and typesets it with a "constant spacing"?
------- edit:
added math mode for "+" and "-", looks better now, but not perfect:
![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png)
```
\documentclass[11pt, a4paper%, halfparskip
]{scrreprt}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{cccccccc}
\midrule
1 & $+$$+$$-$ \\
2 & $+$$-$$+$ \\
3 & $-$$+$$+$ \\
4 & 000 \\
5 & $-$$-$$-$ \\
6 & 000 \\
\midrule
7 & $-$$+$$-$ \\
8 & 000 \\
9 & $+$$-$$-$ \\
10 & $-$$-$$+$ \\
11 & $+$$+$$+$ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
```
---
example and further question about side-effects:
I used the solution of Michel and it looks good, but there is one thing I'm not sure about:
Is it possible that it changes the free space between columns?
I have the impression that the first 3 columns are closer together than the rest...
How can I fix that?
![solution with side effects?!](https://i.stack.imgur.com/25OVA.png) | 2011/03/30 | ['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/'] | ```
\documentclass{minimal}
\begin{document}
\setlength{\parindent}{0pt}
\newlength{\stretchlen}\setlength{\stretchlen}{1em}
\def\splitterm{\_}
\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_}
\def\realstretch#1{%
\def\temp{#1}%
\ifx\temp\splitterm
\else
\hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch
\fi}
\stretchit{abcd}\par
\stretchit{----}\par
\stretchit{++++}\par
\stretchit{-+-+}\par
\stretchit{0aA+}\par
\end{document}
```
`\stretchit` appends an underscore to its argument and passes it to `\realstretch`, which recursively 'eats' one letter at a time, and typesets it centered in an `\hbox` stretched to `\stretchlen`. All letters are thus equally wide, and since they are centered, aligned nicely.
--- **solution for the question:**
```
\documentclass[10pt, a4paper ]{scrreprt}
\usepackage{booktabs}
\usepackage{collcell}
\usepackage{array}
\begin{document}
\setlength{\parindent}{0pt}
\newlength{\stretchlen}\setlength{\stretchlen}{1em}
\def\splitterm{\_}
\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_}
\def\realstretch#1{%
\def\temp{#1}%
\ifx\temp\splitterm
\else
\hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch
\fi}
without the stretchit command
\begin{tabular}{cccccccc}
\midrule
1 & ++- \\
2 & +-+ \\
3 & -++ \\
4 & 000 \\
5 & --- \\
6 & 000 \\
\midrule
7 & -+- \\
8 & 000 \\
9 & +-- \\
10 & --+ \\
11 & +++ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\medskip
\emph{with} the stretchit command
\begin{tabular}{c>{\collectcell\stretchit}c<{\endcollectcell}ccccccc}
\midrule
1 & ++- \\
2 & +-+ \\
3 & -++ \\
4 & 000 \\
5 & --- \\
6 & 000 \\
\midrule
7 & -+- \\
8 & 000 \\
9 & +-- \\
10 & --+ \\
11 & +++ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
``` | A quick and dirty solution might be to enclose the symbols in braces: `${-}{+}{+}{+}$` looks better than `$-+++$`, as LaTeX won't try to interpret each `+` or `-` as a binary operator. |
14,576 | for typesetting tables with design of experiments, I have to typeset strings like "+ - + +", - - - +", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain "a", "A" and "0" (zero)).
However, the width of the "+" and "-" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash....
So I'm searching for a way to easily typeset e. g. "+ - - - + -" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters ("+" or "-", "a", "A" and "0") would be aligned with each other, when they are in the same column of a table.
I hope I could make clear what I need, some examples how it shall NOT look are found here:
![bad example](https://i.stack.imgur.com/YZkQH.png)
in line 9 it should be "+ - -" and in 10 "- - +", line 5 should be "- - -"
It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned:
![enter image description here](https://i.stack.imgur.com/dC5x3.png)
Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns...
Does anybody have an idea how to solve that?
Maybe a command that parses the string like --+--++ and typesets it with a "constant spacing"?
------- edit:
added math mode for "+" and "-", looks better now, but not perfect:
![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png)
```
\documentclass[11pt, a4paper%, halfparskip
]{scrreprt}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{cccccccc}
\midrule
1 & $+$$+$$-$ \\
2 & $+$$-$$+$ \\
3 & $-$$+$$+$ \\
4 & 000 \\
5 & $-$$-$$-$ \\
6 & 000 \\
\midrule
7 & $-$$+$$-$ \\
8 & 000 \\
9 & $+$$-$$-$ \\
10 & $-$$-$$+$ \\
11 & $+$$+$$+$ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
```
---
example and further question about side-effects:
I used the solution of Michel and it looks good, but there is one thing I'm not sure about:
Is it possible that it changes the free space between columns?
I have the impression that the first 3 columns are closer together than the rest...
How can I fix that?
![solution with side effects?!](https://i.stack.imgur.com/25OVA.png) | 2011/03/30 | ['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/'] | ```
\documentclass{minimal}
\begin{document}
\setlength{\parindent}{0pt}
\newlength{\stretchlen}\setlength{\stretchlen}{1em}
\def\splitterm{\_}
\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_}
\def\realstretch#1{%
\def\temp{#1}%
\ifx\temp\splitterm
\else
\hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch
\fi}
\stretchit{abcd}\par
\stretchit{----}\par
\stretchit{++++}\par
\stretchit{-+-+}\par
\stretchit{0aA+}\par
\end{document}
```
`\stretchit` appends an underscore to its argument and passes it to `\realstretch`, which recursively 'eats' one letter at a time, and typesets it centered in an `\hbox` stretched to `\stretchlen`. All letters are thus equally wide, and since they are centered, aligned nicely.
--- **solution for the question:**
```
\documentclass[10pt, a4paper ]{scrreprt}
\usepackage{booktabs}
\usepackage{collcell}
\usepackage{array}
\begin{document}
\setlength{\parindent}{0pt}
\newlength{\stretchlen}\setlength{\stretchlen}{1em}
\def\splitterm{\_}
\newcommand{\stretchit}[1]{\leavevmode\realstretch#1\_}
\def\realstretch#1{%
\def\temp{#1}%
\ifx\temp\splitterm
\else
\hbox to \stretchlen{\hss#1\hss}\expandafter\realstretch
\fi}
without the stretchit command
\begin{tabular}{cccccccc}
\midrule
1 & ++- \\
2 & +-+ \\
3 & -++ \\
4 & 000 \\
5 & --- \\
6 & 000 \\
\midrule
7 & -+- \\
8 & 000 \\
9 & +-- \\
10 & --+ \\
11 & +++ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\medskip
\emph{with} the stretchit command
\begin{tabular}{c>{\collectcell\stretchit}c<{\endcollectcell}ccccccc}
\midrule
1 & ++- \\
2 & +-+ \\
3 & -++ \\
4 & 000 \\
5 & --- \\
6 & 000 \\
\midrule
7 & -+- \\
8 & 000 \\
9 & +-- \\
10 & --+ \\
11 & +++ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
``` | An easy way to achieve this would be to typeset the plusses and minuses in a monospace font with `\verb|+-+-|`
There are however [issues](https://tex.stackexchange.com/q/203/215) with verbatim text which you might run into...
Another solution might be to use `\texttt` and macros for your plusses etc. Here's an example:
```
\documentclass{article}
\usepackage[T1]{fontenc}
\newcommand\p{+}
\newcommand\m{-{}}
\begin{document}
\texttt{++---++}
\texttt{\p\p\m\m\m\p\p}
\texttt{++\m\m aA0}
\end{document}
```
You need to use a macro like this for the minus sign because otherwise they get turned into en-dashes if you use the `fontenc` package. This should also mono-space letters easily. |
14,576 | for typesetting tables with design of experiments, I have to typeset strings like "+ - + +", - - - +", etc. in a column of a table to represent the so called pattern of the experimental run (sometimes they also contain "a", "A" and "0" (zero)).
However, the width of the "+" and "-" sign are very different in the used font (standard font in KOMA script class scrreprt) and a sequence of 2 or 3 dashes creates one long or very long dash....
So I'm searching for a way to easily typeset e. g. "+ - - - + -" with a little spacing between the characters and (if possible) that several different strings composed of the same number of characters ("+" or "-", "a", "A" and "0") would be aligned with each other, when they are in the same column of a table.
I hope I could make clear what I need, some examples how it shall NOT look are found here:
![bad example](https://i.stack.imgur.com/YZkQH.png)
in line 9 it should be "+ - -" and in 10 "- - +", line 5 should be "- - -"
It looks a little better, if I insert `\,` between the characters, but as the widths are different, it is still not aligned:
![enter image description here](https://i.stack.imgur.com/dC5x3.png)
Sure, I could split it up in centered columns like `- & + & - & - & ...`, but the tables are already complicated enough and I do not want to add 3 to 7 columns...
Does anybody have an idea how to solve that?
Maybe a command that parses the string like --+--++ and typesets it with a "constant spacing"?
------- edit:
added math mode for "+" and "-", looks better now, but not perfect:
![math mode for plus and minus](https://i.stack.imgur.com/D3hFt.png)
```
\documentclass[11pt, a4paper%, halfparskip
]{scrreprt}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{cccccccc}
\midrule
1 & $+$$+$$-$ \\
2 & $+$$-$$+$ \\
3 & $-$$+$$+$ \\
4 & 000 \\
5 & $-$$-$$-$ \\
6 & 000 \\
\midrule
7 & $-$$+$$-$ \\
8 & 000 \\
9 & $+$$-$$-$ \\
10 & $-$$-$$+$ \\
11 & $+$$+$$+$ \\
12 & 000 \\
\midrule
13 & 000 \\
14 & 00a \\
15 & 00A \\
16 & 0A0 \\
17 & A00 \\
18 & 0a0 \\
19 & a00 \\
20 & 000 \\
\toprule
\end{tabular}
\end{document}
```
---
example and further question about side-effects:
I used the solution of Michel and it looks good, but there is one thing I'm not sure about:
Is it possible that it changes the free space between columns?
I have the impression that the first 3 columns are closer together than the rest...
How can I fix that?
![solution with side effects?!](https://i.stack.imgur.com/25OVA.png) | 2011/03/30 | ['https://tex.stackexchange.com/questions/14576', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/4009/'] | Make sure you typeset them it **math-mode**, i.e. `$-$` and `$+$`.
Be aware that it makes a difference if you use a single math-mode or separate ones for them. The last sign has different spacing in the first case because it
is taken as an unary sign but the others are operators.
Compare the following:
```
\documentclass{article}
\begin{document}
$-$$-$$-$$+$$+$$+$
$+$$+$$+$$+$$+$$+$
$-$$-$$-$$-$$-$$-$
$---+++$
$++++++$
$------$
\end{document}
```
### Result:
![Result](https://i.stack.imgur.com/8AnbD.png)
---
For the alignment with the other signs `a`, `A` and `0` I would recommend that you make macros for all and set the width manually the one of the widest (should be `$+$`).
This can be done either with `\hbox to <length>{\hss <sign>\hss}` (TeX) or using `\makebox[<length>][c]{<sign>}` (LaTeX). The width is provided by `\settowidth{<length register>}{<content>}`.
```
\documentclass[11pt, a4paper]{scrreprt}
\usepackage{booktabs}
\newlength{\slength}
\settowidth{\slength}{$+$}
\newcommand*{\Sz}{\makebox[\slength][c]{0}}
\newcommand*{\SA}{\makebox[\slength][c]{A}}
\newcommand*{\Sa}{\makebox[\slength][c]{a}}
\newcommand*{\Sp}{\makebox[\slength][c]{$+$}}
\newcommand*{\Sm}{\makebox[\slength][c]{$-$}}
\begin{document}
\begin{tabular}{cc}
\toprule
1 & \Sp\Sp\Sm \\
2 & \Sp\Sm\Sp \\
3 & \Sm\Sp\Sp \\
4 & \Sz\Sz\Sz \\
5 & \Sm\Sm\Sm \\
6 & \Sz\Sz\Sz \\
\midrule
7 & \Sm\Sp\Sm \\
8 & \Sz\Sz\Sz \\
9 & \Sp\Sm\Sm \\
10 & \Sm\Sm\Sp \\
11 & \Sp\Sp\Sp \\
12 & \Sz\Sz\Sz \\
\midrule
13 & \Sz\Sz\Sz \\
14 & \Sz\Sz\Sa \\
15 & \Sz\Sz\SA \\
16 & \Sz\SA\Sz \\
17 & \SA\Sz\Sz \\
18 & \Sz\Sa\Sz \\
19 & \Sa\Sz\Sz \\
20 & \Sz\Sz\Sz \\
\bottomrule
\end{tabular}
\end{document}
```
### Result:
![Result 2](https://i.stack.imgur.com/1d879.png) | A quick and dirty solution might be to enclose the symbols in braces: `${-}{+}{+}{+}$` looks better than `$-+++$`, as LaTeX won't try to interpret each `+` or `-` as a binary operator. |
6,628,452 | I want Django to send an email to user email-address with Login details once admin adds a new user to admin site.So I tried using Django signals for that but just becoz django user registration is a two step process signals get notified in first step only and called email function without email address(which comes in second step).
My signal code:
```
def email_new_user(sender, **kwargs):
if kwargs["created"]: # only for new users
new_user = kwargs["instance"]
send_mail('Subject here', 'Here is the message.', 'from@example.com',['to@example.com'], fail_silently=False)
post_save.connect(email_new_user, sender=User)
```
So what i tried to overcome this problem.I use this code in admin.py
```
class UserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'first_name', 'last_name', 'date_joined', 'last_login')
search_fields = ['username', 'email']
filter_horizontal = ('user_permissions',)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
```
This makes all registration process a single step process and my signals start working and sending mail to user\_id on new user addition.But the problem came after this were:
**1. User password is not converted into hash and is visible while entering into form,that makes user not able to login into admin site.**
**2.Email field in form is not compulsory which I want to be compulsory.**
Please help me :(
**[EDIT]**
```
I tried your code But I m still at same place where i was before posting this question.
the code i used in my admin.py is:
from django.contrib import admin
from mysite.naturefarms.models import *
from django.contrib.auth.models import User,Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from django.contrib.admin.views.main import *
class MyUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email',)
class UserAdmin(admin.ModelAdmin):
add_form = MyUserCreationForm
admin.site.unregister(User)
class MyUserAdmin(UserAdmin):
add_form = MyUserCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
admin.site.register(User, MyUserAdmin)
```
![This is the output I m getting using this code which is even not converting password field into hash.](https://i.stack.imgur.com/ps5Qz.jpg) | 2011/07/08 | ['https://Stackoverflow.com/questions/6628452', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/632467/'] | If you look in django.contrib.auth admin.py, you'll see that the UserAdmin class specifies the add\_form as UserCreationForm.
UserCreationForm only includes the 'username' field from the User model.
Since you're providing your own UserAdmin, you can just override the add\_form to a custom UserCreationForm that includes the fields you need to make your signal work properly.
Hope that helps you out.
[Edit]
Here's the UserCreationForm from contrib.auth forms.py:
```
class UserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and password.
"""
username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
help_text = _("Enter the same password as above, for verification."))
class Meta:
model = User
fields = ("username",)
def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(_("A user with that username already exists."))
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
```
Notice the fields = ("username",) tuple which excludes all other fields on the User model. You need something like:
```
class MyUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email',)
```
then you can use that as the add\_form in your custom UserAdmin:
```
class UserAdmin(admin.ModelAdmin):
add_form = MyUserCreationForm
```
It's pretty late in my part of the world, but I'll see if I can get a working sample for you tomorrow.
[Edit]
Ok, here's the necessary changes you'll need to make to make this work. I've tested it using Django 1.3:
```
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django import forms
admin.site.unregister(User)
class MyUserAdmin(UserAdmin):
add_form = MyUserCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
admin.site.register(User, MyUserAdmin)
```
I didn't see that the UserAdmin had an add\_fieldset property initially. That's why the email field wasn't displaying in the add form. | From [this example](http://jessenoller.com/blog/2011/12/19/quick-example-of-extending-usercreationform-in-django) try defining email in your custom UserCreationForm as required=True:
```
class MyUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email',)
``` |
224,643 | It says:
>
> Please list up to three projects (in order of preference) you are
> interested in.
>
>
>
So I am not sure: Do I have to put in exactly three projects or can I also just put in two? | 2015/01/30 | ['https://english.stackexchange.com/questions/224643', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/108012/'] | You can put in three or fewer projects, since up to is a limiting factor, but does not require a minimum, so by this grammar, two projects would be an acceptable response. | Yes. You can put two.
You can put one, two, or three. |
62,993,565 | I'm using `logging.config.dictconfig()` and my formatter is:
```
'formatters': {
'logfileFormat': {
'format': '%(asctime)s %(name)-12s: %(levelname)s %(message)s'
}
}
```
When there's an exception, I would like the formatter to show the error message, as well as print out the exec\_info. How do I alter the `format` to do this? Or do I need to implement my own formatter in code, and reference it here? | 2020/07/20 | ['https://Stackoverflow.com/questions/62993565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1724926/'] | For me working nice if assign back output, but very similar method [`DataFrame.update`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html) working inplace:
```
df = df1.combine_first(df2)
print (df)
Gen1 Gen2
0 5.0 1.0
1 4.0 2.0
2 3.0 3.0
3 2.0 4.0
4 1.0 5.0
```
---
```
df1.update(df2)
print (df1)
Gen1 Gen2
0 5.0 1.0
1 4.0 2.0
2 3.0 3.0
3 2.0 4.0
4 1.0 5.0
``` | `combine_first` returns a dataframe which has the change and not updating the existing dataframe so you should get the return dataframe
```
df1=df1.combine_first(df2)
``` |
66,027,931 | I have table like:
```
name | timeStamp | previousValue | newValue
--------+---------------+-------------------+------------
Mark | 13.12.2020 | 123 | 155
Mark | 12.12.2020 | 123 | 12
Tom | 14.12.2020 | 123 | 534
Mark | 12.12.2020 | 123 | 31
Tom | 11.12.2020 | 123 | 84
Mark | 19.12.2020 | 123 | 33
Mark | 17.12.2020 | 123 | 96
John | 22.12.2020 | 123 | 69
John | 19.12.2020 | 123 | 33
```
I'd like to mix last\_value, count (\*) and group to get this result:
```
name | count | lastValue
--------+-----------+-------------
Mark | 5 | 33
Tom | 2 | 534
John | 2 | 69
```
This part:
```
select name, count(*)
from table
group by name
```
returns table:
```
name | count
--------+---------
Mark | 5
Tom | 2
John | 2
```
but I have to add the last value for each name.
How to do it?
Best regards! | 2021/02/03 | ['https://Stackoverflow.com/questions/66027931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15133478/'] | `LAST_VALUE` is a windowed function, so you'll need to get that value first, and then aggregate:
```sql
WITH CTE AS(
SELECT [name],
[timeStamp], --This is a poor choice for a column's name. timestamp is a (deprecated) synonym of rowversion, and a rowversion is not a date and time value
previousValue,
newValue,
LAST_VALUE(newValue) OVER (PARTITION BY [name] ORDER BY [timeStamp] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lastValue
FROM dbo.YourTable)
SELECT [Name],
COUNT(*) AS [count],
lastValue
FROM CTE
GROUP BY [Name],
lastValue;
``` | I got a solution that works, but here's another one:
```
SELECT
[name], COUNT([name]), [lastValue]
FROM (
SELECT
[name], FIRST_VALUE([newValue]) OVER (PARTITION BY [name] ORDER BY TimeStamp DESC ROWS UNBOUNDED PRECEDING) AS [lastValue]
FROM [table]
) xyz GROUP BY [name], [lastValue]
```
Keep well! |
73,659,886 | I have a JSON file with a category structure of unknown depth. I want to make sure all pages can be accessed. I established three nested calls, but I think it would be better to recursion here. Unfortunately, I have no experience with Typescript regarding recursion. Can someone be so kind as to help me put the logic into a function I can call?
```
test.setTimeout(28800000); // 8 hours max.
// console.log(ofcJSON)
for (let i = 0; i < ofcJSON.items.length; i++) {
let currentPage = ofcJSON.items[i].link
console.log(currentPage)
if (!currentPage.startsWith("http")) await page.goto(currentPage)
if (ofcJSON.items[i].items != null) {
for (let j = 0; j < ofcJSON.items[i].items!.length; j++) {
let currentPage1 = ofcJSON.items[i].items![j].link
console.log(currentPage1)
if (!currentPage1.startsWith("http")) await page.goto(currentPage1)
if (ofcJSON.items[i].items![j].items != null) {
for(let k = 0; k < ofcJSON.items[i].items![j].items!.length; k++) {
let currentPage2 = ofcJSON.items[i].items![j].items![k].link
console.log(currentPage2)
if (!currentPage2.startsWith("http")) await page.goto(currentPage2)
if (ofcJSON.items![i].items![j].items![k].items != null) {
for(let l = 0; l < ofcJSON.items[i].items![j].items![k].items!.length; l++) {
let currentPage3 = ofcJSON.items[i].items![j].items![k].items![l].link
console.log(currentPage3)
if (!currentPage3.startsWith("http")) await page.goto(currentPage3)
}
}
}
}
}
}
}
});
```
The JSON has 1 **items** object, which in turn can have 1 **items** object. This is optional. I don't know the depth. | 2022/09/09 | ['https://Stackoverflow.com/questions/73659886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/558120/'] | Can I suggest that you use an f-string if you're on a version of python that supports them.
```
sqlcuery=f"insert into position ('position'), values('{position}')"
``` | Try this:
```
"insert into position ('position'), values('"+str(position)+"')"
```
To transform the integer or float to a string.
You can do this more elegantly with a f-string:
```
f"insert into position ('position'), values('{position}')"
``` |
73,659,886 | I have a JSON file with a category structure of unknown depth. I want to make sure all pages can be accessed. I established three nested calls, but I think it would be better to recursion here. Unfortunately, I have no experience with Typescript regarding recursion. Can someone be so kind as to help me put the logic into a function I can call?
```
test.setTimeout(28800000); // 8 hours max.
// console.log(ofcJSON)
for (let i = 0; i < ofcJSON.items.length; i++) {
let currentPage = ofcJSON.items[i].link
console.log(currentPage)
if (!currentPage.startsWith("http")) await page.goto(currentPage)
if (ofcJSON.items[i].items != null) {
for (let j = 0; j < ofcJSON.items[i].items!.length; j++) {
let currentPage1 = ofcJSON.items[i].items![j].link
console.log(currentPage1)
if (!currentPage1.startsWith("http")) await page.goto(currentPage1)
if (ofcJSON.items[i].items![j].items != null) {
for(let k = 0; k < ofcJSON.items[i].items![j].items!.length; k++) {
let currentPage2 = ofcJSON.items[i].items![j].items![k].link
console.log(currentPage2)
if (!currentPage2.startsWith("http")) await page.goto(currentPage2)
if (ofcJSON.items![i].items![j].items![k].items != null) {
for(let l = 0; l < ofcJSON.items[i].items![j].items![k].items!.length; l++) {
let currentPage3 = ofcJSON.items[i].items![j].items![k].items![l].link
console.log(currentPage3)
if (!currentPage3.startsWith("http")) await page.goto(currentPage3)
}
}
}
}
}
}
}
});
```
The JSON has 1 **items** object, which in turn can have 1 **items** object. This is optional. I don't know the depth. | 2022/09/09 | ['https://Stackoverflow.com/questions/73659886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/558120/'] | Personally, I'd recommend using an f-string. These allow you to input variables of any type within your code without too much issue. Wrap your variables in {}, like I've shown below.
```
sqlcuery=f"insert into position {position}"
``` | Try this:
```
"insert into position ('position'), values('"+str(position)+"')"
```
To transform the integer or float to a string.
You can do this more elegantly with a f-string:
```
f"insert into position ('position'), values('{position}')"
``` |
73,659,886 | I have a JSON file with a category structure of unknown depth. I want to make sure all pages can be accessed. I established three nested calls, but I think it would be better to recursion here. Unfortunately, I have no experience with Typescript regarding recursion. Can someone be so kind as to help me put the logic into a function I can call?
```
test.setTimeout(28800000); // 8 hours max.
// console.log(ofcJSON)
for (let i = 0; i < ofcJSON.items.length; i++) {
let currentPage = ofcJSON.items[i].link
console.log(currentPage)
if (!currentPage.startsWith("http")) await page.goto(currentPage)
if (ofcJSON.items[i].items != null) {
for (let j = 0; j < ofcJSON.items[i].items!.length; j++) {
let currentPage1 = ofcJSON.items[i].items![j].link
console.log(currentPage1)
if (!currentPage1.startsWith("http")) await page.goto(currentPage1)
if (ofcJSON.items[i].items![j].items != null) {
for(let k = 0; k < ofcJSON.items[i].items![j].items!.length; k++) {
let currentPage2 = ofcJSON.items[i].items![j].items![k].link
console.log(currentPage2)
if (!currentPage2.startsWith("http")) await page.goto(currentPage2)
if (ofcJSON.items![i].items![j].items![k].items != null) {
for(let l = 0; l < ofcJSON.items[i].items![j].items![k].items!.length; l++) {
let currentPage3 = ofcJSON.items[i].items![j].items![k].items![l].link
console.log(currentPage3)
if (!currentPage3.startsWith("http")) await page.goto(currentPage3)
}
}
}
}
}
}
}
});
```
The JSON has 1 **items** object, which in turn can have 1 **items** object. This is optional. I don't know the depth. | 2022/09/09 | ['https://Stackoverflow.com/questions/73659886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/558120/'] | Personally, I'd recommend using an f-string. These allow you to input variables of any type within your code without too much issue. Wrap your variables in {}, like I've shown below.
```
sqlcuery=f"insert into position {position}"
``` | Can I suggest that you use an f-string if you're on a version of python that supports them.
```
sqlcuery=f"insert into position ('position'), values('{position}')"
``` |
43,310,947 | I'm trying to replace all full stops in an email with an x character - for example "my.email@email.com" would become "myxemail@emailxcom". Email is set to a string.
My problem is it's not replacing just full stops, it's replacing every character, so I just get a string of x's.
I can get it working with just one full stop, so I'm assuming I'm wrong on the global instance part. Here's my code:
```
let re = ".";
let new = email.replace(/re/gi, "x");
```
I've also tried
```
re = /./gi;
new = email.replace(re, "x");
```
If anyone can shed any light I'd really appreciate it, I've been stuck on this for so long and can't seem to figure out where I'm going wrong.
\*\* Edit: Whoops, my new variable was actually called newemail, keyword new wasn't causing the issue! | 2017/04/09 | ['https://Stackoverflow.com/questions/43310947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7232648/'] | Your second example is the closest. The first problem is your variable name, **`new`**, which happens to be one of JavaScript's [reserved keywords](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords) (and is instead used to construct objects, like `new RegExp` or `new Set`). This means that your program will throw a Syntax Error.
Also, since the dot (`.`) is a special character inside regex grammar, you should escape it as `\.`. Otherwise you would end up with `result == "xxxxxxxxxxxxxxxxxx"`, which is undesirable.
```js
let email = "my.email@email.com"
let re = /\./gi;
let result = email.replace(re, "x");
console.log(result)
``` | You can try `split()` and `join()` method that was work for me. (For normal string text)
It was short and simple to implement and understand.
Below is an example.
```
let email = "my.email@email.com";
email.split('.').join('x');
```
So, it will replace all your `.` with `x`. So, after the above example, `email` variable will have value `myxemail@gmailxcom` |
43,310,947 | I'm trying to replace all full stops in an email with an x character - for example "my.email@email.com" would become "myxemail@emailxcom". Email is set to a string.
My problem is it's not replacing just full stops, it's replacing every character, so I just get a string of x's.
I can get it working with just one full stop, so I'm assuming I'm wrong on the global instance part. Here's my code:
```
let re = ".";
let new = email.replace(/re/gi, "x");
```
I've also tried
```
re = /./gi;
new = email.replace(re, "x");
```
If anyone can shed any light I'd really appreciate it, I've been stuck on this for so long and can't seem to figure out where I'm going wrong.
\*\* Edit: Whoops, my new variable was actually called newemail, keyword new wasn't causing the issue! | 2017/04/09 | ['https://Stackoverflow.com/questions/43310947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7232648/'] | Your second example is the closest. The first problem is your variable name, **`new`**, which happens to be one of JavaScript's [reserved keywords](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords) (and is instead used to construct objects, like `new RegExp` or `new Set`). This means that your program will throw a Syntax Error.
Also, since the dot (`.`) is a special character inside regex grammar, you should escape it as `\.`. Otherwise you would end up with `result == "xxxxxxxxxxxxxxxxxx"`, which is undesirable.
```js
let email = "my.email@email.com"
let re = /\./gi;
let result = email.replace(re, "x");
console.log(result)
``` | You may just use `replaceAll()` String function, described here:
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll>
If you are getting
**Property 'replaceAll' does not exist on type 'string'**
error - go to `tsconfig.json` and within "lib" change or add "es2021".
Like this:
[![enter image description here](https://i.stack.imgur.com/TKIil.png)](https://i.stack.imgur.com/TKIil.png)
More info here: [Property 'replaceAll' does not exist on type 'string'](https://stackoverflow.com/questions/63616486/property-replaceall-does-not-exist-on-type-string) |
43,310,947 | I'm trying to replace all full stops in an email with an x character - for example "my.email@email.com" would become "myxemail@emailxcom". Email is set to a string.
My problem is it's not replacing just full stops, it's replacing every character, so I just get a string of x's.
I can get it working with just one full stop, so I'm assuming I'm wrong on the global instance part. Here's my code:
```
let re = ".";
let new = email.replace(/re/gi, "x");
```
I've also tried
```
re = /./gi;
new = email.replace(re, "x");
```
If anyone can shed any light I'd really appreciate it, I've been stuck on this for so long and can't seem to figure out where I'm going wrong.
\*\* Edit: Whoops, my new variable was actually called newemail, keyword new wasn't causing the issue! | 2017/04/09 | ['https://Stackoverflow.com/questions/43310947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7232648/'] | You can try `split()` and `join()` method that was work for me. (For normal string text)
It was short and simple to implement and understand.
Below is an example.
```
let email = "my.email@email.com";
email.split('.').join('x');
```
So, it will replace all your `.` with `x`. So, after the above example, `email` variable will have value `myxemail@gmailxcom` | You may just use `replaceAll()` String function, described here:
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll>
If you are getting
**Property 'replaceAll' does not exist on type 'string'**
error - go to `tsconfig.json` and within "lib" change or add "es2021".
Like this:
[![enter image description here](https://i.stack.imgur.com/TKIil.png)](https://i.stack.imgur.com/TKIil.png)
More info here: [Property 'replaceAll' does not exist on type 'string'](https://stackoverflow.com/questions/63616486/property-replaceall-does-not-exist-on-type-string) |
38,740,587 | How do I make sure that a file is not branchable across different projects in UCM ?
It should always be picked from `/main/LATEST/` for all the parallel projects | 2016/08/03 | ['https://Stackoverflow.com/questions/38740587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3119109/'] | Did you read the JavaDocs on `isDirectory()` etc.? For `isDirectory()` it says:
>
> returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise
>
>
>
So if the directory doesn't exist you get false and don't create one. Then you continue trying to write and create and write etc. until you get the StackOverFlowError.
To fix the stackoverflow you should check the return value of your create file, e.g.
```
boolean created = this.createFileMain(path);
if( created ) {
this.writeInFile(path, content);
}
```
To fix your file/directory creation you need to check whether the file already exists and otherwise create it (optionally also creating the parent directories via `file.getParentFile().mkdirs()`).
The problem is that you should know whether you want to create a file or a directory, since you can't tell by the name alone whether the path is meant to be a directory or file name (unless you invent some markup like always ending a directory path with a separator or requiring files to always have an extension). If you want to write some content you need to create a file anyways, a directory would break your code again. | ```
private boolean createFile(File file) {
if(!file.exists()) {
if(file.getParentFile().exists()) {
// ...
} else { // In this case, neither file nor its parent exist
if(this.createDirectory(file)) {
this.createFile(file); // HERE, you're calling the same method again
} else {
// ...;
}
}
}
return true;
}
```
I believe you want to replace the line marked `HERE` with `this.createFile(file.getParentFile());`. Here what happens is that your function recursively calls itself with the same arguments, so nothing ever happens, and your program gets stuck in a loop until it runs out of stack memory. |
38,740,587 | How do I make sure that a file is not branchable across different projects in UCM ?
It should always be picked from `/main/LATEST/` for all the parallel projects | 2016/08/03 | ['https://Stackoverflow.com/questions/38740587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3119109/'] | Did you read the JavaDocs on `isDirectory()` etc.? For `isDirectory()` it says:
>
> returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise
>
>
>
So if the directory doesn't exist you get false and don't create one. Then you continue trying to write and create and write etc. until you get the StackOverFlowError.
To fix the stackoverflow you should check the return value of your create file, e.g.
```
boolean created = this.createFileMain(path);
if( created ) {
this.writeInFile(path, content);
}
```
To fix your file/directory creation you need to check whether the file already exists and otherwise create it (optionally also creating the parent directories via `file.getParentFile().mkdirs()`).
The problem is that you should know whether you want to create a file or a directory, since you can't tell by the name alone whether the path is meant to be a directory or file name (unless you invent some markup like always ending a directory path with a separator or requiring files to always have an extension). If you want to write some content you need to create a file anyways, a directory would break your code again. | Your `createFileMain` only creates files which already exist.
You don't need to create a file to write to it, all you need is the directory you want to write it into.
```
public void writeInFile(String path, List<String> content) {
File file = new File(path);
File parent = file.getParentFile();
if (parent != null && !parent.exists())
parent.mkdirs();
try (PrintWriter writer = new PrintWriter(path, "ASCII")) {
for (String contentItem : content) {
writer.println(contentItem);
}
writer.close();
} catch (IOException e1) {
//DO STUFF
}
}
``` |
38,740,587 | How do I make sure that a file is not branchable across different projects in UCM ?
It should always be picked from `/main/LATEST/` for all the parallel projects | 2016/08/03 | ['https://Stackoverflow.com/questions/38740587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3119109/'] | Your `createFileMain` only creates files which already exist.
You don't need to create a file to write to it, all you need is the directory you want to write it into.
```
public void writeInFile(String path, List<String> content) {
File file = new File(path);
File parent = file.getParentFile();
if (parent != null && !parent.exists())
parent.mkdirs();
try (PrintWriter writer = new PrintWriter(path, "ASCII")) {
for (String contentItem : content) {
writer.println(contentItem);
}
writer.close();
} catch (IOException e1) {
//DO STUFF
}
}
``` | ```
private boolean createFile(File file) {
if(!file.exists()) {
if(file.getParentFile().exists()) {
// ...
} else { // In this case, neither file nor its parent exist
if(this.createDirectory(file)) {
this.createFile(file); // HERE, you're calling the same method again
} else {
// ...;
}
}
}
return true;
}
```
I believe you want to replace the line marked `HERE` with `this.createFile(file.getParentFile());`. Here what happens is that your function recursively calls itself with the same arguments, so nothing ever happens, and your program gets stuck in a loop until it runs out of stack memory. |
384,030 | So we have realtime events and they are great but the issue we are having is very often we don't need the full "hosepipe" of events only events related to a specific record or user where based on some method they are marked as high risk. Is there any way to filter these events before they are sent to us as 99% of all of these events we have no interest in and are just dropping it seems wasteful. | 2022/08/27 | ['https://salesforce.stackexchange.com/questions/384030', 'https://salesforce.stackexchange.com', 'https://salesforce.stackexchange.com/users/94095/'] | With winter 23 one can easily filter platform event by defining a filter expression via the metadata or the tooling API!
Check out the details [here](https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_filters.htm)
Read more about the General Availability of the [feature](https://help.salesforce.com/s/articleView?id=release-notes.rn_platform_events_filtering_ga.htm&type=5&release=240). | You can use [PushTopic](https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/pushtopic_events_intro.htm) to listen for specific updates, assuming you can define those updates in a SOQL statement. Each client can create a PushTopic to listen for specific events, then cancel them when they see no longer necessary. |
35,455,315 | I have a problem outputting the date which is created within my `PHP` file.
I've been following a tutorial on how to make a really Basic-CMS Platform to help me understand some of the basics for `databases` and `PHP`, everything has been going well up until I was trying to output the date of when the page was created.
This is the error I get
```
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings.
You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of
those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.' in
C:\MAMP\htdocs\basic-cms\page.php:22 Stack trace: #0 C:\MAMP\htdocs\basic-cms\page.php(22): DateTime->__construct('2016-02-17 10:3...') #1 {main} thrown in C:\MAMP\htdocs\basic-cms\page.php on line 22
```
Now when I remove line 22 inside my `page.php` it outputs the full date that is inside the database i.e `2016-02-17 10:38:05` but I'm trying to format it to show the date like `jS M, Y (17th Feb 2016)`.
This is the code inside my `page.php` file
```
if ( $page ) {
$page['created'] = new DateTime( $page['created'] );
if ( $page['updated'] ) {
$page['updated'] = new DateTime( $page['created'] );
}
}
```
Then inside my `show.php` where I'm displaying this I have this code to format the date.
```
Created on <?php echo $page['created']->format('jS M, Y'); ?>
```
Now removing this from my `show.php` doesn't do anything as that's not where the error is contained - but I thought I'd show you guys what I am trying to achieve.
Like I said this is a very Basic-CMS site that I am creating by following a [tutorial on YouTube](https://www.youtube.com/watch?v=Hvb0oeMbH0U&list=PLfdtiltiRHWF0O8kS5D_3-nTzsFiPMOfM&index=4) and I have copied his code exactly and he got no error so I'm sure it has to be a typo I just can't find. | 2016/02/17 | ['https://Stackoverflow.com/questions/35455315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5006451/'] | This is because no timezone has set in php configuration.
Add the following line of code to top of your php.ini file
```
date.timezone = "US/Central"
```
And restart web server
**OR**
you can set it via php script also by using following function:
```
date_default_timezone_set('America/Los_Angeles');
```
Dont forget to reload/restart apache server | **If you're using a database to hold the page details when its created:**
You can actually just add a DateTime Column in your database and then when the page is created and you Insert whatever you need to add, make the Column a default TimeStamp and it should automatically add the time and date the page was created for you.
To then get the TimeStamp out of the database (MySQLi version):
```
$db = mysqli_connect('host', 'user', 'pass', 'dbname');
$result = $db->query("SELECT * FROM tbl_name");
// add an error check here
while($row = mysqli_fetch_array($result)){
if($row['columnPageID'] == 'the page ID you are on'){
$createdOn = $row['columnName'];
}
}
$db->close();
```
This code will **not** work, its so you get an understanding. |
55,641,172 | I'm having some trouble getting the correct output when printing an array. Essentially what I'm trying to do is set up an array in the main method, then send that array to another method that would print out something like this:
```
89 12 33 7 72 42 76 49
69 85 61 23
```
With it being 3 spaces to the right and starting a new print line after the 8th number. Seems easy enough but I get something like this instead.
```
89
69 85 61 23
```
It doesn't print out the values between position 1 and 7 for some reason. This is what I have.
```
public class Test
{
public static void main (String [] args)
{
int [] myInches = {89,12,33,7,72,42,76,49,69,85,61,23};
printArrayValues(myInches);
}
public static void printArrayValues(int [] myInchesParam) {
for (int i = 0; i < 8; i++) {
System.out.print(" " + myInchesParam[i]);
System.out.println();
for (i = 8; i < 12; i++) {
System.out.print(" " + myInchesParam[i]);
}
}
}
}
```
Should I use a do-while instead? Or can I still do it with a for loop and I'm just doing it wrong? | 2019/04/11 | ['https://Stackoverflow.com/questions/55641172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11167410/'] | If you insist on using loops, take @Dason's comment and do the following:
```
for(i in 1:length(Letters)) {
for(j in 1:length(Letters)) {
Combined <- paste0(Letters[i], ' vs ', Letters[j])
print(Combined)
}
}
``` | We can either use `expand.grid` or `CJ` (from `data.table`) and then do a `paste`
```
library(data.table)
CJ(Letters, Letters)[, paste(V1, 'vs', V2)]
``` |
19,940,038 | Is there any way to disable auto-save for `UIManagedDocument` ?
I present `NSManagedObjects` in a controller where the user can add and delete them. But I just want to save those changes when the user explicitly fires a save action. Otherwise I want to discard the changes.
Thanks for your help! | 2013/11/12 | ['https://Stackoverflow.com/questions/19940038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1263739/'] | Can't you override the method below in the `UIManagedDocument` subclass
```
- (void)autosaveWithCompletionHandler:(void (^)(BOOL success))completionHandler
```
EDIT: Here are some additional methods you might want to include. I use the first one to confirm if and when auto-saves were happening and the second to debug certain errors, the details of which can't be obtained any other way. That's all thats in my subclass so its pretty trivial to add this.
```
@implementation YourManagedDocument
- (id)contentsForType:(NSString *)typeName error:(NSError *__autoreleasing *)outError
{
NSLog(@"Auto-Saving Document");
return [super contentsForType:typeName error:outError];
}
- (void)handleError:(NSError *)error userInteractionPermitted:(BOOL)userInteractionPermitted
{
NSLog(@" error: %@", error.localizedDescription);
NSArray* errors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
if(errors != nil && errors.count > 0) {
for (NSError *error in errors) {
NSLog(@" Error: %@", error.userInfo);
}
} else {
NSLog(@" error.userInfo = %@", error.userInfo);
}
}
@end
``` | See [this SO answer](https://stackoverflow.com/a/8425546/953105) for the details, but unless you explicitly save your `NSManagedObjectContext`, you can call `[managedObjectContext rollback]` to undo any changes the user made. |
861,911 | Is it 32 bit, or 64 bit or 128 bit or bigger? | 2009/05/14 | ['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/'] | I would go with 88 bytes. If you look at the ASP.NET state database, that is how it is defined. | Because it's generated as a [System.Guid](http://msdn.microsoft.com/en-us/library/system.guid(VS.90).aspx) Valuetype, it's a 128-bit integer, which is 16 bytes. |
861,911 | Is it 32 bit, or 64 bit or 128 bit or bigger? | 2009/05/14 | ['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/'] | It's neither int nor guid; from the [MSDN help file](http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionidmanager.aspx)...
>
> The ASP.NET session identifier is a randomly generated number encoded into a 24-character string consisting of lowercase characters from a to z and numbers from 0 to 5.
>
>
> | Because it's generated as a [System.Guid](http://msdn.microsoft.com/en-us/library/system.guid(VS.90).aspx) Valuetype, it's a 128-bit integer, which is 16 bytes. |
861,911 | Is it 32 bit, or 64 bit or 128 bit or bigger? | 2009/05/14 | ['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/'] | The reason for the extra 8 characters in the database vs what you get in code is the application id. In the database the session is appended with the tempApplicationID from ASPStateTempApplications table. This is why you get 24 characters in code, and 32 in the db. | Because it's generated as a [System.Guid](http://msdn.microsoft.com/en-us/library/system.guid(VS.90).aspx) Valuetype, it's a 128-bit integer, which is 16 bytes. |
861,911 | Is it 32 bit, or 64 bit or 128 bit or bigger? | 2009/05/14 | ['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/'] | It's neither int nor guid; from the [MSDN help file](http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionidmanager.aspx)...
>
> The ASP.NET session identifier is a randomly generated number encoded into a 24-character string consisting of lowercase characters from a to z and numbers from 0 to 5.
>
>
> | I would go with 88 bytes. If you look at the ASP.NET state database, that is how it is defined. |
861,911 | Is it 32 bit, or 64 bit or 128 bit or bigger? | 2009/05/14 | ['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/'] | The reason for the extra 8 characters in the database vs what you get in code is the application id. In the database the session is appended with the tempApplicationID from ASPStateTempApplications table. This is why you get 24 characters in code, and 32 in the db. | I would go with 88 bytes. If you look at the ASP.NET state database, that is how it is defined. |
861,911 | Is it 32 bit, or 64 bit or 128 bit or bigger? | 2009/05/14 | ['https://Stackoverflow.com/questions/861911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106866/'] | It's neither int nor guid; from the [MSDN help file](http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionidmanager.aspx)...
>
> The ASP.NET session identifier is a randomly generated number encoded into a 24-character string consisting of lowercase characters from a to z and numbers from 0 to 5.
>
>
> | The reason for the extra 8 characters in the database vs what you get in code is the application id. In the database the session is appended with the tempApplicationID from ASPStateTempApplications table. This is why you get 24 characters in code, and 32 in the db. |
56,888 | At work we make websites for other companies. One of our client wanted us to make a e-commerce website for them. Nothing out of the ordinary until we realized they had 50 000+ products to sell and their classification is inexistant. In other words, we don't have ay categories to work with. They just told us to "Put a search bar and it'll be fine".
So, how would you make an e-commerce site work for the users without any kind of browsing through lists of products ?
**EDIT**
The client is a reseller. He sells power outlets, light bulbs, electrical cords and stuff like that. The reselling part is why he doesn't have categories, because every single seller manage their own database with their own description for each product. | 2014/05/07 | ['https://ux.stackexchange.com/questions/56888', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/47784/'] | I would recommend a [masonry-like](http://masonry.desandro.com/) experience as Pinterest implements. Infinite scrolling of all 50k products and have a details page for each one. Keep track of which products are viewed the most on a weekly basis and display those towards the top.
It sounds like this client wants an adventure-like experience with a search bar that searches on just one field; product name.
That is my 1/50th of a dollar; 2 cents =) | Your client might not be able to assign categories to products, but there is noting stopping them assigning categories to *sellers*.
The kind of sellers using a resale ecommerce site are likely to be specialists in certain categories already, rather than having a diverse range of products (e.g. there will likely be sellers that specialise in lightbulbs and related items). You could build loose categories around this information to augment the search functionality. For example you could have an option to "view more sellers like this", or "view all items from similar sellers". |
56,888 | At work we make websites for other companies. One of our client wanted us to make a e-commerce website for them. Nothing out of the ordinary until we realized they had 50 000+ products to sell and their classification is inexistant. In other words, we don't have ay categories to work with. They just told us to "Put a search bar and it'll be fine".
So, how would you make an e-commerce site work for the users without any kind of browsing through lists of products ?
**EDIT**
The client is a reseller. He sells power outlets, light bulbs, electrical cords and stuff like that. The reselling part is why he doesn't have categories, because every single seller manage their own database with their own description for each product. | 2014/05/07 | ['https://ux.stackexchange.com/questions/56888', 'https://ux.stackexchange.com', 'https://ux.stackexchange.com/users/47784/'] | I would recommend a [masonry-like](http://masonry.desandro.com/) experience as Pinterest implements. Infinite scrolling of all 50k products and have a details page for each one. Keep track of which products are viewed the most on a weekly basis and display those towards the top.
It sounds like this client wants an adventure-like experience with a search bar that searches on just one field; product name.
That is my 1/50th of a dollar; 2 cents =) | If there is no way of categorizing the products then search must be the primary method of traversing the catalog. But as a previous answer suggests you should guide the user with top products sold for a search, top products viewed for a search etc. The other users behavior should help guide them, consider adding a method for users to tag products to build the categories may be an option. You may also be able to build a straw man structure by querying the product names for things like bulb, switch, socket etc and start with that to see what sort of a category structure may be involved. |