qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
53,452,226 | In C++, if I try to do this:
```
std::function<void(bool,void)>
```
then the compiler will throw errors. Why is this? It's useful in many cases. One example:
```
//g++ -std=c++17 prblm.cpp
#include <cstdio>
#include <functional>
template<class type_t>
class some_callback
{
public:
using callback_t = std::function<void(bool,type_t)>;
some_callback(callback_t _myfunc)
{
this->myfunc = _myfunc;
}
callback_t myfunc;
};
using callback_with_just_bool = some_callback<void>;
using callback_with_an_int_too = some_callback<int>;
int main()
{
auto my_callback_with_int = callback_with_an_int_too([](bool x, int y)
{
}); //OK
auto my_callback_just_bool = callback_with_just_bool([](bool x)
{
}); //Error
auto my_callback_just_bool = callback_with_just_bool([](bool x,void z)
{
}); //Error
return 0;
}
```
This allows for a very clean syntax if the user would like to optionally have additional data in their callback, but not have to. However, the compiler will reject code that tries to initialize an object of `callback_with_just_bool`
Why is it like this, and is there a clean way around it? Thanks.
Edit: The specific reason I'm trying to do this, in real world code, is in an event system. There is data provided to the event system about an individual object that wishes to *conditionally* receive events (e.x. "if you're close enough to the source, you'll receive a sound event") as well as data provided to a callback *about* the event (e.x. "a 10khz noise at X200 Y200"). Most of the time, the data needed to check the requirements will exist inside the data provided to the callback *about* the event, but I wanted to provided an optional additional data structure if that was not the case. Hence, the user would specify "void" if they didn't need this additional data structure. | 2018/11/23 | [
"https://Stackoverflow.com/questions/53452226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10438811/"
] | *"Why is this?"*
Because the only permitted usage of `void` in a parameter list is to show that the function doesn't accept any parameters.
From [[function]](https://en.cppreference.com/w/cpp/language/function):
>
> `void`
>
>
> Indicates that the function takes no parameters, it is the exact synonym for an empty parameter list: `int f(void);` and `int f();` declare the same function. Note that the type void (possibly cv-qualified) cannot be used in a parameter list otherwise: `int f(void, int);` and `int f(const void);` are errors (although derived types, such as `void*` can be used)
>
>
>
*"Is there a clean way around it?"*
I would suggest to specialize for `void`:
```
template<class type_t>
class some_callback
{
std::function<void(bool,type_t)> myfunc;
};
template<>
class some_callback<void>
{
std::function<void(bool)> myfunc;
};
``` | Other answers have explained the why. This answers "is there a clean way around it?"
What I usually do for callbacks is use lambdas.
```
std::function<void(void)> myfunc;
bool b = false;
int i = 42;
myfunc = [&]() { if (b) ++i; };
``` |
53,452,226 | In C++, if I try to do this:
```
std::function<void(bool,void)>
```
then the compiler will throw errors. Why is this? It's useful in many cases. One example:
```
//g++ -std=c++17 prblm.cpp
#include <cstdio>
#include <functional>
template<class type_t>
class some_callback
{
public:
using callback_t = std::function<void(bool,type_t)>;
some_callback(callback_t _myfunc)
{
this->myfunc = _myfunc;
}
callback_t myfunc;
};
using callback_with_just_bool = some_callback<void>;
using callback_with_an_int_too = some_callback<int>;
int main()
{
auto my_callback_with_int = callback_with_an_int_too([](bool x, int y)
{
}); //OK
auto my_callback_just_bool = callback_with_just_bool([](bool x)
{
}); //Error
auto my_callback_just_bool = callback_with_just_bool([](bool x,void z)
{
}); //Error
return 0;
}
```
This allows for a very clean syntax if the user would like to optionally have additional data in their callback, but not have to. However, the compiler will reject code that tries to initialize an object of `callback_with_just_bool`
Why is it like this, and is there a clean way around it? Thanks.
Edit: The specific reason I'm trying to do this, in real world code, is in an event system. There is data provided to the event system about an individual object that wishes to *conditionally* receive events (e.x. "if you're close enough to the source, you'll receive a sound event") as well as data provided to a callback *about* the event (e.x. "a 10khz noise at X200 Y200"). Most of the time, the data needed to check the requirements will exist inside the data provided to the callback *about* the event, but I wanted to provided an optional additional data structure if that was not the case. Hence, the user would specify "void" if they didn't need this additional data structure. | 2018/11/23 | [
"https://Stackoverflow.com/questions/53452226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10438811/"
] | Variadic templates are one way to do this:
```
template <class... T>
struct some_callback
{
std::function<void(bool, T...)> myfunc;
};
using callback_with_just_bool = some_callback<>;
using callback_with_an_int_too = some_callback<int>;
```
This is even cleaner with an alias template:
```
template <class... T> using callback_type = std::function<void(bool, T...)>;
int main()
{
callback_type<int> my_callback_with_int = [](bool x, int y)
{
}; //OK
callback_type<> my_callback_just_bool = [](bool x)
{
}; //OK now too...
}
``` | Other answers have explained the why. This answers "is there a clean way around it?"
What I usually do for callbacks is use lambdas.
```
std::function<void(void)> myfunc;
bool b = false;
int i = 42;
myfunc = [&]() { if (b) ++i; };
``` |
1,782,545 | How / where do I store settings in a windows mobile 6 application (targeting compact framework 3.5)?
Is there some mechanism like the properties.settings for desktop? | 2009/11/23 | [
"https://Stackoverflow.com/questions/1782545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021/"
] | Unfortunately, the System.Configuration is missing from .NET Compact Framework.
You can use the [Smart Device Framework](http://www.opennetcf.com/Products/SmartDeviceFramework/tabid/65/Default.aspx) or you can just create a class that stores your settings and the save it and load it using a [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx). | It would be best to use the config settings class to do the job for you. Alternatively, for more flexibility, use an INI class handler (there are a good few out there, look for Windows mobile platform portability). [Nini](http://nini.sourceforge.net/) would be your best bet! Hope this helps, Best regards,
Tom. |
1,782,545 | How / where do I store settings in a windows mobile 6 application (targeting compact framework 3.5)?
Is there some mechanism like the properties.settings for desktop? | 2009/11/23 | [
"https://Stackoverflow.com/questions/1782545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021/"
] | Or just store the stuff in the registry, which is what I ended up doing. | It would be best to use the config settings class to do the job for you. Alternatively, for more flexibility, use an INI class handler (there are a good few out there, look for Windows mobile platform portability). [Nini](http://nini.sourceforge.net/) would be your best bet! Hope this helps, Best regards,
Tom. |
115,147 | Every time I go to break a block in Minecraft it opens the in-game menu.
I don't know how to stop this from happening, any ideas? | 2013/04/25 | [
"https://gaming.stackexchange.com/questions/115147",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/47528/"
] | Try looking at your controls, I think that you have it so that if you left-click it opens the menu instead of Esc. | It's a Java bug. Try downloading and installing a different (newer, older, whatever) Java VM. As a workaround, hit more slowly, one click at a time. The bug seems to trigger when you hold the mouse button down for repeated clicks. |
6,013,339 | How do I turn this, which uses two calls two `children`:
```
$('#id tr').children('td').children('input')
```
into something that calls children only once? I am trying to select every input text box inside a particular table row (`tr`) that's a child of `#id`. I've tried
```
$('#id tr').children('td input')
```
and
```
$('#id tr').children('td > input')
```
But neither of those work. I'm kinda new to these selector expressions, so sorry if it's obvious. | 2011/05/16 | [
"https://Stackoverflow.com/questions/6013339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726361/"
] | Although I like the `$("#id tr td input")` suggestions, in some cases (e.g. if you had the `$("#id tr")` object from some other source) you might instead be looking for [`.find()`](http://api.jquery.com/find/), which goes multiple levels deep (instead of `.children()` which only goes one):
```
$("#id tr").find("td input")
``` | Why not just `$('#id tr input')`?
Or maybe `$('#id input')` |
6,013,339 | How do I turn this, which uses two calls two `children`:
```
$('#id tr').children('td').children('input')
```
into something that calls children only once? I am trying to select every input text box inside a particular table row (`tr`) that's a child of `#id`. I've tried
```
$('#id tr').children('td input')
```
and
```
$('#id tr').children('td > input')
```
But neither of those work. I'm kinda new to these selector expressions, so sorry if it's obvious. | 2011/05/16 | [
"https://Stackoverflow.com/questions/6013339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726361/"
] | Why not just `$('#id tr input')`?
Or maybe `$('#id input')` | U can set a class for your inputs and select it
`$('#id tr').children('td:input').hasclass('class name')` |
6,013,339 | How do I turn this, which uses two calls two `children`:
```
$('#id tr').children('td').children('input')
```
into something that calls children only once? I am trying to select every input text box inside a particular table row (`tr`) that's a child of `#id`. I've tried
```
$('#id tr').children('td input')
```
and
```
$('#id tr').children('td > input')
```
But neither of those work. I'm kinda new to these selector expressions, so sorry if it's obvious. | 2011/05/16 | [
"https://Stackoverflow.com/questions/6013339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726361/"
] | Why not just `$('#id tr input')`?
Or maybe `$('#id input')` | I'm amazed no one suggested this one:
```
$('td input', '#idc tr')
```
Which will allow you to have the `#idc tr` part from a variable. Basically what you're doing is doing a concatenation; so you read the right selector first, and then the left one, for instance:
```
$('> input', 'div')
```
Is the equivalent of:
```
$('div > input')
```
Now, lets do some golf here; the way you're passing the selector could be simplified to this two forms:
```
$('input', '#idc td')
// vs
$('#id').find('td input')
```
Both basically do the same, however as you may have noticed, the second one allows you to do jquery chaining; using `.end()` to go back to the previous selector `#id`.
I usually use the first statement whenever I need to do something simple that doesn't require me going back to the previous selector. |
6,013,339 | How do I turn this, which uses two calls two `children`:
```
$('#id tr').children('td').children('input')
```
into something that calls children only once? I am trying to select every input text box inside a particular table row (`tr`) that's a child of `#id`. I've tried
```
$('#id tr').children('td input')
```
and
```
$('#id tr').children('td > input')
```
But neither of those work. I'm kinda new to these selector expressions, so sorry if it's obvious. | 2011/05/16 | [
"https://Stackoverflow.com/questions/6013339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726361/"
] | Although I like the `$("#id tr td input")` suggestions, in some cases (e.g. if you had the `$("#id tr")` object from some other source) you might instead be looking for [`.find()`](http://api.jquery.com/find/), which goes multiple levels deep (instead of `.children()` which only goes one):
```
$("#id tr").find("td input")
``` | U can set a class for your inputs and select it
`$('#id tr').children('td:input').hasclass('class name')` |
6,013,339 | How do I turn this, which uses two calls two `children`:
```
$('#id tr').children('td').children('input')
```
into something that calls children only once? I am trying to select every input text box inside a particular table row (`tr`) that's a child of `#id`. I've tried
```
$('#id tr').children('td input')
```
and
```
$('#id tr').children('td > input')
```
But neither of those work. I'm kinda new to these selector expressions, so sorry if it's obvious. | 2011/05/16 | [
"https://Stackoverflow.com/questions/6013339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726361/"
] | Although I like the `$("#id tr td input")` suggestions, in some cases (e.g. if you had the `$("#id tr")` object from some other source) you might instead be looking for [`.find()`](http://api.jquery.com/find/), which goes multiple levels deep (instead of `.children()` which only goes one):
```
$("#id tr").find("td input")
``` | I'm amazed no one suggested this one:
```
$('td input', '#idc tr')
```
Which will allow you to have the `#idc tr` part from a variable. Basically what you're doing is doing a concatenation; so you read the right selector first, and then the left one, for instance:
```
$('> input', 'div')
```
Is the equivalent of:
```
$('div > input')
```
Now, lets do some golf here; the way you're passing the selector could be simplified to this two forms:
```
$('input', '#idc td')
// vs
$('#id').find('td input')
```
Both basically do the same, however as you may have noticed, the second one allows you to do jquery chaining; using `.end()` to go back to the previous selector `#id`.
I usually use the first statement whenever I need to do something simple that doesn't require me going back to the previous selector. |
6,013,339 | How do I turn this, which uses two calls two `children`:
```
$('#id tr').children('td').children('input')
```
into something that calls children only once? I am trying to select every input text box inside a particular table row (`tr`) that's a child of `#id`. I've tried
```
$('#id tr').children('td input')
```
and
```
$('#id tr').children('td > input')
```
But neither of those work. I'm kinda new to these selector expressions, so sorry if it's obvious. | 2011/05/16 | [
"https://Stackoverflow.com/questions/6013339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726361/"
] | I'm amazed no one suggested this one:
```
$('td input', '#idc tr')
```
Which will allow you to have the `#idc tr` part from a variable. Basically what you're doing is doing a concatenation; so you read the right selector first, and then the left one, for instance:
```
$('> input', 'div')
```
Is the equivalent of:
```
$('div > input')
```
Now, lets do some golf here; the way you're passing the selector could be simplified to this two forms:
```
$('input', '#idc td')
// vs
$('#id').find('td input')
```
Both basically do the same, however as you may have noticed, the second one allows you to do jquery chaining; using `.end()` to go back to the previous selector `#id`.
I usually use the first statement whenever I need to do something simple that doesn't require me going back to the previous selector. | U can set a class for your inputs and select it
`$('#id tr').children('td:input').hasclass('class name')` |
61,278 | What method do you use when you want to get performance data about specific code paths? | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | I do my profiles by creating two classes: `cProfile` and `cProfileManager`.
`cProfileManager` will hold all the data that resulted from `cProfile`.
`cProfile` with have the following requirements:
* `cProfile` has a constructor which initializes the current time.
* `cProfile` has a deconstructor which sends the total time the class was alive to `cProfileManager`
To use these profile classes, I first make an instance of `cProfileManager`. Then, I put the code block, which I want to profile, inside curly braces. Inside the curly braces, I create a `cProfile` instance. When the code block ends, `cProfile` will send the time it took for the block of code to finish to `cProfileManager`.
**Example Code**
Here's an example of the code (simplified):
```
class cProfile
{
cProfile()
{
TimeStart = GetTime();
};
~cProfile()
{
ProfileManager->AddProfile (GetTime() - TimeStart);
}
float TimeStart;
}
```
To use `cProfile`, I would do something like this:
```
int main()
{
printf("Start test");
{
cProfile Profile;
Calculate();
}
ProfileManager->OutputData();
}
```
or this:
```
void foobar()
{
cProfile ProfileFoobar;
foo();
{
cProfile ProfileBarCheck;
while (bar())
{
cProfile ProfileSpam;
spam();
}
}
}
```
**Technical Note**
This code is actually an abuse of the way scoping, constructors and deconstructors work in [C++](http://en.wikipedia.org/wiki/C_%28programming_language%29). `cProfile` exists only inside the block scope (the code block we want to test). Once the program leaves the block scope, `cProfile` records the result.
**Additional Enhancements**
* You can add a string parameter to the constructor so you can do something like this:
cProfile Profile("Profile for complicated calculation");
* You can use a macro to make the code look cleaner (be careful not to abuse this. Unlike our other abuses on the language, macros can be dangerous when used).
Example:
#define START\_PROFILE cProfile Profile(); {
#define END\_PROFILE }
* `cProfileManager` can check how many times a block of code is called. But you would need an identifier for the block of code. The first enhancement can help identify the block. This can be useful in cases where the code you want to profile is inside a loop (like the second example aboe). You can also add the average, fastest and longest execution time the code block took.
* Don't forget to add a check to skip profiling if you are in debug mode. | I have a quick-and-dirty profiling class that can be used in profiling in even the most tight inner loops. The emphasis is on extreme light weight and simple code. The class allocates a two-dimensional array of fixed size. I then add "checkpoint" calls all over the place. When checkpoint N is reached immediately after checkpoint M, I add the time elapsed (in microseconds) to the array item [M,N]. Since this is designed to profile tight loops, I also have "start of iteration" call that resets the the "last checkpoint" variable. At the end of test, the `dumpResults()` call produces the list of all pairs of checkpoints that followed each other, together with total time accounted for and unaccounted for. |
61,278 | What method do you use when you want to get performance data about specific code paths? | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.
1. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).
2. It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now.
3. Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't.
---
I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with [DbgView](http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx)), including how many times the code was executed (and the average time spent of course)).
```
#pragma once
#include <tchar.h>
#include <windows.h>
#include <sstream>
#include <boost/noncopyable.hpp>
namespace scope_timer {
class time_collector : boost::noncopyable {
__int64 total;
LARGE_INTEGER start;
size_t times;
const TCHAR* name;
double cpu_frequency()
{ // cache the CPU frequency, which doesn't change.
static double ret = 0; // store as double so devision later on is floating point and not truncating
if (ret == 0) {
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
ret = static_cast<double>(freq.QuadPart);
}
return ret;
}
bool in_use;
public:
time_collector(const TCHAR* n)
: times(0)
, name(n)
, total(0)
, start(LARGE_INTEGER())
, in_use(false)
{
}
~time_collector()
{
std::basic_ostringstream<TCHAR> msg;
msg << _T("scope_timer> ") << name << _T(" called: ");
double seconds = total / cpu_frequency();
double average = seconds / times;
msg << times << _T(" times total time: ") << seconds << _T(" seconds ")
<< _T(" (avg ") << average <<_T(")\n");
OutputDebugString(msg.str().c_str());
}
void add_time(__int64 ticks)
{
total += ticks;
++times;
in_use = false;
}
bool aquire()
{
if (in_use)
return false;
in_use = true;
return true;
}
};
class one_time : boost::noncopyable {
LARGE_INTEGER start;
time_collector* collector;
public:
one_time(time_collector& tc)
{
if (tc.aquire()) {
collector = &tc;
QueryPerformanceCounter(&start);
}
else
collector = 0;
}
~one_time()
{
if (collector) {
LARGE_INTEGER end;
QueryPerformanceCounter(&end);
collector->add_time(end.QuadPart - start.QuadPart);
}
}
};
}
// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)
#define TIME_THIS_SCOPE(name) \
static scope_timer::time_collector st_time_collector_##name(_T(#name)); \
scope_timer::one_time st_one_time_##name(st_time_collector_##name)
``` | I do my profiles by creating two classes: `cProfile` and `cProfileManager`.
`cProfileManager` will hold all the data that resulted from `cProfile`.
`cProfile` with have the following requirements:
* `cProfile` has a constructor which initializes the current time.
* `cProfile` has a deconstructor which sends the total time the class was alive to `cProfileManager`
To use these profile classes, I first make an instance of `cProfileManager`. Then, I put the code block, which I want to profile, inside curly braces. Inside the curly braces, I create a `cProfile` instance. When the code block ends, `cProfile` will send the time it took for the block of code to finish to `cProfileManager`.
**Example Code**
Here's an example of the code (simplified):
```
class cProfile
{
cProfile()
{
TimeStart = GetTime();
};
~cProfile()
{
ProfileManager->AddProfile (GetTime() - TimeStart);
}
float TimeStart;
}
```
To use `cProfile`, I would do something like this:
```
int main()
{
printf("Start test");
{
cProfile Profile;
Calculate();
}
ProfileManager->OutputData();
}
```
or this:
```
void foobar()
{
cProfile ProfileFoobar;
foo();
{
cProfile ProfileBarCheck;
while (bar())
{
cProfile ProfileSpam;
spam();
}
}
}
```
**Technical Note**
This code is actually an abuse of the way scoping, constructors and deconstructors work in [C++](http://en.wikipedia.org/wiki/C_%28programming_language%29). `cProfile` exists only inside the block scope (the code block we want to test). Once the program leaves the block scope, `cProfile` records the result.
**Additional Enhancements**
* You can add a string parameter to the constructor so you can do something like this:
cProfile Profile("Profile for complicated calculation");
* You can use a macro to make the code look cleaner (be careful not to abuse this. Unlike our other abuses on the language, macros can be dangerous when used).
Example:
#define START\_PROFILE cProfile Profile(); {
#define END\_PROFILE }
* `cProfileManager` can check how many times a block of code is called. But you would need an identifier for the block of code. The first enhancement can help identify the block. This can be useful in cases where the code you want to profile is inside a loop (like the second example aboe). You can also add the average, fastest and longest execution time the code block took.
* Don't forget to add a check to skip profiling if you are in debug mode. |
61,278 | What method do you use when you want to get performance data about specific code paths? | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | Note, the following is all written specifically for Windows.
I also have a timer class that I wrote to do quick-and-dirty profiling that uses QueryPerformanceCounter() to get high-precision timings, but with a slight difference. My timer class doesn't dump the elapsed time when the Timer object falls out of scope. Instead, it accumulates the elapsed times in to an collection. I added a static member function, Dump(), which creates a table of elapsed times, sorted by timing category (specified in Timer's constructor as a string) along with some statistical analysis such as mean elapsed time, standard deviation, max and min. I also added a Clear() static member function which clears the collection & lets you start over again.
**How to use the Timer class (psudocode):**
```
int CInsertBuffer::Read(char* pBuf)
{
// TIMER NOTES: Avg Execution Time = ~1 ms
Timer timer("BufferRead");
: :
return -1;
}
```
**Sample output :**
```
Timer Precision = 418.0095 ps
=== Item Trials Ttl Time Avg Time Mean Time StdDev ===
AddTrade 500 7 ms 14 us 12 us 24 us
BufferRead 511 1:19.25 0.16 s 621 ns 2.48 s
BufferWrite 516 511 us 991 ns 482 ns 11 us
ImportPos Loop 1002 18.62 s 19 ms 77 us 0.51 s
ImportPosition 2 18.75 s 9.38 s 16.17 s 13.59 s
Insert 515 4.26 s 8 ms 5 ms 27 ms
recv 101 18.54 s 0.18 s 2603 ns 1.63 s
```
**file Timer.inl :**
```
#include <map>
#include "x:\utils\stlext\stringext.h"
#include <iterator>
#include <set>
#include <vector>
#include <numeric>
#include "x:\utils\stlext\algorithmext.h"
#include <math.h>
class Timer
{
public:
Timer(const char* name)
{
label = std::safe_string(name);
QueryPerformanceCounter(&startTime);
}
virtual ~Timer()
{
QueryPerformanceCounter(&stopTime);
__int64 clocks = stopTime.QuadPart-startTime.QuadPart;
double elapsed = (double)clocks/(double)TimerFreq();
TimeMap().insert(std::make_pair(label,elapsed));
};
static std::string Dump(bool ClipboardAlso=true)
{
static const std::string loc = "Timer::Dump";
if( TimeMap().empty() )
{
return "No trials\r\n";
}
std::string ret = std::formatstr("\r\n\r\nTimer Precision = %s\r\n\r\n", format_elapsed(1.0/(double)TimerFreq()).c_str());
// get a list of keys
typedef std::set<std::string> keyset;
keyset keys;
std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());
size_t maxrows = 0;
typedef std::vector<std::string> strings;
strings lines;
static const size_t tabWidth = 9;
std::string head = std::formatstr("=== %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s ===", tabWidth*2, tabWidth*2, "Item", tabWidth, tabWidth, "Trials", tabWidth, tabWidth, "Ttl Time", tabWidth, tabWidth, "Avg Time", tabWidth, tabWidth, "Mean Time", tabWidth, tabWidth, "StdDev");
ret += std::formatstr("\r\n%s\r\n", head.c_str());
if( ClipboardAlso )
lines.push_back("Item\tTrials\tTtl Time\tAvg Time\tMean Time\tStdDev\r\n");
// dump the values for each key
{for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )
{
time_type ttl = 0;
ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));
size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));
if( num > maxrows )
maxrows = num;
time_type avg = ttl / num;
// compute mean
std::vector<time_type> sortedTimes;
std::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));
std::sort(sortedTimes.begin(), sortedTimes.end());
size_t mid = (size_t)floor((double)num/2.0);
double mean = ( num > 1 && (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];
// compute variance
double sum = 0.0;
if( num > 1 )
{
for( std::vector<time_type>::iterator timeIt = sortedTimes.begin(); sortedTimes.end() != timeIt; ++timeIt )
sum += pow(*timeIt-mean,2.0);
}
// compute std dev
double stddev = num > 1 ? sqrt(sum/((double)num-1.0)) : 0.0;
ret += std::formatstr(" %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s\r\n", tabWidth*2, tabWidth*2, key->c_str(), tabWidth, tabWidth, std::formatstr("%d",num).c_str(), tabWidth, tabWidth, format_elapsed(ttl).c_str(), tabWidth, tabWidth, format_elapsed(avg).c_str(), tabWidth, tabWidth, format_elapsed(mean).c_str(), tabWidth, tabWidth, format_elapsed(stddev).c_str());
if( ClipboardAlso )
lines.push_back(std::formatstr("%s\t%s\t%s\t%s\t%s\t%s\r\n", key->c_str(), std::formatstr("%d",num).c_str(), format_elapsed(ttl).c_str(), format_elapsed(avg).c_str(), format_elapsed(mean).c_str(), format_elapsed(stddev).c_str()));
}
}
ret += std::formatstr("%s\r\n", std::string(head.length(),'=').c_str());
if( ClipboardAlso )
{
// dump header row of data block
lines.push_back("");
{
std::string s;
for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
{
if( key != keys.begin() )
s.append("\t");
s.append(*key);
}
s.append("\r\n");
lines.push_back(s);
}
// blow out the flat map of time values to a seperate vector of times for each key
typedef std::map<std::string, std::vector<time_type> > nodematrix;
nodematrix nodes;
for( Times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )
nodes[time->first].push_back(time->second);
// dump each data point
for( size_t row = 0; row < maxrows; ++row )
{
std::string rowDump;
for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
{
if( key != keys.begin() )
rowDump.append("\t");
if( nodes[*key].size() > row )
rowDump.append(std::formatstr("%f", nodes[*key][row]));
}
rowDump.append("\r\n");
lines.push_back(rowDump);
}
// dump to the clipboard
std::string dump;
for( strings::iterator s = lines.begin(); s != lines.end(); ++s )
{
dump.append(*s);
}
OpenClipboard(0);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);
if( hg != 0 )
{
char* buf = (char*)GlobalLock(hg);
if( buf != 0 )
{
std::copy(dump.begin(), dump.end(), buf);
buf[dump.length()] = 0;
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
}
}
CloseClipboard();
}
return ret;
}
static void Reset()
{
TimeMap().clear();
}
static std::string format_elapsed(double d)
{
if( d < 0.00000001 )
{
// show in ps with 4 digits
return std::formatstr("%0.4f ps", d * 1000000000000.0);
}
if( d < 0.00001 )
{
// show in ns
return std::formatstr("%0.0f ns", d * 1000000000.0);
}
if( d < 0.001 )
{
// show in us
return std::formatstr("%0.0f us", d * 1000000.0);
}
if( d < 0.1 )
{
// show in ms
return std::formatstr("%0.0f ms", d * 1000.0);
}
if( d <= 60.0 )
{
// show in seconds
return std::formatstr("%0.2f s", d);
}
if( d < 3600.0 )
{
// show in min:sec
return std::formatstr("%01.0f:%02.2f", floor(d/60.0), fmod(d,60.0));
}
// show in h:min:sec
return std::formatstr("%01.0f:%02.0f:%02.2f", floor(d/3600.0), floor(fmod(d,3600.0)/60.0), fmod(d,60.0));
}
private:
static __int64 TimerFreq()
{
static __int64 freq = 0;
static bool init = false;
if( !init )
{
LARGE_INTEGER li;
QueryPerformanceFrequency(&li);
freq = li.QuadPart;
init = true;
}
return freq;
}
LARGE_INTEGER startTime, stopTime;
std::string label;
typedef std::string key_type;
typedef double time_type;
typedef std::multimap<key_type, time_type> Times;
// static Times times;
static Times& TimeMap()
{
static Times times_;
return times_;
}
struct extract_key : public std::unary_function<Times::value_type, key_type>
{
std::string operator()(Times::value_type const & r) const
{
return r.first;
}
};
struct extract_val : public std::unary_function<Times::value_type, time_type>
{
time_type operator()(Times::value_type const & r) const
{
return r.second;
}
};
struct match_key : public std::unary_function<Times::value_type, bool>
{
match_key(key_type const & key_) : key(key_) {};
bool operator()(Times::value_type const & rhs) const
{
return key == rhs.first;
}
private:
match_key& operator=(match_key&) { return * this; }
const key_type key;
};
struct accum_key : public std::binary_function<time_type, Times::value_type, time_type>
{
accum_key(key_type const & key_) : key(key_), n(0) {};
time_type operator()(time_type const & v, Times::value_type const & rhs) const
{
if( key == rhs.first )
{
++n;
return rhs.second + v;
}
return v;
}
private:
accum_key& operator=(accum_key&) { return * this; }
const Times::key_type key;
mutable size_t n;
};
};
```
**file stringext.h (provides formatstr() function):**
```
namespace std
{
/* ---
Formatted Print
template<class C>
int strprintf(basic_string<C>* pString, const C* pFmt, ...);
template<class C>
int vstrprintf(basic_string<C>* pString, const C* pFmt, va_list args);
Returns :
# characters printed to output
Effects :
Writes formatted data to a string. strprintf() works exactly the same as sprintf(); see your
documentation for sprintf() for details of peration. vstrprintf() also works the same as sprintf(),
but instead of accepting a variable paramater list it accepts a va_list argument.
Requires :
pString is a pointer to a basic_string<>
--- */
template<class char_type> int vprintf_generic(char_type* buffer, size_t bufferSize, const char_type* format, va_list argptr);
template<> inline int vprintf_generic<char>(char* buffer, size_t bufferSize, const char* format, va_list argptr)
{
# ifdef SECURE_VSPRINTF
return _vsnprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);
# else
return _vsnprintf(buffer, bufferSize-1, format, argptr);
# endif
}
template<> inline int vprintf_generic<wchar_t>(wchar_t* buffer, size_t bufferSize, const wchar_t* format, va_list argptr)
{
# ifdef SECURE_VSPRINTF
return _vsnwprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);
# else
return _vsnwprintf(buffer, bufferSize-1, format, argptr);
# endif
}
template<class Type, class Traits>
inline int vstringprintf(basic_string<Type,Traits> & outStr, const Type* format, va_list args)
{
// prologue
static const size_t ChunkSize = 1024;
size_t curBufSize = 0;
outStr.erase();
if( !format )
{
return 0;
}
// keep trying to write the string to an ever-increasing buffer until
// either we get the string written or we run out of memory
while( bool cont = true )
{
// allocate a local buffer
curBufSize += ChunkSize;
std::ref_ptr<Type> localBuffer = new Type[curBufSize];
if( localBuffer.get() == 0 )
{
// we ran out of memory -- nice goin'!
return -1;
}
// format output to local buffer
int i = vprintf_generic(localBuffer.get(), curBufSize * sizeof(Type), format, args);
if( -1 == i )
{
// the buffer wasn't big enough -- try again
continue;
}
else if( i < 0 )
{
// something wierd happened -- bail
return i;
}
// if we get to this point the string was written completely -- stop looping
outStr.assign(localBuffer.get(),i);
return i;
}
// unreachable code
return -1;
};
// provided for backward-compatibility
template<class Type, class Traits>
inline int vstrprintf(basic_string<Type,Traits> * outStr, const Type* format, va_list args)
{
return vstringprintf(*outStr, format, args);
}
template<class Char, class Traits>
inline int stringprintf(std::basic_string<Char, Traits> & outString, const Char* format, ...)
{
va_list args;
va_start(args, format);
int retval = vstringprintf(outString, format, args);
va_end(args);
return retval;
}
// old function provided for backward-compatibility
template<class Char, class Traits>
inline int strprintf(std::basic_string<Char, Traits> * outString, const Char* format, ...)
{
va_list args;
va_start(args, format);
int retval = vstringprintf(*outString, format, args);
va_end(args);
return retval;
}
/* ---
Inline Formatted Print
string strprintf(const char* Format, ...);
Returns :
Formatted string
Effects :
Writes formatted data to a string. formatstr() works the same as sprintf(); see your
documentation for sprintf() for details of operation.
--- */
template<class Char>
inline std::basic_string<Char> formatstr(const Char * format, ...)
{
std::string outString;
va_list args;
va_start(args, format);
vstringprintf(outString, format, args);
va_end(args);
return outString;
}
};
```
**File algorithmext.h (provides transform\_if() function) :**
```
/* ---
Transform
25.2.3
template<class InputIterator, class OutputIterator, class UnaryOperation, class Predicate>
OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op, Predicate pred)
template<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate>
OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op, Predicate pred)
Requires:
T is of type EqualityComparable (20.1.1)
op and binary_op have no side effects
Effects :
Assigns through every iterator i in the range [result, result + (last1-first1)) a new corresponding value equal to one of:
1: op( *(first1 + (i - result))
2: binary_op( *(first1 + (i - result), *(first2 + (i - result))
Returns :
result + (last1 - first1)
Complexity :
At most last1 - first1 applications of op or binary_op
--- */
template<class InputIterator, class OutputIterator, class UnaryFunction, class Predicate>
OutputIterator transform_if(InputIterator first,
InputIterator last,
OutputIterator result,
UnaryFunction f,
Predicate pred)
{
for (; first != last; ++first)
{
if( pred(*first) )
*result++ = f(*first);
}
return result;
}
template<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate>
OutputIterator transform_if(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
OutputIterator result,
BinaryOperation binary_op,
Predicate pred)
{
for (; first1 != last1 ; ++first1, ++first2)
{
if( pred(*first1) )
*result++ = binary_op(*first1,*first2);
}
return result;
}
``` | The article *Code profiler and optimizations* has lots of information about C++ code profiling and also has a free download link to a program/class that will show you a graphic presentation for different code paths/methods. |
61,278 | What method do you use when you want to get performance data about specific code paths? | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | I do my profiles by creating two classes: `cProfile` and `cProfileManager`.
`cProfileManager` will hold all the data that resulted from `cProfile`.
`cProfile` with have the following requirements:
* `cProfile` has a constructor which initializes the current time.
* `cProfile` has a deconstructor which sends the total time the class was alive to `cProfileManager`
To use these profile classes, I first make an instance of `cProfileManager`. Then, I put the code block, which I want to profile, inside curly braces. Inside the curly braces, I create a `cProfile` instance. When the code block ends, `cProfile` will send the time it took for the block of code to finish to `cProfileManager`.
**Example Code**
Here's an example of the code (simplified):
```
class cProfile
{
cProfile()
{
TimeStart = GetTime();
};
~cProfile()
{
ProfileManager->AddProfile (GetTime() - TimeStart);
}
float TimeStart;
}
```
To use `cProfile`, I would do something like this:
```
int main()
{
printf("Start test");
{
cProfile Profile;
Calculate();
}
ProfileManager->OutputData();
}
```
or this:
```
void foobar()
{
cProfile ProfileFoobar;
foo();
{
cProfile ProfileBarCheck;
while (bar())
{
cProfile ProfileSpam;
spam();
}
}
}
```
**Technical Note**
This code is actually an abuse of the way scoping, constructors and deconstructors work in [C++](http://en.wikipedia.org/wiki/C_%28programming_language%29). `cProfile` exists only inside the block scope (the code block we want to test). Once the program leaves the block scope, `cProfile` records the result.
**Additional Enhancements**
* You can add a string parameter to the constructor so you can do something like this:
cProfile Profile("Profile for complicated calculation");
* You can use a macro to make the code look cleaner (be careful not to abuse this. Unlike our other abuses on the language, macros can be dangerous when used).
Example:
#define START\_PROFILE cProfile Profile(); {
#define END\_PROFILE }
* `cProfileManager` can check how many times a block of code is called. But you would need an identifier for the block of code. The first enhancement can help identify the block. This can be useful in cases where the code you want to profile is inside a loop (like the second example aboe). You can also add the average, fastest and longest execution time the code block took.
* Don't forget to add a check to skip profiling if you are in debug mode. | The article *Code profiler and optimizations* has lots of information about C++ code profiling and also has a free download link to a program/class that will show you a graphic presentation for different code paths/methods. |
61,278 | What method do you use when you want to get performance data about specific code paths? | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | Note, the following is all written specifically for Windows.
I also have a timer class that I wrote to do quick-and-dirty profiling that uses QueryPerformanceCounter() to get high-precision timings, but with a slight difference. My timer class doesn't dump the elapsed time when the Timer object falls out of scope. Instead, it accumulates the elapsed times in to an collection. I added a static member function, Dump(), which creates a table of elapsed times, sorted by timing category (specified in Timer's constructor as a string) along with some statistical analysis such as mean elapsed time, standard deviation, max and min. I also added a Clear() static member function which clears the collection & lets you start over again.
**How to use the Timer class (psudocode):**
```
int CInsertBuffer::Read(char* pBuf)
{
// TIMER NOTES: Avg Execution Time = ~1 ms
Timer timer("BufferRead");
: :
return -1;
}
```
**Sample output :**
```
Timer Precision = 418.0095 ps
=== Item Trials Ttl Time Avg Time Mean Time StdDev ===
AddTrade 500 7 ms 14 us 12 us 24 us
BufferRead 511 1:19.25 0.16 s 621 ns 2.48 s
BufferWrite 516 511 us 991 ns 482 ns 11 us
ImportPos Loop 1002 18.62 s 19 ms 77 us 0.51 s
ImportPosition 2 18.75 s 9.38 s 16.17 s 13.59 s
Insert 515 4.26 s 8 ms 5 ms 27 ms
recv 101 18.54 s 0.18 s 2603 ns 1.63 s
```
**file Timer.inl :**
```
#include <map>
#include "x:\utils\stlext\stringext.h"
#include <iterator>
#include <set>
#include <vector>
#include <numeric>
#include "x:\utils\stlext\algorithmext.h"
#include <math.h>
class Timer
{
public:
Timer(const char* name)
{
label = std::safe_string(name);
QueryPerformanceCounter(&startTime);
}
virtual ~Timer()
{
QueryPerformanceCounter(&stopTime);
__int64 clocks = stopTime.QuadPart-startTime.QuadPart;
double elapsed = (double)clocks/(double)TimerFreq();
TimeMap().insert(std::make_pair(label,elapsed));
};
static std::string Dump(bool ClipboardAlso=true)
{
static const std::string loc = "Timer::Dump";
if( TimeMap().empty() )
{
return "No trials\r\n";
}
std::string ret = std::formatstr("\r\n\r\nTimer Precision = %s\r\n\r\n", format_elapsed(1.0/(double)TimerFreq()).c_str());
// get a list of keys
typedef std::set<std::string> keyset;
keyset keys;
std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());
size_t maxrows = 0;
typedef std::vector<std::string> strings;
strings lines;
static const size_t tabWidth = 9;
std::string head = std::formatstr("=== %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s ===", tabWidth*2, tabWidth*2, "Item", tabWidth, tabWidth, "Trials", tabWidth, tabWidth, "Ttl Time", tabWidth, tabWidth, "Avg Time", tabWidth, tabWidth, "Mean Time", tabWidth, tabWidth, "StdDev");
ret += std::formatstr("\r\n%s\r\n", head.c_str());
if( ClipboardAlso )
lines.push_back("Item\tTrials\tTtl Time\tAvg Time\tMean Time\tStdDev\r\n");
// dump the values for each key
{for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )
{
time_type ttl = 0;
ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));
size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));
if( num > maxrows )
maxrows = num;
time_type avg = ttl / num;
// compute mean
std::vector<time_type> sortedTimes;
std::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));
std::sort(sortedTimes.begin(), sortedTimes.end());
size_t mid = (size_t)floor((double)num/2.0);
double mean = ( num > 1 && (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];
// compute variance
double sum = 0.0;
if( num > 1 )
{
for( std::vector<time_type>::iterator timeIt = sortedTimes.begin(); sortedTimes.end() != timeIt; ++timeIt )
sum += pow(*timeIt-mean,2.0);
}
// compute std dev
double stddev = num > 1 ? sqrt(sum/((double)num-1.0)) : 0.0;
ret += std::formatstr(" %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s\r\n", tabWidth*2, tabWidth*2, key->c_str(), tabWidth, tabWidth, std::formatstr("%d",num).c_str(), tabWidth, tabWidth, format_elapsed(ttl).c_str(), tabWidth, tabWidth, format_elapsed(avg).c_str(), tabWidth, tabWidth, format_elapsed(mean).c_str(), tabWidth, tabWidth, format_elapsed(stddev).c_str());
if( ClipboardAlso )
lines.push_back(std::formatstr("%s\t%s\t%s\t%s\t%s\t%s\r\n", key->c_str(), std::formatstr("%d",num).c_str(), format_elapsed(ttl).c_str(), format_elapsed(avg).c_str(), format_elapsed(mean).c_str(), format_elapsed(stddev).c_str()));
}
}
ret += std::formatstr("%s\r\n", std::string(head.length(),'=').c_str());
if( ClipboardAlso )
{
// dump header row of data block
lines.push_back("");
{
std::string s;
for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
{
if( key != keys.begin() )
s.append("\t");
s.append(*key);
}
s.append("\r\n");
lines.push_back(s);
}
// blow out the flat map of time values to a seperate vector of times for each key
typedef std::map<std::string, std::vector<time_type> > nodematrix;
nodematrix nodes;
for( Times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )
nodes[time->first].push_back(time->second);
// dump each data point
for( size_t row = 0; row < maxrows; ++row )
{
std::string rowDump;
for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
{
if( key != keys.begin() )
rowDump.append("\t");
if( nodes[*key].size() > row )
rowDump.append(std::formatstr("%f", nodes[*key][row]));
}
rowDump.append("\r\n");
lines.push_back(rowDump);
}
// dump to the clipboard
std::string dump;
for( strings::iterator s = lines.begin(); s != lines.end(); ++s )
{
dump.append(*s);
}
OpenClipboard(0);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);
if( hg != 0 )
{
char* buf = (char*)GlobalLock(hg);
if( buf != 0 )
{
std::copy(dump.begin(), dump.end(), buf);
buf[dump.length()] = 0;
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
}
}
CloseClipboard();
}
return ret;
}
static void Reset()
{
TimeMap().clear();
}
static std::string format_elapsed(double d)
{
if( d < 0.00000001 )
{
// show in ps with 4 digits
return std::formatstr("%0.4f ps", d * 1000000000000.0);
}
if( d < 0.00001 )
{
// show in ns
return std::formatstr("%0.0f ns", d * 1000000000.0);
}
if( d < 0.001 )
{
// show in us
return std::formatstr("%0.0f us", d * 1000000.0);
}
if( d < 0.1 )
{
// show in ms
return std::formatstr("%0.0f ms", d * 1000.0);
}
if( d <= 60.0 )
{
// show in seconds
return std::formatstr("%0.2f s", d);
}
if( d < 3600.0 )
{
// show in min:sec
return std::formatstr("%01.0f:%02.2f", floor(d/60.0), fmod(d,60.0));
}
// show in h:min:sec
return std::formatstr("%01.0f:%02.0f:%02.2f", floor(d/3600.0), floor(fmod(d,3600.0)/60.0), fmod(d,60.0));
}
private:
static __int64 TimerFreq()
{
static __int64 freq = 0;
static bool init = false;
if( !init )
{
LARGE_INTEGER li;
QueryPerformanceFrequency(&li);
freq = li.QuadPart;
init = true;
}
return freq;
}
LARGE_INTEGER startTime, stopTime;
std::string label;
typedef std::string key_type;
typedef double time_type;
typedef std::multimap<key_type, time_type> Times;
// static Times times;
static Times& TimeMap()
{
static Times times_;
return times_;
}
struct extract_key : public std::unary_function<Times::value_type, key_type>
{
std::string operator()(Times::value_type const & r) const
{
return r.first;
}
};
struct extract_val : public std::unary_function<Times::value_type, time_type>
{
time_type operator()(Times::value_type const & r) const
{
return r.second;
}
};
struct match_key : public std::unary_function<Times::value_type, bool>
{
match_key(key_type const & key_) : key(key_) {};
bool operator()(Times::value_type const & rhs) const
{
return key == rhs.first;
}
private:
match_key& operator=(match_key&) { return * this; }
const key_type key;
};
struct accum_key : public std::binary_function<time_type, Times::value_type, time_type>
{
accum_key(key_type const & key_) : key(key_), n(0) {};
time_type operator()(time_type const & v, Times::value_type const & rhs) const
{
if( key == rhs.first )
{
++n;
return rhs.second + v;
}
return v;
}
private:
accum_key& operator=(accum_key&) { return * this; }
const Times::key_type key;
mutable size_t n;
};
};
```
**file stringext.h (provides formatstr() function):**
```
namespace std
{
/* ---
Formatted Print
template<class C>
int strprintf(basic_string<C>* pString, const C* pFmt, ...);
template<class C>
int vstrprintf(basic_string<C>* pString, const C* pFmt, va_list args);
Returns :
# characters printed to output
Effects :
Writes formatted data to a string. strprintf() works exactly the same as sprintf(); see your
documentation for sprintf() for details of peration. vstrprintf() also works the same as sprintf(),
but instead of accepting a variable paramater list it accepts a va_list argument.
Requires :
pString is a pointer to a basic_string<>
--- */
template<class char_type> int vprintf_generic(char_type* buffer, size_t bufferSize, const char_type* format, va_list argptr);
template<> inline int vprintf_generic<char>(char* buffer, size_t bufferSize, const char* format, va_list argptr)
{
# ifdef SECURE_VSPRINTF
return _vsnprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);
# else
return _vsnprintf(buffer, bufferSize-1, format, argptr);
# endif
}
template<> inline int vprintf_generic<wchar_t>(wchar_t* buffer, size_t bufferSize, const wchar_t* format, va_list argptr)
{
# ifdef SECURE_VSPRINTF
return _vsnwprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);
# else
return _vsnwprintf(buffer, bufferSize-1, format, argptr);
# endif
}
template<class Type, class Traits>
inline int vstringprintf(basic_string<Type,Traits> & outStr, const Type* format, va_list args)
{
// prologue
static const size_t ChunkSize = 1024;
size_t curBufSize = 0;
outStr.erase();
if( !format )
{
return 0;
}
// keep trying to write the string to an ever-increasing buffer until
// either we get the string written or we run out of memory
while( bool cont = true )
{
// allocate a local buffer
curBufSize += ChunkSize;
std::ref_ptr<Type> localBuffer = new Type[curBufSize];
if( localBuffer.get() == 0 )
{
// we ran out of memory -- nice goin'!
return -1;
}
// format output to local buffer
int i = vprintf_generic(localBuffer.get(), curBufSize * sizeof(Type), format, args);
if( -1 == i )
{
// the buffer wasn't big enough -- try again
continue;
}
else if( i < 0 )
{
// something wierd happened -- bail
return i;
}
// if we get to this point the string was written completely -- stop looping
outStr.assign(localBuffer.get(),i);
return i;
}
// unreachable code
return -1;
};
// provided for backward-compatibility
template<class Type, class Traits>
inline int vstrprintf(basic_string<Type,Traits> * outStr, const Type* format, va_list args)
{
return vstringprintf(*outStr, format, args);
}
template<class Char, class Traits>
inline int stringprintf(std::basic_string<Char, Traits> & outString, const Char* format, ...)
{
va_list args;
va_start(args, format);
int retval = vstringprintf(outString, format, args);
va_end(args);
return retval;
}
// old function provided for backward-compatibility
template<class Char, class Traits>
inline int strprintf(std::basic_string<Char, Traits> * outString, const Char* format, ...)
{
va_list args;
va_start(args, format);
int retval = vstringprintf(*outString, format, args);
va_end(args);
return retval;
}
/* ---
Inline Formatted Print
string strprintf(const char* Format, ...);
Returns :
Formatted string
Effects :
Writes formatted data to a string. formatstr() works the same as sprintf(); see your
documentation for sprintf() for details of operation.
--- */
template<class Char>
inline std::basic_string<Char> formatstr(const Char * format, ...)
{
std::string outString;
va_list args;
va_start(args, format);
vstringprintf(outString, format, args);
va_end(args);
return outString;
}
};
```
**File algorithmext.h (provides transform\_if() function) :**
```
/* ---
Transform
25.2.3
template<class InputIterator, class OutputIterator, class UnaryOperation, class Predicate>
OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op, Predicate pred)
template<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate>
OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op, Predicate pred)
Requires:
T is of type EqualityComparable (20.1.1)
op and binary_op have no side effects
Effects :
Assigns through every iterator i in the range [result, result + (last1-first1)) a new corresponding value equal to one of:
1: op( *(first1 + (i - result))
2: binary_op( *(first1 + (i - result), *(first2 + (i - result))
Returns :
result + (last1 - first1)
Complexity :
At most last1 - first1 applications of op or binary_op
--- */
template<class InputIterator, class OutputIterator, class UnaryFunction, class Predicate>
OutputIterator transform_if(InputIterator first,
InputIterator last,
OutputIterator result,
UnaryFunction f,
Predicate pred)
{
for (; first != last; ++first)
{
if( pred(*first) )
*result++ = f(*first);
}
return result;
}
template<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate>
OutputIterator transform_if(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
OutputIterator result,
BinaryOperation binary_op,
Predicate pred)
{
for (; first1 != last1 ; ++first1, ++first2)
{
if( pred(*first1) )
*result++ = binary_op(*first1,*first2);
}
return result;
}
``` | I wrote a simple cross-platform class called [nanotimer](http://www.plflib.org/nanotimer.htm) for this reason. The goal was to be as lightweight as possible so as to not interfere with actual code performance by adding too many instructions and thereby influencing the instruction cache. It is capable of getting microsecond accuracy across windows, mac and linux (and probably some unix variants).
Basic usage:
```
plf::timer t;
timer.start();
// stuff
double elapsed = t.get_elapsed_ns(); // Get nanoseconds
```
start() also restarts the timer when necessary. "Pausing" the timer can be achieved by storing the elapsed time, then restarting the timer when "unpausing" and adding to the stored result the next time you check elapsed time. |
61,278 | What method do you use when you want to get performance data about specific code paths? | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.
1. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).
2. It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now.
3. Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't.
---
I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with [DbgView](http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx)), including how many times the code was executed (and the average time spent of course)).
```
#pragma once
#include <tchar.h>
#include <windows.h>
#include <sstream>
#include <boost/noncopyable.hpp>
namespace scope_timer {
class time_collector : boost::noncopyable {
__int64 total;
LARGE_INTEGER start;
size_t times;
const TCHAR* name;
double cpu_frequency()
{ // cache the CPU frequency, which doesn't change.
static double ret = 0; // store as double so devision later on is floating point and not truncating
if (ret == 0) {
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
ret = static_cast<double>(freq.QuadPart);
}
return ret;
}
bool in_use;
public:
time_collector(const TCHAR* n)
: times(0)
, name(n)
, total(0)
, start(LARGE_INTEGER())
, in_use(false)
{
}
~time_collector()
{
std::basic_ostringstream<TCHAR> msg;
msg << _T("scope_timer> ") << name << _T(" called: ");
double seconds = total / cpu_frequency();
double average = seconds / times;
msg << times << _T(" times total time: ") << seconds << _T(" seconds ")
<< _T(" (avg ") << average <<_T(")\n");
OutputDebugString(msg.str().c_str());
}
void add_time(__int64 ticks)
{
total += ticks;
++times;
in_use = false;
}
bool aquire()
{
if (in_use)
return false;
in_use = true;
return true;
}
};
class one_time : boost::noncopyable {
LARGE_INTEGER start;
time_collector* collector;
public:
one_time(time_collector& tc)
{
if (tc.aquire()) {
collector = &tc;
QueryPerformanceCounter(&start);
}
else
collector = 0;
}
~one_time()
{
if (collector) {
LARGE_INTEGER end;
QueryPerformanceCounter(&end);
collector->add_time(end.QuadPart - start.QuadPart);
}
}
};
}
// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)
#define TIME_THIS_SCOPE(name) \
static scope_timer::time_collector st_time_collector_##name(_T(#name)); \
scope_timer::one_time st_one_time_##name(st_time_collector_##name)
``` | Note, the following is all written specifically for Windows.
I also have a timer class that I wrote to do quick-and-dirty profiling that uses QueryPerformanceCounter() to get high-precision timings, but with a slight difference. My timer class doesn't dump the elapsed time when the Timer object falls out of scope. Instead, it accumulates the elapsed times in to an collection. I added a static member function, Dump(), which creates a table of elapsed times, sorted by timing category (specified in Timer's constructor as a string) along with some statistical analysis such as mean elapsed time, standard deviation, max and min. I also added a Clear() static member function which clears the collection & lets you start over again.
**How to use the Timer class (psudocode):**
```
int CInsertBuffer::Read(char* pBuf)
{
// TIMER NOTES: Avg Execution Time = ~1 ms
Timer timer("BufferRead");
: :
return -1;
}
```
**Sample output :**
```
Timer Precision = 418.0095 ps
=== Item Trials Ttl Time Avg Time Mean Time StdDev ===
AddTrade 500 7 ms 14 us 12 us 24 us
BufferRead 511 1:19.25 0.16 s 621 ns 2.48 s
BufferWrite 516 511 us 991 ns 482 ns 11 us
ImportPos Loop 1002 18.62 s 19 ms 77 us 0.51 s
ImportPosition 2 18.75 s 9.38 s 16.17 s 13.59 s
Insert 515 4.26 s 8 ms 5 ms 27 ms
recv 101 18.54 s 0.18 s 2603 ns 1.63 s
```
**file Timer.inl :**
```
#include <map>
#include "x:\utils\stlext\stringext.h"
#include <iterator>
#include <set>
#include <vector>
#include <numeric>
#include "x:\utils\stlext\algorithmext.h"
#include <math.h>
class Timer
{
public:
Timer(const char* name)
{
label = std::safe_string(name);
QueryPerformanceCounter(&startTime);
}
virtual ~Timer()
{
QueryPerformanceCounter(&stopTime);
__int64 clocks = stopTime.QuadPart-startTime.QuadPart;
double elapsed = (double)clocks/(double)TimerFreq();
TimeMap().insert(std::make_pair(label,elapsed));
};
static std::string Dump(bool ClipboardAlso=true)
{
static const std::string loc = "Timer::Dump";
if( TimeMap().empty() )
{
return "No trials\r\n";
}
std::string ret = std::formatstr("\r\n\r\nTimer Precision = %s\r\n\r\n", format_elapsed(1.0/(double)TimerFreq()).c_str());
// get a list of keys
typedef std::set<std::string> keyset;
keyset keys;
std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());
size_t maxrows = 0;
typedef std::vector<std::string> strings;
strings lines;
static const size_t tabWidth = 9;
std::string head = std::formatstr("=== %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s ===", tabWidth*2, tabWidth*2, "Item", tabWidth, tabWidth, "Trials", tabWidth, tabWidth, "Ttl Time", tabWidth, tabWidth, "Avg Time", tabWidth, tabWidth, "Mean Time", tabWidth, tabWidth, "StdDev");
ret += std::formatstr("\r\n%s\r\n", head.c_str());
if( ClipboardAlso )
lines.push_back("Item\tTrials\tTtl Time\tAvg Time\tMean Time\tStdDev\r\n");
// dump the values for each key
{for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )
{
time_type ttl = 0;
ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));
size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));
if( num > maxrows )
maxrows = num;
time_type avg = ttl / num;
// compute mean
std::vector<time_type> sortedTimes;
std::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));
std::sort(sortedTimes.begin(), sortedTimes.end());
size_t mid = (size_t)floor((double)num/2.0);
double mean = ( num > 1 && (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];
// compute variance
double sum = 0.0;
if( num > 1 )
{
for( std::vector<time_type>::iterator timeIt = sortedTimes.begin(); sortedTimes.end() != timeIt; ++timeIt )
sum += pow(*timeIt-mean,2.0);
}
// compute std dev
double stddev = num > 1 ? sqrt(sum/((double)num-1.0)) : 0.0;
ret += std::formatstr(" %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s\r\n", tabWidth*2, tabWidth*2, key->c_str(), tabWidth, tabWidth, std::formatstr("%d",num).c_str(), tabWidth, tabWidth, format_elapsed(ttl).c_str(), tabWidth, tabWidth, format_elapsed(avg).c_str(), tabWidth, tabWidth, format_elapsed(mean).c_str(), tabWidth, tabWidth, format_elapsed(stddev).c_str());
if( ClipboardAlso )
lines.push_back(std::formatstr("%s\t%s\t%s\t%s\t%s\t%s\r\n", key->c_str(), std::formatstr("%d",num).c_str(), format_elapsed(ttl).c_str(), format_elapsed(avg).c_str(), format_elapsed(mean).c_str(), format_elapsed(stddev).c_str()));
}
}
ret += std::formatstr("%s\r\n", std::string(head.length(),'=').c_str());
if( ClipboardAlso )
{
// dump header row of data block
lines.push_back("");
{
std::string s;
for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
{
if( key != keys.begin() )
s.append("\t");
s.append(*key);
}
s.append("\r\n");
lines.push_back(s);
}
// blow out the flat map of time values to a seperate vector of times for each key
typedef std::map<std::string, std::vector<time_type> > nodematrix;
nodematrix nodes;
for( Times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )
nodes[time->first].push_back(time->second);
// dump each data point
for( size_t row = 0; row < maxrows; ++row )
{
std::string rowDump;
for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
{
if( key != keys.begin() )
rowDump.append("\t");
if( nodes[*key].size() > row )
rowDump.append(std::formatstr("%f", nodes[*key][row]));
}
rowDump.append("\r\n");
lines.push_back(rowDump);
}
// dump to the clipboard
std::string dump;
for( strings::iterator s = lines.begin(); s != lines.end(); ++s )
{
dump.append(*s);
}
OpenClipboard(0);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);
if( hg != 0 )
{
char* buf = (char*)GlobalLock(hg);
if( buf != 0 )
{
std::copy(dump.begin(), dump.end(), buf);
buf[dump.length()] = 0;
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
}
}
CloseClipboard();
}
return ret;
}
static void Reset()
{
TimeMap().clear();
}
static std::string format_elapsed(double d)
{
if( d < 0.00000001 )
{
// show in ps with 4 digits
return std::formatstr("%0.4f ps", d * 1000000000000.0);
}
if( d < 0.00001 )
{
// show in ns
return std::formatstr("%0.0f ns", d * 1000000000.0);
}
if( d < 0.001 )
{
// show in us
return std::formatstr("%0.0f us", d * 1000000.0);
}
if( d < 0.1 )
{
// show in ms
return std::formatstr("%0.0f ms", d * 1000.0);
}
if( d <= 60.0 )
{
// show in seconds
return std::formatstr("%0.2f s", d);
}
if( d < 3600.0 )
{
// show in min:sec
return std::formatstr("%01.0f:%02.2f", floor(d/60.0), fmod(d,60.0));
}
// show in h:min:sec
return std::formatstr("%01.0f:%02.0f:%02.2f", floor(d/3600.0), floor(fmod(d,3600.0)/60.0), fmod(d,60.0));
}
private:
static __int64 TimerFreq()
{
static __int64 freq = 0;
static bool init = false;
if( !init )
{
LARGE_INTEGER li;
QueryPerformanceFrequency(&li);
freq = li.QuadPart;
init = true;
}
return freq;
}
LARGE_INTEGER startTime, stopTime;
std::string label;
typedef std::string key_type;
typedef double time_type;
typedef std::multimap<key_type, time_type> Times;
// static Times times;
static Times& TimeMap()
{
static Times times_;
return times_;
}
struct extract_key : public std::unary_function<Times::value_type, key_type>
{
std::string operator()(Times::value_type const & r) const
{
return r.first;
}
};
struct extract_val : public std::unary_function<Times::value_type, time_type>
{
time_type operator()(Times::value_type const & r) const
{
return r.second;
}
};
struct match_key : public std::unary_function<Times::value_type, bool>
{
match_key(key_type const & key_) : key(key_) {};
bool operator()(Times::value_type const & rhs) const
{
return key == rhs.first;
}
private:
match_key& operator=(match_key&) { return * this; }
const key_type key;
};
struct accum_key : public std::binary_function<time_type, Times::value_type, time_type>
{
accum_key(key_type const & key_) : key(key_), n(0) {};
time_type operator()(time_type const & v, Times::value_type const & rhs) const
{
if( key == rhs.first )
{
++n;
return rhs.second + v;
}
return v;
}
private:
accum_key& operator=(accum_key&) { return * this; }
const Times::key_type key;
mutable size_t n;
};
};
```
**file stringext.h (provides formatstr() function):**
```
namespace std
{
/* ---
Formatted Print
template<class C>
int strprintf(basic_string<C>* pString, const C* pFmt, ...);
template<class C>
int vstrprintf(basic_string<C>* pString, const C* pFmt, va_list args);
Returns :
# characters printed to output
Effects :
Writes formatted data to a string. strprintf() works exactly the same as sprintf(); see your
documentation for sprintf() for details of peration. vstrprintf() also works the same as sprintf(),
but instead of accepting a variable paramater list it accepts a va_list argument.
Requires :
pString is a pointer to a basic_string<>
--- */
template<class char_type> int vprintf_generic(char_type* buffer, size_t bufferSize, const char_type* format, va_list argptr);
template<> inline int vprintf_generic<char>(char* buffer, size_t bufferSize, const char* format, va_list argptr)
{
# ifdef SECURE_VSPRINTF
return _vsnprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);
# else
return _vsnprintf(buffer, bufferSize-1, format, argptr);
# endif
}
template<> inline int vprintf_generic<wchar_t>(wchar_t* buffer, size_t bufferSize, const wchar_t* format, va_list argptr)
{
# ifdef SECURE_VSPRINTF
return _vsnwprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);
# else
return _vsnwprintf(buffer, bufferSize-1, format, argptr);
# endif
}
template<class Type, class Traits>
inline int vstringprintf(basic_string<Type,Traits> & outStr, const Type* format, va_list args)
{
// prologue
static const size_t ChunkSize = 1024;
size_t curBufSize = 0;
outStr.erase();
if( !format )
{
return 0;
}
// keep trying to write the string to an ever-increasing buffer until
// either we get the string written or we run out of memory
while( bool cont = true )
{
// allocate a local buffer
curBufSize += ChunkSize;
std::ref_ptr<Type> localBuffer = new Type[curBufSize];
if( localBuffer.get() == 0 )
{
// we ran out of memory -- nice goin'!
return -1;
}
// format output to local buffer
int i = vprintf_generic(localBuffer.get(), curBufSize * sizeof(Type), format, args);
if( -1 == i )
{
// the buffer wasn't big enough -- try again
continue;
}
else if( i < 0 )
{
// something wierd happened -- bail
return i;
}
// if we get to this point the string was written completely -- stop looping
outStr.assign(localBuffer.get(),i);
return i;
}
// unreachable code
return -1;
};
// provided for backward-compatibility
template<class Type, class Traits>
inline int vstrprintf(basic_string<Type,Traits> * outStr, const Type* format, va_list args)
{
return vstringprintf(*outStr, format, args);
}
template<class Char, class Traits>
inline int stringprintf(std::basic_string<Char, Traits> & outString, const Char* format, ...)
{
va_list args;
va_start(args, format);
int retval = vstringprintf(outString, format, args);
va_end(args);
return retval;
}
// old function provided for backward-compatibility
template<class Char, class Traits>
inline int strprintf(std::basic_string<Char, Traits> * outString, const Char* format, ...)
{
va_list args;
va_start(args, format);
int retval = vstringprintf(*outString, format, args);
va_end(args);
return retval;
}
/* ---
Inline Formatted Print
string strprintf(const char* Format, ...);
Returns :
Formatted string
Effects :
Writes formatted data to a string. formatstr() works the same as sprintf(); see your
documentation for sprintf() for details of operation.
--- */
template<class Char>
inline std::basic_string<Char> formatstr(const Char * format, ...)
{
std::string outString;
va_list args;
va_start(args, format);
vstringprintf(outString, format, args);
va_end(args);
return outString;
}
};
```
**File algorithmext.h (provides transform\_if() function) :**
```
/* ---
Transform
25.2.3
template<class InputIterator, class OutputIterator, class UnaryOperation, class Predicate>
OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op, Predicate pred)
template<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate>
OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op, Predicate pred)
Requires:
T is of type EqualityComparable (20.1.1)
op and binary_op have no side effects
Effects :
Assigns through every iterator i in the range [result, result + (last1-first1)) a new corresponding value equal to one of:
1: op( *(first1 + (i - result))
2: binary_op( *(first1 + (i - result), *(first2 + (i - result))
Returns :
result + (last1 - first1)
Complexity :
At most last1 - first1 applications of op or binary_op
--- */
template<class InputIterator, class OutputIterator, class UnaryFunction, class Predicate>
OutputIterator transform_if(InputIterator first,
InputIterator last,
OutputIterator result,
UnaryFunction f,
Predicate pred)
{
for (; first != last; ++first)
{
if( pred(*first) )
*result++ = f(*first);
}
return result;
}
template<class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate>
OutputIterator transform_if(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
OutputIterator result,
BinaryOperation binary_op,
Predicate pred)
{
for (; first1 != last1 ; ++first1, ++first2)
{
if( pred(*first1) )
*result++ = binary_op(*first1,*first2);
}
return result;
}
``` |
61,278 | What method do you use when you want to get performance data about specific code paths? | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | Well, I have two code snippets. In [pseudocode](http://en.wikipedia.org/wiki/Pseudocode) they are looking like (it's a simplified version, I'm using [QueryPerformanceFrequency](http://msdn.microsoft.com/en-us/library/windows/desktop/ms644905%28v=vs.85%29.aspx) actually):
### First snippet:
```
Timer timer = new Timer
timer.Start
```
### Second snippet:
```
timer.Stop
show elapsed time
```
A bit of hot-keys kung fu, and I can say how much time this piece of code stole from my CPU. | The article *Code profiler and optimizations* has lots of information about C++ code profiling and also has a free download link to a program/class that will show you a graphic presentation for different code paths/methods. |
61,278 | What method do you use when you want to get performance data about specific code paths? | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | I do my profiles by creating two classes: `cProfile` and `cProfileManager`.
`cProfileManager` will hold all the data that resulted from `cProfile`.
`cProfile` with have the following requirements:
* `cProfile` has a constructor which initializes the current time.
* `cProfile` has a deconstructor which sends the total time the class was alive to `cProfileManager`
To use these profile classes, I first make an instance of `cProfileManager`. Then, I put the code block, which I want to profile, inside curly braces. Inside the curly braces, I create a `cProfile` instance. When the code block ends, `cProfile` will send the time it took for the block of code to finish to `cProfileManager`.
**Example Code**
Here's an example of the code (simplified):
```
class cProfile
{
cProfile()
{
TimeStart = GetTime();
};
~cProfile()
{
ProfileManager->AddProfile (GetTime() - TimeStart);
}
float TimeStart;
}
```
To use `cProfile`, I would do something like this:
```
int main()
{
printf("Start test");
{
cProfile Profile;
Calculate();
}
ProfileManager->OutputData();
}
```
or this:
```
void foobar()
{
cProfile ProfileFoobar;
foo();
{
cProfile ProfileBarCheck;
while (bar())
{
cProfile ProfileSpam;
spam();
}
}
}
```
**Technical Note**
This code is actually an abuse of the way scoping, constructors and deconstructors work in [C++](http://en.wikipedia.org/wiki/C_%28programming_language%29). `cProfile` exists only inside the block scope (the code block we want to test). Once the program leaves the block scope, `cProfile` records the result.
**Additional Enhancements**
* You can add a string parameter to the constructor so you can do something like this:
cProfile Profile("Profile for complicated calculation");
* You can use a macro to make the code look cleaner (be careful not to abuse this. Unlike our other abuses on the language, macros can be dangerous when used).
Example:
#define START\_PROFILE cProfile Profile(); {
#define END\_PROFILE }
* `cProfileManager` can check how many times a block of code is called. But you would need an identifier for the block of code. The first enhancement can help identify the block. This can be useful in cases where the code you want to profile is inside a loop (like the second example aboe). You can also add the average, fastest and longest execution time the code block took.
* Don't forget to add a check to skip profiling if you are in debug mode. | I wrote a simple cross-platform class called [nanotimer](http://www.plflib.org/nanotimer.htm) for this reason. The goal was to be as lightweight as possible so as to not interfere with actual code performance by adding too many instructions and thereby influencing the instruction cache. It is capable of getting microsecond accuracy across windows, mac and linux (and probably some unix variants).
Basic usage:
```
plf::timer t;
timer.start();
// stuff
double elapsed = t.get_elapsed_ns(); // Get nanoseconds
```
start() also restarts the timer when necessary. "Pausing" the timer can be achieved by storing the elapsed time, then restarting the timer when "unpausing" and adding to the stored result the next time you check elapsed time. |
61,278 | What method do you use when you want to get performance data about specific code paths? | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | Well, I have two code snippets. In [pseudocode](http://en.wikipedia.org/wiki/Pseudocode) they are looking like (it's a simplified version, I'm using [QueryPerformanceFrequency](http://msdn.microsoft.com/en-us/library/windows/desktop/ms644905%28v=vs.85%29.aspx) actually):
### First snippet:
```
Timer timer = new Timer
timer.Start
```
### Second snippet:
```
timer.Stop
show elapsed time
```
A bit of hot-keys kung fu, and I can say how much time this piece of code stole from my CPU. | I wrote a simple cross-platform class called [nanotimer](http://www.plflib.org/nanotimer.htm) for this reason. The goal was to be as lightweight as possible so as to not interfere with actual code performance by adding too many instructions and thereby influencing the instruction cache. It is capable of getting microsecond accuracy across windows, mac and linux (and probably some unix variants).
Basic usage:
```
plf::timer t;
timer.start();
// stuff
double elapsed = t.get_elapsed_ns(); // Get nanoseconds
```
start() also restarts the timer when necessary. "Pausing" the timer can be achieved by storing the elapsed time, then restarting the timer when "unpausing" and adding to the stored result the next time you check elapsed time. |
61,278 | What method do you use when you want to get performance data about specific code paths? | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.
1. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).
2. It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now.
3. Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't.
---
I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with [DbgView](http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx)), including how many times the code was executed (and the average time spent of course)).
```
#pragma once
#include <tchar.h>
#include <windows.h>
#include <sstream>
#include <boost/noncopyable.hpp>
namespace scope_timer {
class time_collector : boost::noncopyable {
__int64 total;
LARGE_INTEGER start;
size_t times;
const TCHAR* name;
double cpu_frequency()
{ // cache the CPU frequency, which doesn't change.
static double ret = 0; // store as double so devision later on is floating point and not truncating
if (ret == 0) {
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
ret = static_cast<double>(freq.QuadPart);
}
return ret;
}
bool in_use;
public:
time_collector(const TCHAR* n)
: times(0)
, name(n)
, total(0)
, start(LARGE_INTEGER())
, in_use(false)
{
}
~time_collector()
{
std::basic_ostringstream<TCHAR> msg;
msg << _T("scope_timer> ") << name << _T(" called: ");
double seconds = total / cpu_frequency();
double average = seconds / times;
msg << times << _T(" times total time: ") << seconds << _T(" seconds ")
<< _T(" (avg ") << average <<_T(")\n");
OutputDebugString(msg.str().c_str());
}
void add_time(__int64 ticks)
{
total += ticks;
++times;
in_use = false;
}
bool aquire()
{
if (in_use)
return false;
in_use = true;
return true;
}
};
class one_time : boost::noncopyable {
LARGE_INTEGER start;
time_collector* collector;
public:
one_time(time_collector& tc)
{
if (tc.aquire()) {
collector = &tc;
QueryPerformanceCounter(&start);
}
else
collector = 0;
}
~one_time()
{
if (collector) {
LARGE_INTEGER end;
QueryPerformanceCounter(&end);
collector->add_time(end.QuadPart - start.QuadPart);
}
}
};
}
// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)
#define TIME_THIS_SCOPE(name) \
static scope_timer::time_collector st_time_collector_##name(_T(#name)); \
scope_timer::one_time st_one_time_##name(st_time_collector_##name)
``` | I wrote a simple cross-platform class called [nanotimer](http://www.plflib.org/nanotimer.htm) for this reason. The goal was to be as lightweight as possible so as to not interfere with actual code performance by adding too many instructions and thereby influencing the instruction cache. It is capable of getting microsecond accuracy across windows, mac and linux (and probably some unix variants).
Basic usage:
```
plf::timer t;
timer.start();
// stuff
double elapsed = t.get_elapsed_ns(); // Get nanoseconds
```
start() also restarts the timer when necessary. "Pausing" the timer can be achieved by storing the elapsed time, then restarting the timer when "unpausing" and adding to the stored result the next time you check elapsed time. |
74,558,080 | This is a true story of evolving code. We began with many classes based on this structure:
```
class Base
{
public:
virtual void doSomething() {}
};
class Derived : public Base
{
public:
void doSomething() override
{
Base::doSomething(); // Do the basics
// Do other derived things
}
};
```
At one point, we needed a class in between Base and Derived:
```
class Base;
class Between : public Base;
class Derived : public Between;
```
To keep the structure, `Between::doSomething()` first calls Base.
However now `Derived::doSomething()` must be changed to call `Between::doSomething()`...
And this goes for all methods of Derived, requiring search & replace to many many calls.
A best solution would be to have some this->std::direct\_parent mechanism to avoid all the replacements and to allow easy managing of class topology.
Of course, this should compile only when there's a single immediate parent.
Is there any way to accomplish this? If not, could this be a feature request for the C++ committee? | 2022/11/24 | [
"https://Stackoverflow.com/questions/74558080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2181250/"
] | What I can suggest is `parent` typedef in `Derived`:
```
class Base
{
public:
virtual void doSomething() {}
};
class Derived : public Base
{
private:
typedef Base parent;
public:
void doSomething() override
{
parent::doSomething(); // Do the basics
// Do other derived things
}
};
```
Then after introduction of `Between` the only change needed in `Derived` is the change of the `parent` typedef:
```
class Derived : public Between
{
private:
typedef Between parent;
public:
void doSomething() override
{
parent::doSomething(); // Do the basics
// Do other derived things
}
};
``` | I think this question is related to: [Using "super" in C++](https://stackoverflow.com/questions/180601/using-super-in-c)
I've seen projects, where the direct parent of the current class is mentioned as a "SUPER" typedef in the class header. This makes code-changes with new intermediate classes easier. Not bulletproof, but easier. Almost the same, as in the linked question. |
16,832,999 | I have an array an elements. They have similar id:
```
Step2_Visits_0__CountryCode
Step2_Visits_1__CountryCode
Step2_Visits_2__CountryCode
Step2_Visits_3__CountryCode
Step2_Visits_4__CountryCode
```
This array names as "visitCountries".
I use "loop for" and append after each element tag .
For example:
```
for(var i=0; i < 20; i++) {
$(visitCountries[i].id).append("<a id=editCountryItemIcon[" + i + "]"
+ "style=\"vertical-align: bottom;\""
+ "class=\"editLineItemLink\"");
}
```
But it doesn't work. Please,help! | 2013/05/30 | [
"https://Stackoverflow.com/questions/16832999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129783/"
] | PopupWindow already has its own dismiss listener, just use it as follows
```
Popup popup = new Popup(getBaseContext());
popup.show(arg1);
```
Change that to
```
Popup popup = new Popup(getBaseContext());
popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
// Do your action
}
});
popup.show(arg1);
``` | **EDIT**
I hadn't noticed you were extending a PopupWindow, which already has this implemented as shown in @Jayabal's answer. Anyway this is how you would do it if the PopupWindow didn't already have it's own onDismissListener.
Simply create your own OnDismissListener Interface.
```
public interface onDismissListener{
public void onDismiss();
}
```
Add a reference to a Listener in the PopUp class and a setter.
```
OnDismissListener listener;
public void setOnDismissListener(OnDismissListener listener){
this.listener = listener;
}
```
Then in your Activity
```
Popup popup = new Popup(getBaseContext());
popup.setOnDismissListener(new OnDismissListener(){
public void onDismiss(){
//do what you need to here
}
});
popup.show(arg1);
```
This pattern should be familiar to you, its used everywhere in Android. |
38,018,112 | I don't have much experience with jquery so excuse my ignorance. I'm trying to make a FAQ where the answer appears when the question is clicked. Here's some test code. Obviously I'm not doing the jquery right because it's not working.
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<script>
$('li:not(".q")').hide();
$('li.q').click(
function(){
$('li:not(".q")').slideUp();
$(this).toggleClass('open');
});
</script>
<ul>
<li class="q">Q1. Question
</li>
<li> A. Answer
</li>
</ul>
</body>
</html>
``` | 2016/06/24 | [
"https://Stackoverflow.com/questions/38018112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4458077/"
] | Using jQuery's next() method (<http://api.jquery.com/next/>) will let you work with the li following the one you clicked on.
Note that I used show() instead of addClass('open') because I don't know what's in your open class - slideUp() is going to add display:none to all of the answers, so you have to make sure your open class overrides that.
```
$(document).ready(function() {
$('li.q').on('click', function () {
$('li:not(".q")').slideUp();
$(this).next().show();
});
});
```
I'd also recommend using a CSS class to have your answers already hidden when the page loads; using javascript to do it can result in them all being visible and then quickly hidden.
```
li:not(.q) { display: none; }
``` | ```
$(document).ready(function(){
$('.answer').hide();
$('.question').on('click', function() {
$('.answer').toggle('show');
});
});
```
You wanna something like this if I got you right. <https://jsfiddle.net/mprzmb7b/1/> |
5,509,803 | How can I convert a string like `'\\x41'` to an escaped string like `'\x41'`, using Python? | 2011/04/01 | [
"https://Stackoverflow.com/questions/5509803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/363249/"
] | ```
>>> '\\x41'.decode('string_escape')
'A'
```
Gory details [here](http://docs.python.org/library/codecs.html#standard-encodings). | I don't really understand your question, but I'll try to give you some solutions.
1. If you gonna print pure '\x41', you could just
>
> `print r'\x41'`
>
>
>
1. And if what you want is to print the 'A' out, pls do:
>
> `print u'\x41'`
>
>
> |
28,031,165 | I'm trying to get information out of this Dictionary that was created from a JSON string. The JSON string is returned from the server and is put in a dictionary. That dictionary is passed to myMethod that is suppose to break it down so I can get the information that each record contains.
The "Recordset" is an Array. The Record is also an array of dictionaries.
How do I get to the dictionaries? I keep getting ***NSDictionaryM objectAtIndex: unrecognized selector sent to instance***
```
Recordset = (
{
Record = (
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1691;
MODvc50Name = "10/12 Series 2";
},
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1687;
MODvc50Name = "10/4";
},
{
MODMAKlMakeKey = 1112;
MODlModelKey = 1686;
MODvc50Name = "10/6";
},
```
etc .. etc... ( about 100 records )
**Here is what I have**
```
- (void) myMethod : (NSDictionary*) dictionary {
//INITIAL
NSArray * arrRecordSet = [dictionary objectForKey:@"Recordset"];
NSArray * arrRecord = [arrRecordSet objectAtIndex:0];
NSDictionary * theRecord = [NSDictionary dictionaryWithObjects:arrRecord forKeys:[arrRecord objectAtIndex:0]];
for (int i = 0; i < arrRecord.count; i++) {
NSLog(@"MODMAKlMakeKey: %@", [theRecord objectForKey:@"MODMAKlMakeKey"]);
}
}
``` | 2015/01/19 | [
"https://Stackoverflow.com/questions/28031165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/995931/"
] | Try this
```
NSArray * arrRecord = [arrRecordSet objectForKey:@"Record"];
``` | Try to check first if the return of [dictionary objectForKey:@"Recordset"] is really a dictionary or an array.
To do this:
```
if([[dictionary objectForKey:@"Recordset"] isKindOfClass:[NSArray class]]) {
//object is array
}
else if ([[dictionary objectForKey:@"Recordset"] isKindOfClass:[NSDictionary class]]) {
//object is dictionary
}
``` |
12,521,930 | I have a image inputted in the css with the following code:
```
.imgtemp {
float:right;
top:0px;
left:0px;
overflow:visible;
width:100%;
}
```
I have also added the div tag to the page so its displaying, but the image is wider than the div due to the design. How can I make it overflow the divs its in to get it correct.
Thanks. | 2012/09/20 | [
"https://Stackoverflow.com/questions/12521930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1682435/"
] | You should place `overflow:visible` on your div, not on an image. | ```
.contact__section{ // your container
width: 100%;
display: block;
overflow: hidden; // hide in case your XL image is too high to keep other sections of page neat
}
.contact__flexbox{
position: relative; // you may not need it
display: block; // for mobile size, or none; if not want to display on mobile
width: 1100px; // our container width
max-width: 100%; // for mobile
margin: 0 auto; // center it on page
@include tablet{ // My personal media query, replace with yours for tablet + size
display: flex;
align-items: center;
justify-content:space-evenly;
}
}
.contact__image-xl{
position: relative; // important
display: flex;
flex:1; // make de 2 columns same size for a split in the middle of screen
// No need: overflow: visible;
img{
// VERY IMPORTANT:
max-width: 1000%!important;
position: absolute;
right: 0; // if your image is on left, otherwise: left:0;
width: 1200px; // your image at the size you want it to display
}
}
``` |
12,521,930 | I have a image inputted in the css with the following code:
```
.imgtemp {
float:right;
top:0px;
left:0px;
overflow:visible;
width:100%;
}
```
I have also added the div tag to the page so its displaying, but the image is wider than the div due to the design. How can I make it overflow the divs its in to get it correct.
Thanks. | 2012/09/20 | [
"https://Stackoverflow.com/questions/12521930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1682435/"
] | As Nelson said, overflow: hidden on your image won't help you. If you absolutely must have the container be smaller than the image inside it, you can use positioning (relative on the parent div, absolute on the image with a top and left of 0, for example) to ignore its parent's size. You'll want to use something other than % on the image, too, because the % will read off its parents size, which is counter-productive.
Or, did you mean you want the parent div to cut off the extra image? | ```
.contact__section{ // your container
width: 100%;
display: block;
overflow: hidden; // hide in case your XL image is too high to keep other sections of page neat
}
.contact__flexbox{
position: relative; // you may not need it
display: block; // for mobile size, or none; if not want to display on mobile
width: 1100px; // our container width
max-width: 100%; // for mobile
margin: 0 auto; // center it on page
@include tablet{ // My personal media query, replace with yours for tablet + size
display: flex;
align-items: center;
justify-content:space-evenly;
}
}
.contact__image-xl{
position: relative; // important
display: flex;
flex:1; // make de 2 columns same size for a split in the middle of screen
// No need: overflow: visible;
img{
// VERY IMPORTANT:
max-width: 1000%!important;
position: absolute;
right: 0; // if your image is on left, otherwise: left:0;
width: 1200px; // your image at the size you want it to display
}
}
``` |
49,802 | I am in a home loan with my ex-partner in joint tenancy. She is the primary on the loan paperwork. I would like to remove myself from the loan. Is that possible? She does not want to refinance in her name only but rather just remove me from the original which I am fine with. | 2015/07/12 | [
"https://money.stackexchange.com/questions/49802",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/30310/"
] | This will be up to the bank. Ask them, but if they are unwilling then refinancing or selling the house are the only other options. Even changing the title does not release you from the loan obligation. | Both people are responsible for the loan, it doesn't matter who is prime. The lender can ding both parties credit reports for failure to pay. It can force payment from either party.
They are unlikely to want to let one party out of the deal unless they have done an updated review of the solo persons finances and credit. Of course that type of review is only done as part of a refinance.
Even if you give up your portion of the property via a quit claim deed, that won't get your name off the mortgage. |
151,126 | I need to put a quote in my research paper. My friends give me different answers so I'm confused now...
Would it be
>
> According to "Title", "blah blah blah."
>
>
>
or
>
> According to "Title," "blah blah blah."
>
>
> | 2014/02/11 | [
"https://english.stackexchange.com/questions/151126",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/65365/"
] | Depends on the context. Imagine the sentence doesn't have quotes:
>
> According to Fred, astrophysics is a rapidly growing field.
>
>
>
You can substitute "Fred" for anything, including some title. Note that the comma would be where it is, regardless of what you substitute for the word Fred. The comma is not part of the title, so the comma does not belong inside the quote. Therefore in this context you put the comma after the quote, like so:
>
> According to "Astrophysics: Growing Rapidly", astrophysics is a rapidly growing field.
>
>
>
You typically only put the punctuation inside the quotes if you are writing dialogue or if you are quoting a sentence that includes punctuation.
>
> "According to Fred," said Bob, "astrophysics is a rapidly growing field."
>
>
> | In American English, according to most style manuals, punctuation marks are placed inside of the quotes. For more information see [here](https://www.grammarbook.com/punctuation/quotes.asp) and [here](http://blog.apastyle.org/apastyle/2011/08/punctuating-around-quotation-marks.html). |
63,946 | Hi I just wanted some feedback on a DDOS preventing php script that I'm designing. It quite simple and I wanted some feedback on whether you guys think it would be effective.
I'm currently using the [ulogin framework](http://ulogin.sourceforge.net/) as a base and have implemented API Key's. At the moment the user will send a request with a key. This key is checked against the database to see if it correct. So if the key is not correct the program will return.
If the key is correct then some statistics are going to be calculated. The first thing is to increment the counter. The average hit per second will be calculated from the time they started requesting to the current time. Also there is a window of X seconds in which the counter will be reset (Lets say 300). The programmer specifies the max number of requests that should be allowed in this window. If the key is over the limit of requests per stats reset (Window) or over a certain amount of requests per second, they will be blocked and not given access. However the counter still increments but another counter is started (blockcount).
When the counter is set to 0 at the end of the window, the count for the next window will be set to what ever the blockcount is and the blockcount will be set to 0. If the user doesn't use the API key for X (window) seconds then both counters will be reset to 0.
I have added a transferpenalty variable (0-1) that will take a percentage of the blockcount on to the next window instead of the entire block count but I don't think that it is neccessary to have this.
Is this already being done? Would this protect against a sniffed API key being used to (D)DOS a server? What are your thoughts :) | 2014/07/25 | [
"https://security.stackexchange.com/questions/63946",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/-1/"
] | Your code is good for monitoring users activity on the server but to be honest, It can't help preventing DDOS attacks since the aim of DDOS attacks is to send tons of requests to the server to make it too busy to respond to its intended users.
your code seems to be doing lots of checking to determine if the number of requests has reached beyond your standards, and this means that not only the attacker has reached his goal keeping your server busy but also you are helping him with lots of processing which is done by your code.
Imagine that each time there is a request, your code has to search through database and retrieve information and then compare them and do lots of other stuff.
there is nothing you could do in PHP to stop this kind of attacks.
and also if the attacker uses UDP attack, your code will do nothing since the Apache listens to TCP port.
The only thing that can protect your website from DDOS attacks is your Hosting company. the company needs to have needed equipments like:
1. Firewalls
2. rate-limiting Switches
3. appropriate Routers
4. Application front end hardware
5. IPS based prevention
6. DDS based defense
7. Blackholing and sinkholing
8. Clean pipes
but if you need a secure login system you could use a captcha, even the one you created yourself. simply generate a random 5 digit number and create an image in PHP with the number printed in it and show the picture on the form and when the user submits the form, check if the number you generated matches with the one user entered. and also you can use PHP/JavaScript AES libraries to encrypt user inputs on the client side and decrypt them on the server. | the hosting company won't do a lot for you in terms of DDoS. As soon as it gets to large (which with most hosting is small) and/or floods the ISP they will blackhole you. Try something like Prolexic or Akamai (the later doing API with their new release). good luck. |
17,239,204 | Note that I am working in C++03, and the `delete`d functions of C++11 are not available to me.
I am attempting to design a non-copyable object, and prevent the compiler from considering the implicitly-declared copy constructor on that class. This is for a unit test fixture I am developing.
Consider that I have two main objects: a core library object, `Root`, and a derived special-case object under test, `Branch`. I am trying to develop a test fixture class, `Fixture` which handles the minutiae of setting up & talking to the core `Root` object. So this is a simplified illustration of what I've built so far:
([Here is an ideone link](http://ideone.com/TTE4qt) with the same code below, except I've defined my own `noncopyable`)
```
#include <boost/utility.hpp>
#include <boost/noncopyable.hpp>
class Root
{
};
class Fixture
:
public boost::noncopyable
{
public:
Fixture (Root& root)
:
mRoot (root)
{
}
private:
Root& mRoot;
};
class Branch
:
public Root,
public Fixture
{
public:
Branch()
:
Fixture (*this)
{
}
};
int main()
{
Branch branch;
}
```
Compiling this results in:
```
main.cpp: In constructor ‘Branch::Branch()’:
main.cpp:30:23: error: call of overloaded ‘Fixture(Branch&)’ is ambiguous
main.cpp:30:23: note: candidates are:
main.cpp:13:5: note: Fixture::Fixture(Root&)
main.cpp:8:7: note: Fixture::Fixture(const Fixture&)
```
It is not possible\* to prevent the C++03 compiler from implicitly declaring a copy constructor for `Fixture` unless I declare at least one on my own. But even with:
```
class Fixture
:
public boost::noncopyable
{
public:
Fixture (Root& root)
:
mRoot (root)
{
}
private:
Fixture (const Fixture&);
Fixture (Fixture&);
Root& mRoot;
};
```
...the compiler will still consider these `private` declarations when initializing `Fixture` in `Branch`'s initialization list:
```
Fixture (*this)
```
I want the compiler to simply not consider these copy constructors.
I could do this by doing a little contorting on my own:
```
Fixture (static_cast <Root&> (*this))
```
...but I'd rather not, as it's a bit smelly to my nose and non-copy-ability is the *semantics* of what I'm going for by deriving `Fixture` from `boost::noncopyable`.
Is there a way to prevent the compiler from considering implicitly-declared copy constructors in this case without changing code at the call-site from:
```
Fixture (*this)
```
?
---
* "It is not possible..." : Standard C++03: 12.8/4, "Special member functions":
>
> If the class definition does not explicitly declare a copy
> constructor, one is declared implicitly.
>
>
> | 2013/06/21 | [
"https://Stackoverflow.com/questions/17239204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241536/"
] | Your ambiguity is that `*this` can bind to both a `Root &` and a `Fixture &`, and both conversions are equally good (namely derived-to-base conversions).
The trick is to create an overload that's a *better* match. For example,
```
template <typename T> Fixture(T &)
```
is will match any lvalue *exactly*, and thus is a better match than an overload that requires a conversion.
However, this is too naive, since you don't actually want your `Fixture` to be constructible from just anything. Rather you want it to be constructible only from something that's derived from `Root`. We can disable the extraneous constructors with some SFINAE magic. First the C++11 version:
```
#include <type_traits>
template <typename T,
typename = typename std::enable_if<std::is_base_of<Root, T>::value>::type>
Fixture(T & x)
: mRoot(x)
{ }
```
In C++03, we use Boost, and we can't use default template arguments:
```
#include <boost/type_traits.hpp>
template <typename T>
Fixture(T & x,
typename boost::enable_if<boost::is_base_of<Root, T> >::type * = NULL)
: mRoot(x)
{ }
```
Now you are guaranteed that `T` is derived from `Root`. The overload of this templated constructor with `T = Branch` is an exact match, better than the copy constructor, and so it is selected as the best overload unambiguously. | There is no way to prevent the existence of the copy constructor signature, not in C++98, and not in C++11 either. `= delete` does not remove something from the overload set either, it only fails if it is selected.
I have no better idea than to insert the explicit cast if you don't want to mess with the public interface of Fixture.
Options that do mess with the interface include passing the `Root` by pointer to distinguish from the reference of the copy constructor and passing a tag for the sake of overload resolution. Leave a comment if you want to know more about these. |
17,239,204 | Note that I am working in C++03, and the `delete`d functions of C++11 are not available to me.
I am attempting to design a non-copyable object, and prevent the compiler from considering the implicitly-declared copy constructor on that class. This is for a unit test fixture I am developing.
Consider that I have two main objects: a core library object, `Root`, and a derived special-case object under test, `Branch`. I am trying to develop a test fixture class, `Fixture` which handles the minutiae of setting up & talking to the core `Root` object. So this is a simplified illustration of what I've built so far:
([Here is an ideone link](http://ideone.com/TTE4qt) with the same code below, except I've defined my own `noncopyable`)
```
#include <boost/utility.hpp>
#include <boost/noncopyable.hpp>
class Root
{
};
class Fixture
:
public boost::noncopyable
{
public:
Fixture (Root& root)
:
mRoot (root)
{
}
private:
Root& mRoot;
};
class Branch
:
public Root,
public Fixture
{
public:
Branch()
:
Fixture (*this)
{
}
};
int main()
{
Branch branch;
}
```
Compiling this results in:
```
main.cpp: In constructor ‘Branch::Branch()’:
main.cpp:30:23: error: call of overloaded ‘Fixture(Branch&)’ is ambiguous
main.cpp:30:23: note: candidates are:
main.cpp:13:5: note: Fixture::Fixture(Root&)
main.cpp:8:7: note: Fixture::Fixture(const Fixture&)
```
It is not possible\* to prevent the C++03 compiler from implicitly declaring a copy constructor for `Fixture` unless I declare at least one on my own. But even with:
```
class Fixture
:
public boost::noncopyable
{
public:
Fixture (Root& root)
:
mRoot (root)
{
}
private:
Fixture (const Fixture&);
Fixture (Fixture&);
Root& mRoot;
};
```
...the compiler will still consider these `private` declarations when initializing `Fixture` in `Branch`'s initialization list:
```
Fixture (*this)
```
I want the compiler to simply not consider these copy constructors.
I could do this by doing a little contorting on my own:
```
Fixture (static_cast <Root&> (*this))
```
...but I'd rather not, as it's a bit smelly to my nose and non-copy-ability is the *semantics* of what I'm going for by deriving `Fixture` from `boost::noncopyable`.
Is there a way to prevent the compiler from considering implicitly-declared copy constructors in this case without changing code at the call-site from:
```
Fixture (*this)
```
?
---
* "It is not possible..." : Standard C++03: 12.8/4, "Special member functions":
>
> If the class definition does not explicitly declare a copy
> constructor, one is declared implicitly.
>
>
> | 2013/06/21 | [
"https://Stackoverflow.com/questions/17239204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241536/"
] | Your ambiguity is that `*this` can bind to both a `Root &` and a `Fixture &`, and both conversions are equally good (namely derived-to-base conversions).
The trick is to create an overload that's a *better* match. For example,
```
template <typename T> Fixture(T &)
```
is will match any lvalue *exactly*, and thus is a better match than an overload that requires a conversion.
However, this is too naive, since you don't actually want your `Fixture` to be constructible from just anything. Rather you want it to be constructible only from something that's derived from `Root`. We can disable the extraneous constructors with some SFINAE magic. First the C++11 version:
```
#include <type_traits>
template <typename T,
typename = typename std::enable_if<std::is_base_of<Root, T>::value>::type>
Fixture(T & x)
: mRoot(x)
{ }
```
In C++03, we use Boost, and we can't use default template arguments:
```
#include <boost/type_traits.hpp>
template <typename T>
Fixture(T & x,
typename boost::enable_if<boost::is_base_of<Root, T> >::type * = NULL)
: mRoot(x)
{ }
```
Now you are guaranteed that `T` is derived from `Root`. The overload of this templated constructor with `T = Branch` is an exact match, better than the copy constructor, and so it is selected as the best overload unambiguously. | If you're not going to pass around `Branch` as an instance of `Fixture`, there is no need for inheriting it at all. What you basically would like to do is be able to set something up in `Fixture` for all instances of `Root`, if I'm not mistaken. So lets attack that cause, instead of bending C++. **DISCLAIMER**: If it's otherwise, I've no suggestions, I'm afraid.
For this problem, I'd make `Branch` have an instance of `Fixture` as it's member and overload copy-constructor of `Branch` to create the instance of `Fixture` by passing itself as the instance to `Fixture`'s constructor and assignment operator to never copy `Fixture` instance. A brief example is shown below:
```
#include <boost/utility.hpp>
#include <boost/noncopyable.hpp>
class Root
{
};
class Fixture
:
public boost::noncopyable
{
public:
Fixture (Root& root)
:
mRoot (root)
{
}
private:
Root& mRoot;
};
class Branch
:
public Root
{
public:
Branch()
: mFixture(*this)
{
}
Branch(const Branch& branch)
: Root(*this)
, mFixture(*this)
/* other 'Branch' members to be copied */
{
}
Branch& operator = (const Branch& branch)
{
Root::operator=(branch);
/* copy other 'Branch' members, except 'mFixture' */
}
Fixture& getFixture()
{
return mFixture;
}
const Fixture& getFixture() const
{
return mFixture;
}
private:
Fixture mFixture;
};
``` |
11,036,482 | I'm using the following to insert company data into a mysql table. Is is possible to check if the company is already in the database first before it tries to enter it in again? The php variable `$company` is what I want to check against.
```
<?php
require("database.php");
// Opens a connection to a MySQL server
$con = mysql_connect("localhost", $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("medicom_wp", $con);
$pages = get_posts(array(
'orderby' => 'title',
'post_type' => 'members',
'numberposts' => 300,
'post_status' => 'any'
));
foreach($pages as $post) {
setup_postdata($post);
$company = get_field('company_name');
$address = get_field('address');
$city = get_field('city');
$post_code = get_field('post_code');
mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
}
wp_reset_query();
mysql_close($con);
?>
``` | 2012/06/14 | [
"https://Stackoverflow.com/questions/11036482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609630/"
] | 1. Do a select statement to see if they are in there before doing the insert
2. (Not recommended) make the name field (or any other field that idnentifies a company, a unique key so when you try to enter it again it is rejected | The natural solution would be to run another query prior (e.g. select count()) to check if the marker exists, and branch your conditional logic from there.
A more interesting solution would be to use the concept of an **UPSERT** (Update + Insert). An upsert inserts the row if it doesn't exist, and updates it if it does exists. So effectively there will be only 1 row in the end regardless, but this is assuming you don't mind overwriting the data. [Here's a sample SO question about that.](https://stackoverflow.com/questions/1218905/how-do-i-update-if-exists-insert-if-not-aka-upsert-or-merge-in-mysql)
Another technique involves creating a primary key column and taking advantage of mysql's integrity checks to forcefully keep 1 row per record. So the first insert for each primary key would be successful, but all other would fail. |
11,036,482 | I'm using the following to insert company data into a mysql table. Is is possible to check if the company is already in the database first before it tries to enter it in again? The php variable `$company` is what I want to check against.
```
<?php
require("database.php");
// Opens a connection to a MySQL server
$con = mysql_connect("localhost", $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("medicom_wp", $con);
$pages = get_posts(array(
'orderby' => 'title',
'post_type' => 'members',
'numberposts' => 300,
'post_status' => 'any'
));
foreach($pages as $post) {
setup_postdata($post);
$company = get_field('company_name');
$address = get_field('address');
$city = get_field('city');
$post_code = get_field('post_code');
mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
}
wp_reset_query();
mysql_close($con);
?>
``` | 2012/06/14 | [
"https://Stackoverflow.com/questions/11036482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609630/"
] | Try the following. Basically, sending another query to check for a duplicate row with the same company name and if the query returns 0 rows then only run the insert command.
```
<?php
require("database.php");
// Opens a connection to a MySQL server
$con = mysql_connect("localhost", $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("medicom_wp", $con);
$pages = get_posts(array(
'orderby' => 'title',
'post_type' => 'members',
'numberposts' => 300,
'post_status' => 'any'
));
foreach($pages as $post) {
setup_postdata($post);
$company = get_field('company_name');
$address = get_field('address');
$city = get_field('city');
$post_code = get_field('post_code');
// prepare query to check for duplicate company
$sql = sprintf("select count('x') as cnt from markers where `name` = '%s'", mysql_real_escape_string($company));
// run query
$row_dup = mysql_fetch_assoc(mysql_query($sql,$conn));
// if no row exist
if ($row_dup['cnt'] == 0) {
// insert new company
// consider preparing this query using sprintf() and mysql_real_escape_string() as above
mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
}
}
wp_reset_query();
mysql_close($con);
?>
``` | 1. Do a select statement to see if they are in there before doing the insert
2. (Not recommended) make the name field (or any other field that idnentifies a company, a unique key so when you try to enter it again it is rejected |
11,036,482 | I'm using the following to insert company data into a mysql table. Is is possible to check if the company is already in the database first before it tries to enter it in again? The php variable `$company` is what I want to check against.
```
<?php
require("database.php");
// Opens a connection to a MySQL server
$con = mysql_connect("localhost", $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("medicom_wp", $con);
$pages = get_posts(array(
'orderby' => 'title',
'post_type' => 'members',
'numberposts' => 300,
'post_status' => 'any'
));
foreach($pages as $post) {
setup_postdata($post);
$company = get_field('company_name');
$address = get_field('address');
$city = get_field('city');
$post_code = get_field('post_code');
mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
}
wp_reset_query();
mysql_close($con);
?>
``` | 2012/06/14 | [
"https://Stackoverflow.com/questions/11036482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609630/"
] | Try the following. Basically, sending another query to check for a duplicate row with the same company name and if the query returns 0 rows then only run the insert command.
```
<?php
require("database.php");
// Opens a connection to a MySQL server
$con = mysql_connect("localhost", $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("medicom_wp", $con);
$pages = get_posts(array(
'orderby' => 'title',
'post_type' => 'members',
'numberposts' => 300,
'post_status' => 'any'
));
foreach($pages as $post) {
setup_postdata($post);
$company = get_field('company_name');
$address = get_field('address');
$city = get_field('city');
$post_code = get_field('post_code');
// prepare query to check for duplicate company
$sql = sprintf("select count('x') as cnt from markers where `name` = '%s'", mysql_real_escape_string($company));
// run query
$row_dup = mysql_fetch_assoc(mysql_query($sql,$conn));
// if no row exist
if ($row_dup['cnt'] == 0) {
// insert new company
// consider preparing this query using sprintf() and mysql_real_escape_string() as above
mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
}
}
wp_reset_query();
mysql_close($con);
?>
``` | The natural solution would be to run another query prior (e.g. select count()) to check if the marker exists, and branch your conditional logic from there.
A more interesting solution would be to use the concept of an **UPSERT** (Update + Insert). An upsert inserts the row if it doesn't exist, and updates it if it does exists. So effectively there will be only 1 row in the end regardless, but this is assuming you don't mind overwriting the data. [Here's a sample SO question about that.](https://stackoverflow.com/questions/1218905/how-do-i-update-if-exists-insert-if-not-aka-upsert-or-merge-in-mysql)
Another technique involves creating a primary key column and taking advantage of mysql's integrity checks to forcefully keep 1 row per record. So the first insert for each primary key would be successful, but all other would fail. |
24,166,616 | What is the correct way to return a string when no results are returned.
The following isn't working
```
SELECT
TOP 1 CASE
WHEN
CustomerName IS NULL
THEN
'Unknown'
WHEN
CustomerName = ''
THEN
'Unknown'
ELSE
CustomerName
END
AS
CustomerName FROM CUSTOMER WHERE CustomerCode = 222
``` | 2014/06/11 | [
"https://Stackoverflow.com/questions/24166616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974840/"
] | It seems you want to return `Unknown` when there are no rows in your table that have `CustomerName` that's not `NULL` or not `''`.
```
SELECT COALESCE((SELECT TOP 1 CustomerName FROM
CUSTOMER WHERE CustomerCode = 222
AND CustomerName IS NOT NULL
AND CustomerName <> ''),'Unknown') CustomerName
``` | Try this may be it's work..
```
SELECT DISTINCT TOP 1 CASE WHEN ISNULL(CustomerName,'') <>'' THEN CustomerName ELSE 'Unknown'
END as CustomerName FROM CUSTOMER WHERE CustomerCode = 222
```
or
```
SELECT TOP 1 CustomerName FROM
(SELECT DISTINCT TOP 1 CASE WHEN ISNULL(CustomerName,'') <>'' THEN CustomerName ELSE 'Unknown'
END as CustomerName ,1 No FROM CUSTOMER WHERE CustomerCode = 222
UNION
SELECT 'Unknown',2)
AS T ORDER BY No
``` |
24,166,616 | What is the correct way to return a string when no results are returned.
The following isn't working
```
SELECT
TOP 1 CASE
WHEN
CustomerName IS NULL
THEN
'Unknown'
WHEN
CustomerName = ''
THEN
'Unknown'
ELSE
CustomerName
END
AS
CustomerName FROM CUSTOMER WHERE CustomerCode = 222
``` | 2014/06/11 | [
"https://Stackoverflow.com/questions/24166616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974840/"
] | If I understand the question, you want to return a value even when the WHERE clause doesn't match, and you want 'Unknown' to replace the empty string or a NULL value:
```
SELECT TOP 1 COALESCE(NULLIF(CustomerName,''),'Unknown')
FROM (
SELECT CustomerName FROM CUSTOMER WHERE CustomerCode = 222
UNION ALL
SELECT NULL
) t
ORDER BY CustomerName DESC
``` | Try this may be it's work..
```
SELECT DISTINCT TOP 1 CASE WHEN ISNULL(CustomerName,'') <>'' THEN CustomerName ELSE 'Unknown'
END as CustomerName FROM CUSTOMER WHERE CustomerCode = 222
```
or
```
SELECT TOP 1 CustomerName FROM
(SELECT DISTINCT TOP 1 CASE WHEN ISNULL(CustomerName,'') <>'' THEN CustomerName ELSE 'Unknown'
END as CustomerName ,1 No FROM CUSTOMER WHERE CustomerCode = 222
UNION
SELECT 'Unknown',2)
AS T ORDER BY No
``` |
24,166,616 | What is the correct way to return a string when no results are returned.
The following isn't working
```
SELECT
TOP 1 CASE
WHEN
CustomerName IS NULL
THEN
'Unknown'
WHEN
CustomerName = ''
THEN
'Unknown'
ELSE
CustomerName
END
AS
CustomerName FROM CUSTOMER WHERE CustomerCode = 222
``` | 2014/06/11 | [
"https://Stackoverflow.com/questions/24166616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974840/"
] | It seems you want to return `Unknown` when there are no rows in your table that have `CustomerName` that's not `NULL` or not `''`.
```
SELECT COALESCE((SELECT TOP 1 CustomerName FROM
CUSTOMER WHERE CustomerCode = 222
AND CustomerName IS NOT NULL
AND CustomerName <> ''),'Unknown') CustomerName
``` | If I understand the question, you want to return a value even when the WHERE clause doesn't match, and you want 'Unknown' to replace the empty string or a NULL value:
```
SELECT TOP 1 COALESCE(NULLIF(CustomerName,''),'Unknown')
FROM (
SELECT CustomerName FROM CUSTOMER WHERE CustomerCode = 222
UNION ALL
SELECT NULL
) t
ORDER BY CustomerName DESC
``` |
128,855 | I try to help some people with basic English, and I'm not able to explain why "Everyone" takes a "s" with the simple present verb, and why "People" takes no "s".
I explained "Everyone" as a group, and group means a plural, but have a singular form. Example: a football team.
But with "people", my explanation get confusing. How to explain it, considering the students ask for a logic, if they are learning from a language with a very different logic.
In linguistics, how is it called?
PS: why there is no "indefinite pronouns" tags, nor "linguistics" tag? | 2017/05/09 | [
"https://ell.stackexchange.com/questions/128855",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/46339/"
] | "Everyone" is equivalent to "Every person". Although we are talking about multiple people, we are grammatically using a singular.
* Everyone (singular) **works** overtime today.
* Every person (singular) **works** overtime today.
"People", on the other hand, is the plural for "person". "Persons" *can be* correct in certain circumstances. But you'll want to use "people" in most cases.
* People (plural) **work** overtime today.
---
There are ways that you can say the same thing about a group of people, but you can grammatically use the singular if you want to:
* The Coca Cola employees (plural) **work** overtime today.
* The Coca Cola staff (singular) **works** overtime today. | Almost all English plural nouns end in *s* or *es* but there are about 20 or so nouns with irregular plurals (that aren't stolen from Latin) - and *people* is one of them. So it's treated the same way as a noun with *s* or *es* on the end.
*Everyone* is really the two words "every one" run together. So it's really *one* modified by *every*. You would use singular verb forms if *one* was the subject, and continue to do so if *one* was modified by another word.
Similar thread of logic with *everything*, *everywhere* and *everybody* (though "every body" does mean something different than "everybody" and "every where" doesn't work.) |
37,289,099 | I was thinking about trying to get MySQL working with my ASP.NET Core application and so I added `"MySql.Data": "6.9.8"` to my project.json dependencies.
Doing so and running `dotnet restore` I get `Package MySql.Data 6.9.8 is not compatible with netcoreapp1.0`
I think this means that the MySQL ADO provider doesn't work with .NET Core, am I right? (Oh, and I'm not even talking Entity Framework here) Any way around this? | 2016/05/18 | [
"https://Stackoverflow.com/questions/37289099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1348592/"
] | Try adding "net46" within project.json
```
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"dnxcore50",
"net46",
"portable-net45+win8"
]
}
},
``` | There is a new package v 6.10 available on Nuget as a fix for this problem.
<https://www.nuget.org/packages/MySql.Data/6.10.0-alpha>
This is in alpha phase i hope soon the release version come. |
29,033,172 | I have a Label named "`Lable_Match`" (in self.view)
and a `UIView`(in self.view).
In that View there are 1000+ labels.
and view is move using touch move method. and When user move View and he touch end that time check view subview lable is on the "`Lable_Match`" if any one lable is on this so the check text are same or not. | 2015/03/13 | [
"https://Stackoverflow.com/questions/29033172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4194486/"
] | For user input, you usually want `CultureInfo.CurrentCulture`. The fact that *you're* using a locale that's not natural to you is not the usual user case - if the user has `,` as the decimal point in their whole system, they're probably used to using that, instead of your preferred `.`. In other words, while you're testing on a system with locale like that, *learn to use `,` instead of `.`* - it's part of what makes locale testing useful :)
On the other hand, if you're e.g. storing the values in a configuration file or something like that, you really want to use `CultureInfo.InvariantCulture`.
The thinking is rather simple - is it the user's data (=> `CurrentCulture`), or is it supposed to be global (=> `InvariantCulture`)? | If you do a correctly internationalized program...
A) If you are using Winforms or WPF or in general the user will "work" on the machine of the program, then input parsing should be done with the `CurrentCulture`
B) If you are web-programming, then the user should be able to select its culture, and `CurrentCulture` (the culture of the web-server) should be only used as a default
And then,
A) data you save "internally" (so to be written and then read by your program) should use `InvariantCulture`,
B) data you interchange with other apps would be better to be written with `InvariantCulture` (unless the other app is badly written and requires a specific format),
C) files you export to the user should follow the previous rules (the ones about user interface), unless you are using a "standard-defined format" like XML (then use Xml formatters) |
18,805,601 | I'm having a problem using Ember. When I change a model, its "isDirty" flag becomes true, which is what I expect.
However, after that its "isDirty" flag is true, even after I save that model.
Here's a minimal Rails + Ember project (so I can actually save the model) that shows the situation:
<https://github.com/csterritt/etst>
Am I doing something wrong? Is this expected behavior?
Thanks!
---
**Edit:** Turns out that, as Jeremy Green pointed out below, the "isDirty" flag works for Ember Data.
And, it works with the current Ember 1.0.0 (standard, not -latest) and Ember Data beta.
I was doing:
```
isClean: ( ->
! @get("isDirty")
).property("name", "age", "favorite_food")
```
Which was due to a misunderstanding on my part. Changing this to:
```
isClean: ( ->
! @get("isDirty")
).property("isDirty")
```
Works properly.
Unfortunately, this doesn't solve the Epf version's problem. Epf-ites? | 2013/09/14 | [
"https://Stackoverflow.com/questions/18805601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2151750/"
] | Here's probably the funniest answer: assume your file is `file.txt`, then just do this:
```
printf 'curl http://example.com/?vehicle=%s&number=%s&period=%s\n' $(<file.txt)
```
It:
* is 100% pure bash,
* has no explicit loops
* is the shortest answer
* is very funny
Hope this helps `:)` | Try this:
```
while read vehicle number period ; do
echo curl http://example.com/\?vehicle="$vehicle"\&number="$number"\&period="$period"
done < input.txt
``` |
18,805,601 | I'm having a problem using Ember. When I change a model, its "isDirty" flag becomes true, which is what I expect.
However, after that its "isDirty" flag is true, even after I save that model.
Here's a minimal Rails + Ember project (so I can actually save the model) that shows the situation:
<https://github.com/csterritt/etst>
Am I doing something wrong? Is this expected behavior?
Thanks!
---
**Edit:** Turns out that, as Jeremy Green pointed out below, the "isDirty" flag works for Ember Data.
And, it works with the current Ember 1.0.0 (standard, not -latest) and Ember Data beta.
I was doing:
```
isClean: ( ->
! @get("isDirty")
).property("name", "age", "favorite_food")
```
Which was due to a misunderstanding on my part. Changing this to:
```
isClean: ( ->
! @get("isDirty")
).property("isDirty")
```
Works properly.
Unfortunately, this doesn't solve the Epf version's problem. Epf-ites? | 2013/09/14 | [
"https://Stackoverflow.com/questions/18805601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2151750/"
] | Here's probably the funniest answer: assume your file is `file.txt`, then just do this:
```
printf 'curl http://example.com/?vehicle=%s&number=%s&period=%s\n' $(<file.txt)
```
It:
* is 100% pure bash,
* has no explicit loops
* is the shortest answer
* is very funny
Hope this helps `:)` | Maybe use `sed` to interleave the URL arguments with other parts. Guessing from the sample you posted:
```
sed 's/\([a-z]*\) \([0-9]*\) \([A-Z]\)/curl http:\/\/example.com\/?vehicle=\1\&number=\2\&period=\3/'
``` |
285,329 | $A=\begin{bmatrix}
a & b\\
b & c
\end{bmatrix}$
Find any $(a,b,c) \in \mathbb{C}^3$ , $a \neq 0$ , $b \neq 0$ , $c \neq 0$ , so that eigenvalues of A are $\lambda\_1=\lambda\_2=1$
---
$det(A-\lambda I)=\begin{bmatrix}
a-\lambda & b\\
b & c- \lambda
\end{bmatrix}=(a-\lambda)(c-\lambda)-b^2=0$
$\Longrightarrow$
$\lambda^2-\lambda(a+c)+ac-b^2=0$
$\lambda=\frac{a+c \pm \sqrt{a^2+4b^2-2ac+c^2}}{2}$
$\Longrightarrow$
$a^2+4b^2-2ac+c^2=0$ and $\frac{a+c}{2}=1$
(discriminant is 0 because I want a double root, and (a+c)/2=1 because I want it to be 1)
---
but I can't find any solution, is there something wrong?
---
$\Longrightarrow$
$c=2-a$
and
$4a^2-8a+4b^2+4=0$
$a= 1 \pm b \cdot i $
Whatever value I give to a, it won't work... | 2013/01/23 | [
"https://math.stackexchange.com/questions/285329",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/57112/"
] | You are very close, everything is okay up to the step: $4a^2-8a+4b^2+4=0$.
This reduces to $a^2-2a+b^2+1=0$
Now, solve for
$$b = \pm \sqrt{-(a-1)^{2}} = \pm i(a-1)$$
So, you are free to choose $a's$.
Regards | Your work looks OK up to $4a^2-8a+4b^2+4=0$.
This reduces to $a^2-2a+b^2+1=0$, and you can try a few values for $a$ and $b$. I tried $a=3$, which yielded $c=-1$ and $b=2i$. The resulting matrix has the eigenvalues you want. |
74,485,961 | ```
const human = {
name: "asdasd",
mouth: {
sayName(){
console.log(this.name)
}
}
}
human.mouth.sayName()
// undefined
```
HELLO!
I need the name field to be taken from the parent object
THANK YOU! | 2022/11/18 | [
"https://Stackoverflow.com/questions/74485961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12106806/"
] | You're using a function called `check`, and it doesn't exist - like your error is telling you. There's one in your class, but that isn't in the same scope so you can't just call it using its name.
To access a method in a class, use `self.<name>`.
Also, you should only *pass the check function*, not *call* it.
```py
(..., check=self.check
```
**EDIT** the code in the original question was edited. You're not loading your cogs asynchronously. Extensions & cogs were made async in 2.0. Docs: <https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous> | Put this code in your `@commands.Cog.listener()` decorator, and the code will work if your cogs loader is working. If you would like me to show you my cogs loader, I can.
```py
accept = '✅'
decline = ''
def check(reaction, user):
return user == author
messsage = await ctx.send("test")
await message.add_reaction(accept)
await message.add_reaction(decline)
reaction = await self.bot.wait_for("reaction_add", check=check)
if str(reaction[0]) == accept:
await ctx.send("Accepted")
elif str(reaction[0]) == decline:
await ctx.send("Denied")
``` |
620,827 | I'm a bit hung up on the idea of forces at either end of a spring being equal, surely by extending the spring you are moving its centre of mass and hence applying a resultant force on it. I get it when the spring is not extending or has already extended, but while it is extending surely the force pulling the molecules apart must be greater than the force pulling them back together and hence there should be a resultant force on each molecule. And then this should accumulate throughout the spring as the force pulling on each molecule gets smaller such that though the fixed end of the spring is in equilibrium, the forces acting on it are less than the force pulling at the other end of the spring. | 2021/03/13 | [
"https://physics.stackexchange.com/questions/620827",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/291944/"
] | >
> I'm a bit hung up on the idea of forces at either end of a spring
> being equal, surely by extending the spring you are moving its centre
> of mass and hence applying a resultant force on it.
>
>
>
Yes.
If the spring is *being extended* then almost by definition its Centre of Mass (in the case of a **massive spring**) is accelerating. *Being extended* here means that one end moves and the other not or than one end moves faster than the other.
This means that acc. Newton's Second Law there must be a *net force* acting on the spring. This in turn means the forces acting on both ends cannot be the same. | The forces are equal at the ends because if they were not one end or the other would move.
If you replace the spring with an elastic string , it is easier to see that the tension in the string is the same all over. And also in the spring (which is a hard kind of curly string) the tension (force) is equal along the length of the spring. |
18,161,636 | I want to read json from php server using javascript (not jquery) like
```
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
json = xmlhttp.responseText;
JSON.parse(json, function (key, val) {
alert(key + '-'+ val);
});
}
}
```
in php file i do
```
$data = array();
$data['id'] = '1';
$data['name'] = '2';
print json_encode($data);
```
But output is
```
id-1
name-2
-[object Object] // why??
```
How to fix that thanks | 2013/08/10 | [
"https://Stackoverflow.com/questions/18161636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1600166/"
] | If you are using normal javascript, You want to loop through the properties of an object, which u can do it in javascript with `for in` statement.
```
<script>
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
var data = JSON.parse(xmlhttp.responseText);
for(key in data)
{
alert(key + ' - '+ data[key]); //outputs key and value
}
}
}
xmlhttp.open("GET","sample.php",true); //Say my php file name is sample.php
xmlhttp.send();
</script>
``` | From the [MDN documentation about `JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse):
>
> The reviver is ultimately called with the empty string and the topmost value to permit transformation of the topmost value.
>
>
>
Parsing `{"id":"1","name":"2"}` will generate a JavaScript object. Hence, in the last call of the reviver function, `key` is an empty string and `val` is the generated object.
The default string representation of any object is `[object Object]`, so the output you get is not surprising.
Here is a simpler example:
```
// object vv
alert('Object string representation: ' + {});
```
You usually only use a reviver function if you want to transform the parsed data immediately. You can just do:
```
var obj = JSON.parse(json);
```
and then iterate over the object or access its properties directly. Have a look at [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) for more information. |
38,727,544 | I normally don't ask questions here because most of the times I can find answers. But at this moment I haven´t find one, and I am really stuck. I have a problem trying to get access token for the Cherwell api: <http://13.88.176.216/CherwellAPI/Swagger/ui/index#!/Service/Service_Token> I used postman to generate this code:
This is relevant to Cherwell Service Management's V8+ REST API.
Code that throws server run time exception:
```
string user = "myUser";
string password = "myPassword";
var client1 = new RestClient("http://13.88.176.216/cherwellapi/token?auth_mode=Internal");
client.Authenticator = new HttpBasicAuthenticator(user, password);
var request1 = new RestRequest(Method.POST);
request1.AddHeader("content-type", "application/x-www-form-urlencoded");
request1.AddHeader("cache-control", "no-cache");
request1.AddParameter("application/x-www-form-urlencoded", "grant_type=password&client_id=my_client_id&client_secret=my_client_secret", ParameterType.RequestBody);
IRestResponse response = client1.Execute(request1);
```
The thing is when I execute the same method from the swagger ui (<http://13.88.176.216/CherwellAPI/Swagger/ui/index#!/Service/Service_Token>) I can get the token without getting any error.
Details of the request in CURL:
Curl
curl -X POST
--header "Content-Type: application/x-www-form-urlencoded"
--header "Accept: application/json" -d "grant\_type=password&client\_id=my\_client\_id&client\_secret=my\_client\_secret&username=my\_user\_name&password=my\_password" "<http://13.88.176.216/CherwellAPI/token?auth_mode=Internal>"
Request URL
<http://13.88.176.216/CherwellAPI/token?auth_mode=Internal>
This is the response body from the swagger ui test, not my code:
```
{
"access_token": "the_acces_token",
"token_type": "bearer",
"expires_in": 1199,
"refresh_token": "the_refresh_token",
"as:client_id": "client_key",
"username": "user",
".issued": "date",
".expires": "other_date"
}
```
Any help will be appreciated. | 2016/08/02 | [
"https://Stackoverflow.com/questions/38727544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3357141/"
] | You should probably edit (parts of) your last two ... er, now, *three*—comments into your question, but for now, I'll just quote them here:
>
> I found where I might have off road. When I checked-out the branch I was going to work on, I got this message (let's called the branch `b1`:
>
>
>
> ```
> Branch b1 set up to track remote branch b1 from origin.
> Switched to a new branch 'b1'.
>
> ```
>
> I checked-out the branch this way:
>
>
>
> ```
> git checkout b1.
>
> ```
>
> Then when I tried to push I did:
>
>
>
> ```
> git push --set-upstream origin b1.
> Branch b1 set up to track remote branch b1 from origin.
> Everything up to date
>
> ```
>
>
OK, in that case you are probably fine.
`git checkout`
==============
The problem you are running into here (well, in my opinion it's a problem) is that `git checkout` crams three or four (or more, depending on how you count) *different* things into one command.
Normally you would use:
```
git checkout somebranch
```
to check out (switch to) your local branch `somebranch`. Of course, that's great for branches you *already have*, but no good for branches you *don't* have locally yet. So Git crams another, different, command into `git checkout`: the "create new branch, then switch to it" command.
*Normally* this command is spelled `git checkout -b newbranch`. The `-b` flag means "create new". It's pretty reasonable to have this command spelled the same as `git checkout`, with just a flag, since we're switching to this newly created branch, but it probably would be clearer if it were a separate command, such as `git create-and-then-switch-to-new-branch`.
Now, pretty often, when you are creating a new *local* branch, you are doing so with the *intent* of having it "track" (as its "upstream") some existing *remote-tracking* branch, `origin/b1` or whatever. In this case, you originally had to type in:
```
git checkout -b b1 --track origin/b1
```
which is still really obvious: create new branch `b1`, base it off remote-tracking branch `origin/b1`, and make it *track* (have as its upstream) `origin/b1`. Again, this might be clearer as `git create-and-then-switch-to`, but it's not so bad to have it shoved into `git checkout`, plus `checkout` is a lot shorter to type!
Now, many years ago (back in 2013 or so), the Git folks saw that this action was pretty common, and decided to make Git do it "magically" for you ***under certain conditions***. If you write:
```
git checkout b1
```
**and** you don't currently have a branch `b1` **and** you *do* currently have an `origin/b1` **and** you don't have any *other* remote-tracking branch whose name ends in `b1`, ***then*** (and only then!), `git checkout` uses the create-and-then-switch-to-new-branch command, *with* the `--track` flag. So:
```
git checkout b1
```
means
```
git checkout -b b1 --track origin/b1
```
*in this one special (but common) case*.
### `--track` means "set upstream"
Each branch (well, each *named*, local, branch) can have one (1) "upstream" set. The upstream of a branch has a bunch of uses: `git status`, `git fetch`, `git merge`, `git rebase`, and `git push` all look at the upstream. Having an upstream set makes `git status` show how many commits you are ahead and/or behind of the current branch's upstream. And, it lets you run all the other commands with no additional arguments: they can figure out where to fetch from, or what to merge or rebase, or what to push, using the current branch's name and its upstream setting.
Branches do not *have* to have an upstream, and a new branch you create doesn't, by default. Moreover, if it's a "very new" branch—one that does not exist on `origin`, for instance—there's no `origin/name` yet to have as an upstream in the first place. But when you create a new branch *from* a remote-tracking branch, setting the remote-tracking branch as the upstream of the new branch is almost always the right thing.
(Note: having an upstream also affects `git pull` because `git pull` is just `git fetch` followed by either `git merge` or `git rebase`. Until they are very familiar with Git, I think most people are noticeably better off running `git fetch` first, then `git rebase` or `git merge` second, depending on which one they want—and more often, that's actually `git rebase`, which is *not* the default for `git pull`: `git pull` defaults to using `git merge` second. Once they are familiar with the fetch-and-whatever sequence, *then* people can configure `git pull` to do the one they intend, and use `git pull` as a shortcut to run both commands. However, there are times to keep them separate anyway.)
### For completeness
The other things that `git checkout` can do, that *don't* change the current branch, are:
* copy files from the index to the work-tree: `git checkout -- <paths>`, including the special `git checkout --ours` and `git checkout --theirs` variations
* copy files from specified commits to the index and then on to the work-tree: `git checkout <tree-ish> -- <paths>`
* restore conflicted merge files to their conflicted state: `git checkout -m -- <paths>` (as with `--ours` and `--theirs`, this only works during a conflicted merge)
* interactively patch files: `git checkout -p` (this variant gets especially complicated and I'm not going to address it further)
The `checkout` command can also "detach HEAD" (see previous answer below) and create "orphan" branches, but both of these effectively change your current branch, so they don't fall into this special "non-branch-changing" class of `checkout` operations.
### So what happened with the first `git push`
When you ran:
```
git push --set-upstream origin b1
```
you told your Git to contact the other Git on `origin`, give it the commit ID to which your branch `b1` pointed, see if it needed any of those commits and files (it didn't), and then ask it to set *its* branch name `b1` to point to the same commit.
Now, you'd just created your own local `b1` from your `origin/b1`, which you recently `git fetch`-ed from `origin`, so *your* `b1` already pointed to the *same* commit (you did not make any new commits) and hence your `git push` gave them their own commit hash back and they said "Well, gosh, that's what I already have! We're all up-to-date!" And then their Git and your Git said goodbye to each other, and your Git carried out your last instruction: `--set-upstream`.
This changed the upstream of your local branch `b1` to `origin/b1`. Of course, this was *already* the upstream for your local branch `b1`, so that was not a big change. :-) But your Git did it anyway, and then reported that everything was still up to date.
### Earlier answer (was mostly done when you added your third comment)
>
> ... I had one file committed with changes. `git status` didn't return nothing after I committed.
>
>
>
`git status` should always print *something*, such as (two actual examples):
```
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean
```
or:
```
HEAD detached at 08bb350
nothing to commit, working directory clean
```
In this second case, you are in "detached HEAD" mode. This special mode means you are not on a branch—or it may be more accurate to say that you are on the (single, special-case) *anonymous* branch that goes away as soon as you get on any *other* branch.
Any commits you make while in detached HEAD mode are perfectly fine, normal commits—except that there ***is no branch name that will make them permanent.*** This means these commits can go away once you switch to some other branch.
>
> All my attempts to `push` were unsuccessful.
>
>
>
Again, actual `git push` output might help here, so one could tell *why* the push failed or did nothing. If it complained about being in "detached HEAD" mode, that would be significant: we would know that you were in the detached HEAD mode.
>
> `git fetch -a` didn't return nothing as well.
>
>
>
(Just an aside: It's a bit odd to use `-a` here: that flag is almost never useful to humans and is intended more for scripting purposes. It just makes your `fetch` append to `FETCH_HEAD` rather than overwriting it. The special `FETCH_HEAD` name is meant for scripts to use.)
>
> the last step I had were to `git checkout origin/branch_name`.
>
>
>
This will take you off whatever branch you were on before, and put you in "detached HEAD" mode. If you used to be in "detached HEAD" mode, it will abandon your previous anonymous branch and put you on a new, different anonymous branch.
Any commits you made while on the previous anonymous branch are ... well, not *lost*, precisely, but are now difficult to find (and set to expire after 30 days).
>
> When I tried to push from there I got the following message:
>
>
>
> ```
> fatal: You are not currently on a branch.
> To push history leading to current (detached HEAD) state now, use:
>
> git push origin HEAD:<name-of-remote-branch>.
>
> ```
>
> Which I did [`... HEAD:origin/branch_name`] and it worked
>
>
>
Yes, but alas, this did nothing useful, because you are now on an anonymous branch that is *exactly the same as* `origin/branch_name`. This ends up asking the remote to create—on the remote, as a *local* branch there—the name `origin/branch_name`. That's probably not a good idea, since having a local branch named `origin/branch_name` is like having a bicycle named "motorcycle". If you also have a motorcycle and ask your friend to bring you "motorcycle", which will he bring you, the bicycle named "motorcycle", or the motorcycle? | **Current State:** Your head isn't attached to a branch, so you pushed with the branch whose history was the same as the remotes. You were working with a detached head, so when you pushed the head instead of the branch, it worked.
If you do a `git status` it with show:
>
> HEAD detached at XXXXXXX
>
>
>
**Fixing it:**
Now that your remote has the changes you made, you can checkout the `branch_name` and pull your changes from remote. Your `branch_name` should already be tracking that remote branch.
**Why you had to do this:** You somehow detached your head. Without knowing the commands you used, we won't be able to tell you why you had to do this.
An example of how you could have done this:
```
#Don't do this, because force pulling will make you lose your work.
git checkout --detach
git pull --all -f #Don't do this.
``` |
62,067 | **Question**: when did someone first call the astronomical objects that orbit planets "moons"? More precisely, I'm probably looking for the first use of *lunae* in this context. I assume that "moons" would have been a translation of the Latin word which astronomers tended to prefer.
**Presumed, but Incorrect Answer**: One might assume that the answer is whoever discovered the first such objects, but this is not the case. Galileo who discovered the first natural satellites other than the Moon **did not** call them *moons*. More on this below.
**Context**: I was trying to answer this question from the Astronomy Stack Exchange: [Do our sun and moon have names?](https://astronomy.stackexchange.com/questions/40110/do-our-sun-and-moon-have-names) but I've gotten stuck. The question as asked is backwards. The other planets' "moons" are named after the Moon and not the other way around. We call Earth's natural satellite *the Moon* because Middle English-speakers called it *mona*. And if we trace this word's origin back as far as we can, the theoretical Proto-Indo-European-speakers called the Moon \*mḗh₁n̥s, probably from the root meh₁- which meant *to measure*, since the Moon was used to measure time ([Wiktionary — Reconstruction:Proto-Indo-European/mḗh₁n̥s](https://en.wiktionary.org/wiki/Reconstruction:Proto-Indo-European/m%E1%B8%97h%E2%82%81n%CC%A5s)).
So there's a compelling theory about why we call the Moon *the Moon*, but why do we call other similar astronomical objects *moons*?
The naive, or the partial answer is that someone chose the word *moon* because these other bodies closely resembled the Moon. But this glib answer presumes that people in the past shared our current understanding of astronomy, and this is not true.
When Galileo first spotted the three (and then later the fourth) objects arrayed in a straight line near Jupiter, he described these objects as *Stellae* ("stars") and as *Planetea* ("planets") ([Wikipedia — *Sidereus Nuncius*](https://en.wikipedia.org/wiki/Sidereus_Nuncius). You can see a use of *Stellae* in one of the pictures on that site ([File:Medicean Stars.png](https://en.wikipedia.org/wiki/File:Medicean_Stars.png)). When giving them a proper name, Galileo initially chose *Cosmica Sidera* ("Cosimo's stars") and later *Medicea Sidera* ("the Medician stars").
To Galileo, it was *not* obvious that these objects were more similar to the Moon than to other celestial bodies. So who made the connection?
**Also Interesting, but not the Answer**: Johannes Kepler was apparently the first person to call the Galilean moons *satellites*, extending the meaning of the Latin word for "a body-guard, a courtier; an assistant" ([Online Etymology Dictionary — satellite](https://www.etymonline.com/word/satellite)). | 2020/12/02 | [
"https://history.stackexchange.com/questions/62067",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/44571/"
] | [Chistiaan Huygens](https://en.wikipedia.org/wiki/Christiaan_Huygens#Saturn%27s_rings_and_Titan) in 1656 is the first documented evidence.
---
The invention of the telescope limits this to after 1610. Since Galileo was the first to observe such objects, it was Kepler who in 1611 called them satellites in his *Narratio de observatis a se quatuor Iovis Satellitibus erronibus*. Which is about 'the *Satellites* wandering about Jupiter'.
The comparison to Earth's moon was then made by Huygens, who called Saturn's [Titan](https://en.wikipedia.org/wiki/Titan_(moon)#Naming) a/his *"luna"* and provided a rationale for making this comparison:
>
> Saturnius hic mundus adferat: si enim gravaté olim isti systemati assentientibus, scrupulum demere potuerunt quaternae circa Iovem repertae Lunae; manifestius utiq; nunc eos convincet unica illa circa Saturnum oberrans, atque ob hoc ipsum quod unica est, nostratis Lunas similitudinem magis exprimens ut omittam nunc aliam quoque Saturnij globi cum hoc nostro cognationem, quam in simili axium utriusque inclinatione invenient Astronomiae periti.[…]
>
> — ([archive.org](https://archive.org/stream/CristianiHugeni00Huyg#page/2/mode/2up/search/luna))
>
>
>
[On WP:](https://en.wikipedia.org/wiki/Christiaan_Huygens)
>
> 1656 – *De Saturni Luna observatio nova* (About the new observation of the moon of Saturn – discovery of Titan)
>
>
>
As confirmed by this article:
>
> Christiaan Huygens, the discoverer of Titan, was the first to use the term moon for such objects, calling Titan Luna Saturni or Luna Saturnia – "Saturn's moon" or "The Saturnian moon", because it stood in the same relation to Saturn as the Moon did to the Earth.
>
> — [Gravity Wiki: Natural satellite](https://gravity.wikia.org/wiki/Natural_satellite)
>
>
>
Apparently the earliest surviving copy of that text is found in *a history book* about the invention of telescopes, published almost immediately after Huygens first observation and conclusion, Huygen's text just slapped on for good measure to increase the length of the book.
>
> [](https://i.stack.imgur.com/q69oH.jpg) […]
>
> [](https://i.stack.imgur.com/ifcAp.png)
>
>
> — Petrus Borellus: "De vero telescopii inventore cum brevi omnium conspiciliorum historia; ubi de eorum confectione, ac usu, seu de effectibus agitur, novaque quaedam circa ea proponuntur, accessit etiam centuria observationum microcospicarum", Adrian Vlaaacq: Gent, 1655 (sic! on archive.org). ([archive.org](https://archive.org/details/bub_gb_pIsPAAAAQAAJ/page/n147/mode/2up)), Text printed with date of "March 5, 1656", page number on page: 62, page number in PDF: 148, original pamphlet 4 pages long. [English translation in the Hartlib Papers](https://www.dhi.ac.uk/hartlib/view?docset=additional&docname=TCDLaa5T).)
>
>
>
A note on the timeline of confusing dates:
Huygens discovered the object we now call Titan in March 1655, published a rushed but cautious pamphlet already calling it "Saturn's moon" in The Hague in March 1656. He did this because he wasn't really sure about all he concluded from his discovery but wanted to assure his primacy on this discovery in a time before copyright.
In that Latin paper we see all the terminology current at the time. Those objects around Jupiter were the most obvious to compare and those are called variously "star" *(stellulam)*, "satellite" *(novus Saturni satelles)*, "planet" *(planeta)*, "Medicaen planet" (Mediceos Jovi |[named after the Medici](https://en.wikipedia.org/wiki/Galilean_moons#Dedication_to_the_Medicis)), "companion", "follower". He already concludes that neither Jupiter's nor Saturn's 'planets' are properly called 'planets', as they are different from those in orbiting not the sun, but orbiting an object that orbits the sun. A difference in properties he claims no other astronomer before had recognised nor taken into account.
But as the very title of the pamphlet shows, his synonym Moon=satellite was already there, and within the text he just goes on to make this comparison:
>
> Caeterum mihi novum Saturniae lunae phaenomenon ad haec quoque viam aperuit
>
> (However, this new phenomenon of Saturn's moon…)
>
>
>
It took a little while longer for him to publish his full treatise on *why* the moon of Saturn is really much like Earth's moon, together with his explanation of Saturn's rings in his [Systema Saturnium](https://www.sil.si.edu/DigitalCollections/HST/Huygens/huygens-text.htm) in 1659.
In this we find his explanation, him still juggling with other terminology of planets, star, satellite, for the 'new', 'Saturn's moon', and the moons around Jupiter:
>
> Now I was greatly helped in this matter not only by those more genuine phases, but also by the motion of Saturn's Moon, which I observed from the beginning; indeed it was the revolution of this Moon around Saturn that first caused to dawn upon me the hope of constructing the hypothesis. The nature of this hypothesis I will proceed to explain in what follows.
>
>
> When, then, I had discovered that the new planet revolved around Saturn in a period of sixteen days, I thought that without any doubt Saturn rotated on his own axis in even less time. For even before this I had always believed that the other primary planets were like our Earth in this respect that each rotated on its own axis, and so the entire surface rejoiced in the light of the Sun, a part at a time; and, more than this, I believe that in general the arrangement with the large bodies of the world was such that those around which smaller bodies revolved, having themselves a central position, had also a shorter period of rotation. Thus the Sun, its spots declare, rotates on its own axis in about twenty-six days; but around the Sun the various planets, among which the Earth is also to be reckoned, complete their courses in times varying as their distances. Again, this Earth rotates in daily course, and around the Earth the Moon circles with monthly motion. Around the planet Jupiter four smaller planets, that is to say Moons, revolve, subject to this same law, under which the velocities increase as the distances diminish. Whence, indeed, we must conclude perhaps that Jupiter rotates in a shorter time than 24 hours, since his nearest Moon requires less than two days. Now having long since learned all these facts, I concluded even then that Saturn must have a similar motion. But it was my observation in regard to his satellite that gave me the information about the velocity of his motion of rotarion. The fact that the satellite completes its orbit in sixteen days leads to the conclusion that Saturn, being in the centre of the satellite's orbit, rotates in much less time. Furthermore, the following conclusion seemed reasonable: that all the celestial matter that lies between Saturn and his satellite is subject to the same motion, in this way that the nearer it is to Saturn, the nearer it approaches Saturn's velocity. Whence, finally, the following resulted: the appendages also, or arms, of Saturn are either joined and attached to the globular body at its middle and go around with it, or, if they are separated by a certain distance, still revolve at a rate not much inferior to that of Saturn.
>
> — [In 1659 Christiaan Huygens published an article on Saturn's Ring in *Systema Saturnium.* The translation below is based on that made by J H Walden in 1928.](https://mathshistory.st-andrews.ac.uk/Extras/Huygens_Saturn/)
>
>
>
A nice outline of the events unfolding is to be read in the title:
— Albert van Helden: ["'Annulo Cingitur': The Solution to the Problem of Saturn"](http://articles.adsabs.harvard.edu/full/1974JHA.....5..155V/0000159.000.html), Journal for the History of Astronomy, Vol. 5, p.155, 1974.
This was for the *concept* of using a word for our moon to describe other celestial bodies that are natural satellites to other planets. But that went all on in Latin, the language Huygens used.
In English we see the Oxford English Dictionary give the earliest attestation at 1665 (as [shown in justCal's answer](https://history.stackexchange.com/a/62070) with the following description:
>
> 1665: Phil. Trans. I. 72 “The Conformity of these Moons with our Moon.”
> – OED 2nd edition
>
>
>
This is found in good visual quality in Vol 1, No 4, but on *page 74* in the article ["A Further Account,Touching Signor Campani's Book and Performances about Optick-Glasses (pp. 70-75)"](https://www.jstor.org/stable/101429)
This is however preceded by at least Robert Hooke's book [*Micrographia,*](https://en.wikipedia.org/wiki/Micrographia) which was published in the same year, albeit already in January, and as per imprint was ordered into printing on November 23. 1664:
>
> [](https://i.stack.imgur.com/ZN3BR.jpg)
>
> [](https://i.stack.imgur.com/Tc6Xn.jpg)
>
> This will seem much more consonant to the rest of the secundary Planets; for the highest of Jupiter's Moons is between twenty and thirty Jovial Semidiameters distant from the Center of Jupiter; and the Moons of Saturn much about the same number of Saturnial Semidiameters from the Center of that Planet. (p240)
>
> — Robert Hooke: "Micrographia", January 1665. ([archive.org](https://archive.org/details/b30326370))
>
>
>
Since the earliest pamphlet by Huygens was also sent to England (as in the Hartlib-source link above), where it might have been translated and shown around early, and surely discussed in the local tongue, and both the Philosophical Transactions as well as Hooke use it without much explanation: an even earlier date seems quite likely for a direct usage of 'moons' in this sense in English. | A publication from 1665, [Philosophical Transactions](https://books.google.com/books?id=4u2DURXGT-IC&pg=PA72&dq=moons%20satellites%20%20jupiter&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwik7-WEsK7tAhXNop4KHd16DnIQuwUwAXoECAIQBg#v=onepage&q=moons%20satellites%20%20jupiter&f=true), in an article which tosses about names like [Huygens](https://en.wikipedia.org/wiki/Christiaan_Huygens) and [Cassini](https://en.wikipedia.org/wiki/Giovanni_Domenico_Cassini), has a discussion concerning a publication by [Giuseppe Campani.](https://en.wikipedia.org/wiki/Giuseppe_Campani)
[](https://i.stack.imgur.com/I3utf.jpg)
This article discusses the similarity between Earth's moon and the satellites observed around Saturn and Jupiter, including a transition in terminology in the middle of the paragraph:
>
> no longer doubt can be made of the turning of these 4 ***Satellites, or
> Moons*** about Jupiter, as our Moon turns about the Earth.
>
>
>
If these observations were those of Campani, his work might hold your Latin root. Regardless you can at least narrow your answer to on or before Monday, June 5, 1665. |
69,761,783 | Given two integer arrays `a` and `b`, where the elements in `b` represent indices of `a`...
```
a = array([10,10,10,8,8,8])
b = array([0,2,3,5])
```
I want to generate a new array whose elements are the sums of the elements in `a` along the index ranges given in `b`, not including the element at the tail of the range... It's hard to put in words, but the expected result given `a` and `b` from above would be:
```
result = array([0, # sum(a[:0])
20, # sum(a[0:2])
10, # sum(a[2:3])
16]) # sum(a[3:5])
```
How could I achieve this in a vectorized/"numpythonic" way?
Thank you! | 2021/10/28 | [
"https://Stackoverflow.com/questions/69761783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11499001/"
] | You can try this:
```
import numpy as np
a = np.array([10,10,10,8,8,8])
b = np.array([0,2,3,5])
list(map(sum, np.split(a, b)))
```
It gives:
```
[0, 20, 10, 16, 8]
```
The last number is the sum of the slice `a[5:]`. | Is that what you are looking for?
```
import numpy as np
a = np.array([10,10,10,8,8,8])
b = np.array([0,2,3,5])
result = []
for i, v in enumerate(b):
result.append(sum(a[b[i-1]:v]))
result = np.array(result)
```
The result:
```
[ 0 20 10 16]
``` |
69,761,783 | Given two integer arrays `a` and `b`, where the elements in `b` represent indices of `a`...
```
a = array([10,10,10,8,8,8])
b = array([0,2,3,5])
```
I want to generate a new array whose elements are the sums of the elements in `a` along the index ranges given in `b`, not including the element at the tail of the range... It's hard to put in words, but the expected result given `a` and `b` from above would be:
```
result = array([0, # sum(a[:0])
20, # sum(a[0:2])
10, # sum(a[2:3])
16]) # sum(a[3:5])
```
How could I achieve this in a vectorized/"numpythonic" way?
Thank you! | 2021/10/28 | [
"https://Stackoverflow.com/questions/69761783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11499001/"
] | I think you are looking at [`np.ufunc.reduceat`](https://numpy.org/devdocs/reference/generated/numpy.ufunc.reduceat.html):
```
np.add.reduceat(a,b)
```
Out:
```
# gotta handle the case `b[0] == 0` separately
array([20, 10, 16, 8])
``` | Is that what you are looking for?
```
import numpy as np
a = np.array([10,10,10,8,8,8])
b = np.array([0,2,3,5])
result = []
for i, v in enumerate(b):
result.append(sum(a[b[i-1]:v]))
result = np.array(result)
```
The result:
```
[ 0 20 10 16]
``` |
69,761,783 | Given two integer arrays `a` and `b`, where the elements in `b` represent indices of `a`...
```
a = array([10,10,10,8,8,8])
b = array([0,2,3,5])
```
I want to generate a new array whose elements are the sums of the elements in `a` along the index ranges given in `b`, not including the element at the tail of the range... It's hard to put in words, but the expected result given `a` and `b` from above would be:
```
result = array([0, # sum(a[:0])
20, # sum(a[0:2])
10, # sum(a[2:3])
16]) # sum(a[3:5])
```
How could I achieve this in a vectorized/"numpythonic" way?
Thank you! | 2021/10/28 | [
"https://Stackoverflow.com/questions/69761783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11499001/"
] | I think you are looking at [`np.ufunc.reduceat`](https://numpy.org/devdocs/reference/generated/numpy.ufunc.reduceat.html):
```
np.add.reduceat(a,b)
```
Out:
```
# gotta handle the case `b[0] == 0` separately
array([20, 10, 16, 8])
``` | You can try this:
```
import numpy as np
a = np.array([10,10,10,8,8,8])
b = np.array([0,2,3,5])
list(map(sum, np.split(a, b)))
```
It gives:
```
[0, 20, 10, 16, 8]
```
The last number is the sum of the slice `a[5:]`. |
2,156,832 | I want to get some data between some 2 indexes.
For example, I have string: "just testing..." and I need string from 2 till 6. I should get:
'st tes'.
What function can do this for me? | 2010/01/28 | [
"https://Stackoverflow.com/questions/2156832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87152/"
] | Use `substr`:
```
std::string myString = "just testing...";
std::string theSubstring = myString.substr(2, 6);
```
Note that the second parameter is the *length* of the substring, not an index (your question is a bit unclear, since the substring from 2 to 6 is actually 'st t', not 'st tes'). | use the [substr](http://www.cplusplus.com/reference/string/string/substr/) method:
```
std::string theString = "just testing";
std::string theSubstring = theString.substr(2, 4);
``` |
30,034,822 | I am trying to fill a ComboBox with the days in the selected month with this
```
private void cboSelectMonth_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboSelectMonth.SelectedIndex >= 0)
{
int year = Convert.ToInt32(cboSelectYear.SelectedValue);
int month = Convert.ToInt32(cboSelectMonth.SelectedValue);
this.cboSelectDay.DisplayMember = "Text";
this.cboSelectDay.ValueMember = "Value";
int dayCount = DateTime.DaysInMonth(year, month);
var days = new[ dayCount+1 ] { };
for (int i = 1; i < dayCount +1; i++)
{
days[i] = new { Text = Convert.ToString(i), Value = i };
//cboSelectDay.Items.Add(i);
// days[] { new { Text = Convert.ToString(i), Value = i } };
}
this.cboSelectDay.DataSource = days;
DateTime now = DateTime.Now;
int dayValue = now.Day;
cboSelectDay.SelectedIndex = dayValue - 1;
}
}
```
So I am trying to end up with a ComboBox that lists all days from the current month. For instance, choosing September is going to add 30 days tot the ComboBox and choosing October would give you 31 etc. I am getting two errors. The first is on the `var days = new[ dayCount+1 ] { };` line, which says that a `']'` is exptected. The second error is on the `days[i] = new { Text = Convert.ToString(i), Value = i };`line which says Cannot implicitly convert type `'AnonymousType#1' to 'int'`
I am trying to do something similar to what I am doing with the Months, which does work (code block below). What am I doing wrong?
```
private void FillMonthCombobox()
{
this.cboSelectMonth.DisplayMember = "Text";
this.cboSelectMonth.ValueMember = "Value";
var months = new[]
{
new { Text = "January", Value = 1 },
new { Text = "February", Value = 2 },
new { Text = "March", Value = 3 },
new { Text = "April", Value = 4 },
new { Text = "May", Value = 5 },
new { Text = "June", Value = 6 },
new { Text = "July", Value = 7 },
new { Text = "Aughust", Value = 8 },
new { Text = "September", Value = 9 },
new { Text = "October", Value = 10 },
new { Text = "November", Value = 11 },
new { Text = "December", Value = 12 }
};
this.cboSelectMonth.DataSource = months;
DateTime now = DateTime.Now;
int monthValue = now.Month;
cboSelectMonth.SelectedIndex = monthValue - 1;
}
```
**Edit:** I can populate the ComboBox now but how do I add the Text = day and the Value = day to the loop so I can reference the Value later? In the case of this loop they will be the same but in the case of some other loops I am working with they will be different. Essentially I want to do the same thing I am doing in the second code block but with a loop. | 2015/05/04 | [
"https://Stackoverflow.com/questions/30034822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481813/"
] | It's simple, but you have to specify a year, too. Mind February and leap years!
```
int year = 2015;
int month = 5;
int[] days = Enumerable.Range(1, DateTime.DaysInMonth(year, month)).ToArray();
```
You can specify it as a `DataSource` afterwards:
```
cboSelectDay.DataSource = days;
cboSelectDay.DataBind();
``` | Using your general approach, this does work:
```
int thisMonthsDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
for (int i = 1; i <= thisMonthsDays; i++) { comboBox1.Items.Add(i); }
```
It fills a comboBox1 with (for May) with 31 days as expected.
Trying to work through and grasp it better, I think this update will help:
First a small class:
```
public class YearClass
{
public int IndexOfMonth { get; set; }
public string DayName { get; set; }
}
```
And now additional code to bind the month's days to a comboBox:
```
List<YearClass> months = new List<YearClass>();
int thisMonthsDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
for (int i = 1; i <= thisMonthsDays; i++)
{
YearClass currentDay = new YearClass();
currentDay.IndexOfMonth = i;
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, i);
currentDay.DayName = dt.DayOfWeek.ToString();
months.Add(currentDay);
}
comboBox1.DataSource = months;
comboBox1.DisplayMember = "DayName";
```
The output then looks like:
 |
30,034,822 | I am trying to fill a ComboBox with the days in the selected month with this
```
private void cboSelectMonth_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboSelectMonth.SelectedIndex >= 0)
{
int year = Convert.ToInt32(cboSelectYear.SelectedValue);
int month = Convert.ToInt32(cboSelectMonth.SelectedValue);
this.cboSelectDay.DisplayMember = "Text";
this.cboSelectDay.ValueMember = "Value";
int dayCount = DateTime.DaysInMonth(year, month);
var days = new[ dayCount+1 ] { };
for (int i = 1; i < dayCount +1; i++)
{
days[i] = new { Text = Convert.ToString(i), Value = i };
//cboSelectDay.Items.Add(i);
// days[] { new { Text = Convert.ToString(i), Value = i } };
}
this.cboSelectDay.DataSource = days;
DateTime now = DateTime.Now;
int dayValue = now.Day;
cboSelectDay.SelectedIndex = dayValue - 1;
}
}
```
So I am trying to end up with a ComboBox that lists all days from the current month. For instance, choosing September is going to add 30 days tot the ComboBox and choosing October would give you 31 etc. I am getting two errors. The first is on the `var days = new[ dayCount+1 ] { };` line, which says that a `']'` is exptected. The second error is on the `days[i] = new { Text = Convert.ToString(i), Value = i };`line which says Cannot implicitly convert type `'AnonymousType#1' to 'int'`
I am trying to do something similar to what I am doing with the Months, which does work (code block below). What am I doing wrong?
```
private void FillMonthCombobox()
{
this.cboSelectMonth.DisplayMember = "Text";
this.cboSelectMonth.ValueMember = "Value";
var months = new[]
{
new { Text = "January", Value = 1 },
new { Text = "February", Value = 2 },
new { Text = "March", Value = 3 },
new { Text = "April", Value = 4 },
new { Text = "May", Value = 5 },
new { Text = "June", Value = 6 },
new { Text = "July", Value = 7 },
new { Text = "Aughust", Value = 8 },
new { Text = "September", Value = 9 },
new { Text = "October", Value = 10 },
new { Text = "November", Value = 11 },
new { Text = "December", Value = 12 }
};
this.cboSelectMonth.DataSource = months;
DateTime now = DateTime.Now;
int monthValue = now.Month;
cboSelectMonth.SelectedIndex = monthValue - 1;
}
```
**Edit:** I can populate the ComboBox now but how do I add the Text = day and the Value = day to the loop so I can reference the Value later? In the case of this loop they will be the same but in the case of some other loops I am working with they will be different. Essentially I want to do the same thing I am doing in the second code block but with a loop. | 2015/05/04 | [
"https://Stackoverflow.com/questions/30034822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481813/"
] | It's simple, but you have to specify a year, too. Mind February and leap years!
```
int year = 2015;
int month = 5;
int[] days = Enumerable.Range(1, DateTime.DaysInMonth(year, month)).ToArray();
```
You can specify it as a `DataSource` afterwards:
```
cboSelectDay.DataSource = days;
cboSelectDay.DataBind();
``` | you can do this - I am passing hard coded values for year and month
```
for (int i = 0; i < DateTime.DaysInMonth(2015, 05); i++)
{
cmbMonth.Items.Add(i.ToString());
}
```
let me know if you have any other requirement |
30,034,822 | I am trying to fill a ComboBox with the days in the selected month with this
```
private void cboSelectMonth_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboSelectMonth.SelectedIndex >= 0)
{
int year = Convert.ToInt32(cboSelectYear.SelectedValue);
int month = Convert.ToInt32(cboSelectMonth.SelectedValue);
this.cboSelectDay.DisplayMember = "Text";
this.cboSelectDay.ValueMember = "Value";
int dayCount = DateTime.DaysInMonth(year, month);
var days = new[ dayCount+1 ] { };
for (int i = 1; i < dayCount +1; i++)
{
days[i] = new { Text = Convert.ToString(i), Value = i };
//cboSelectDay.Items.Add(i);
// days[] { new { Text = Convert.ToString(i), Value = i } };
}
this.cboSelectDay.DataSource = days;
DateTime now = DateTime.Now;
int dayValue = now.Day;
cboSelectDay.SelectedIndex = dayValue - 1;
}
}
```
So I am trying to end up with a ComboBox that lists all days from the current month. For instance, choosing September is going to add 30 days tot the ComboBox and choosing October would give you 31 etc. I am getting two errors. The first is on the `var days = new[ dayCount+1 ] { };` line, which says that a `']'` is exptected. The second error is on the `days[i] = new { Text = Convert.ToString(i), Value = i };`line which says Cannot implicitly convert type `'AnonymousType#1' to 'int'`
I am trying to do something similar to what I am doing with the Months, which does work (code block below). What am I doing wrong?
```
private void FillMonthCombobox()
{
this.cboSelectMonth.DisplayMember = "Text";
this.cboSelectMonth.ValueMember = "Value";
var months = new[]
{
new { Text = "January", Value = 1 },
new { Text = "February", Value = 2 },
new { Text = "March", Value = 3 },
new { Text = "April", Value = 4 },
new { Text = "May", Value = 5 },
new { Text = "June", Value = 6 },
new { Text = "July", Value = 7 },
new { Text = "Aughust", Value = 8 },
new { Text = "September", Value = 9 },
new { Text = "October", Value = 10 },
new { Text = "November", Value = 11 },
new { Text = "December", Value = 12 }
};
this.cboSelectMonth.DataSource = months;
DateTime now = DateTime.Now;
int monthValue = now.Month;
cboSelectMonth.SelectedIndex = monthValue - 1;
}
```
**Edit:** I can populate the ComboBox now but how do I add the Text = day and the Value = day to the loop so I can reference the Value later? In the case of this loop they will be the same but in the case of some other loops I am working with they will be different. Essentially I want to do the same thing I am doing in the second code block but with a loop. | 2015/05/04 | [
"https://Stackoverflow.com/questions/30034822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481813/"
] | Using your general approach, this does work:
```
int thisMonthsDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
for (int i = 1; i <= thisMonthsDays; i++) { comboBox1.Items.Add(i); }
```
It fills a comboBox1 with (for May) with 31 days as expected.
Trying to work through and grasp it better, I think this update will help:
First a small class:
```
public class YearClass
{
public int IndexOfMonth { get; set; }
public string DayName { get; set; }
}
```
And now additional code to bind the month's days to a comboBox:
```
List<YearClass> months = new List<YearClass>();
int thisMonthsDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
for (int i = 1; i <= thisMonthsDays; i++)
{
YearClass currentDay = new YearClass();
currentDay.IndexOfMonth = i;
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, i);
currentDay.DayName = dt.DayOfWeek.ToString();
months.Add(currentDay);
}
comboBox1.DataSource = months;
comboBox1.DisplayMember = "DayName";
```
The output then looks like:
 | you can do this - I am passing hard coded values for year and month
```
for (int i = 0; i < DateTime.DaysInMonth(2015, 05); i++)
{
cmbMonth.Items.Add(i.ToString());
}
```
let me know if you have any other requirement |
16,529,276 | I'm relatively new to python but I'm trying to understand something which seems basic.
Create a vector:
```
x = np.linspace(0,2,3)
Out[38]: array([ 0., 1., 2.])
```
now why isn't x[:,0] a value argument?
```
IndexError: invalid index
```
It must be x[0]. I have a function I am calling which calculates:
```
np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
Why can't what I have just be true regardless of the input? It many other languages, it is independent of there being other rows in the array. Perhaps I misunderstand something fundamental - sorry if so. I'd like to avoid putting:
```
if len(x) == 1:
norm = np.sqrt(x[0]**2 + x[1]**2 + x[2]**2)
else:
norm = np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
everywhere. Surely there is a way around this... thanks.
Edit: An example of it working in another language is Matlab:
```
>> b = [1,2,3]
b =
1 2 3
>> b(:,1)
ans =
1
>> b(1)
ans =
1
``` | 2013/05/13 | [
"https://Stackoverflow.com/questions/16529276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495869/"
] | Perhaps you are looking for this:
```
np.sqrt(x[...,0]**2 + x[...,1]**2 + x[...,2]**2)
```
There can be any number of dimensions in place of the ellipsis `...`
See also [What does the Python Ellipsis object do?](https://stackoverflow.com/q/772124/222914), and [the docs of NumPy basic slicing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing) | I tend to solve this is by writing
```
x = np.atleast_2d(x)
norm = np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
Matlab doesn't have 1D arrays, so `b=[1 2 3]` is still a 2D array and indexing with two dimensions makes sense. It can be a novel concept for you, but they're quite useful in fact (you can stop worrying whether you need to multiply by the transpose, insert a row or a column in another array...)
By the way, you could write a fancier, more general norm like this:
```
x = np.atleast_2d(x)
norm = np.sqrt((x**2).sum(axis=1))
``` |
16,529,276 | I'm relatively new to python but I'm trying to understand something which seems basic.
Create a vector:
```
x = np.linspace(0,2,3)
Out[38]: array([ 0., 1., 2.])
```
now why isn't x[:,0] a value argument?
```
IndexError: invalid index
```
It must be x[0]. I have a function I am calling which calculates:
```
np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
Why can't what I have just be true regardless of the input? It many other languages, it is independent of there being other rows in the array. Perhaps I misunderstand something fundamental - sorry if so. I'd like to avoid putting:
```
if len(x) == 1:
norm = np.sqrt(x[0]**2 + x[1]**2 + x[2]**2)
else:
norm = np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
everywhere. Surely there is a way around this... thanks.
Edit: An example of it working in another language is Matlab:
```
>> b = [1,2,3]
b =
1 2 3
>> b(:,1)
ans =
1
>> b(1)
ans =
1
``` | 2013/05/13 | [
"https://Stackoverflow.com/questions/16529276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495869/"
] | Perhaps you are looking for this:
```
np.sqrt(x[...,0]**2 + x[...,1]**2 + x[...,2]**2)
```
There can be any number of dimensions in place of the ellipsis `...`
See also [What does the Python Ellipsis object do?](https://stackoverflow.com/q/772124/222914), and [the docs of NumPy basic slicing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing) | The problem is that x[:,0] in Python isn't the same as in Matlab.
If you want to extract the first element in the single row vector you should go with
```
x[:1]
```
This is called a "slice". In this example it means that you take everything in the array from the first element to the element with index 1 (not included).
Remember that Python has zero-based numbering.
Another example may be:
```
x[0:2]
```
which would return the first and the second element of the array. |
16,529,276 | I'm relatively new to python but I'm trying to understand something which seems basic.
Create a vector:
```
x = np.linspace(0,2,3)
Out[38]: array([ 0., 1., 2.])
```
now why isn't x[:,0] a value argument?
```
IndexError: invalid index
```
It must be x[0]. I have a function I am calling which calculates:
```
np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
Why can't what I have just be true regardless of the input? It many other languages, it is independent of there being other rows in the array. Perhaps I misunderstand something fundamental - sorry if so. I'd like to avoid putting:
```
if len(x) == 1:
norm = np.sqrt(x[0]**2 + x[1]**2 + x[2]**2)
else:
norm = np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
everywhere. Surely there is a way around this... thanks.
Edit: An example of it working in another language is Matlab:
```
>> b = [1,2,3]
b =
1 2 3
>> b(:,1)
ans =
1
>> b(1)
ans =
1
``` | 2013/05/13 | [
"https://Stackoverflow.com/questions/16529276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495869/"
] | Perhaps you are looking for this:
```
np.sqrt(x[...,0]**2 + x[...,1]**2 + x[...,2]**2)
```
There can be any number of dimensions in place of the ellipsis `...`
See also [What does the Python Ellipsis object do?](https://stackoverflow.com/q/772124/222914), and [the docs of NumPy basic slicing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing) | It looks like the ellipsis as described by @JanneKarila has answered your question, but I'd like to point out how you might make your code a bit more "numpythonic". It appears you want to handle an n-dimensional array with the shape (d\_1, d\_2, ..., d\_{n-1}, 3), and compute the magnitudes of this collection of three-dimensional vectors, resulting in an (n-1)-dimensional array with shape (d\_1, d\_2, ..., d\_{n-1}). One simple way to do that is to square all the elements, then sum along the last axis, and then take the square root. If `x` is the array, that calculation can be written `np.sqrt(np.sum(x**2, axis=-1))`. The following shows a few examples.
x is 1-D, with shape (3,):
```
In [31]: x = np.array([1.0, 2.0, 3.0])
In [32]: np.sqrt(np.sum(x**2, axis=-1))
Out[32]: 3.7416573867739413
```
x is 2-D, with shape (2, 3):
```
In [33]: x = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
In [34]: x
Out[34]:
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
In [35]: np.sqrt(np.sum(x**2, axis=-1))
Out[35]: array([ 3.74165739, 8.77496439])
```
x is 3-D, with shape (2, 2, 3):
```
In [36]: x = np.arange(1.0, 13.0).reshape(2,2,3)
In [37]: x
Out[37]:
array([[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[ 7., 8., 9.],
[ 10., 11., 12.]]])
In [38]: np.sqrt(np.sum(x**2, axis=-1))
Out[38]:
array([[ 3.74165739, 8.77496439],
[ 13.92838828, 19.10497317]])
``` |
16,529,276 | I'm relatively new to python but I'm trying to understand something which seems basic.
Create a vector:
```
x = np.linspace(0,2,3)
Out[38]: array([ 0., 1., 2.])
```
now why isn't x[:,0] a value argument?
```
IndexError: invalid index
```
It must be x[0]. I have a function I am calling which calculates:
```
np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
Why can't what I have just be true regardless of the input? It many other languages, it is independent of there being other rows in the array. Perhaps I misunderstand something fundamental - sorry if so. I'd like to avoid putting:
```
if len(x) == 1:
norm = np.sqrt(x[0]**2 + x[1]**2 + x[2]**2)
else:
norm = np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
everywhere. Surely there is a way around this... thanks.
Edit: An example of it working in another language is Matlab:
```
>> b = [1,2,3]
b =
1 2 3
>> b(:,1)
ans =
1
>> b(1)
ans =
1
``` | 2013/05/13 | [
"https://Stackoverflow.com/questions/16529276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495869/"
] | I tend to solve this is by writing
```
x = np.atleast_2d(x)
norm = np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
Matlab doesn't have 1D arrays, so `b=[1 2 3]` is still a 2D array and indexing with two dimensions makes sense. It can be a novel concept for you, but they're quite useful in fact (you can stop worrying whether you need to multiply by the transpose, insert a row or a column in another array...)
By the way, you could write a fancier, more general norm like this:
```
x = np.atleast_2d(x)
norm = np.sqrt((x**2).sum(axis=1))
``` | The problem is that x[:,0] in Python isn't the same as in Matlab.
If you want to extract the first element in the single row vector you should go with
```
x[:1]
```
This is called a "slice". In this example it means that you take everything in the array from the first element to the element with index 1 (not included).
Remember that Python has zero-based numbering.
Another example may be:
```
x[0:2]
```
which would return the first and the second element of the array. |
16,529,276 | I'm relatively new to python but I'm trying to understand something which seems basic.
Create a vector:
```
x = np.linspace(0,2,3)
Out[38]: array([ 0., 1., 2.])
```
now why isn't x[:,0] a value argument?
```
IndexError: invalid index
```
It must be x[0]. I have a function I am calling which calculates:
```
np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
Why can't what I have just be true regardless of the input? It many other languages, it is independent of there being other rows in the array. Perhaps I misunderstand something fundamental - sorry if so. I'd like to avoid putting:
```
if len(x) == 1:
norm = np.sqrt(x[0]**2 + x[1]**2 + x[2]**2)
else:
norm = np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
everywhere. Surely there is a way around this... thanks.
Edit: An example of it working in another language is Matlab:
```
>> b = [1,2,3]
b =
1 2 3
>> b(:,1)
ans =
1
>> b(1)
ans =
1
``` | 2013/05/13 | [
"https://Stackoverflow.com/questions/16529276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495869/"
] | It looks like the ellipsis as described by @JanneKarila has answered your question, but I'd like to point out how you might make your code a bit more "numpythonic". It appears you want to handle an n-dimensional array with the shape (d\_1, d\_2, ..., d\_{n-1}, 3), and compute the magnitudes of this collection of three-dimensional vectors, resulting in an (n-1)-dimensional array with shape (d\_1, d\_2, ..., d\_{n-1}). One simple way to do that is to square all the elements, then sum along the last axis, and then take the square root. If `x` is the array, that calculation can be written `np.sqrt(np.sum(x**2, axis=-1))`. The following shows a few examples.
x is 1-D, with shape (3,):
```
In [31]: x = np.array([1.0, 2.0, 3.0])
In [32]: np.sqrt(np.sum(x**2, axis=-1))
Out[32]: 3.7416573867739413
```
x is 2-D, with shape (2, 3):
```
In [33]: x = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
In [34]: x
Out[34]:
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
In [35]: np.sqrt(np.sum(x**2, axis=-1))
Out[35]: array([ 3.74165739, 8.77496439])
```
x is 3-D, with shape (2, 2, 3):
```
In [36]: x = np.arange(1.0, 13.0).reshape(2,2,3)
In [37]: x
Out[37]:
array([[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[ 7., 8., 9.],
[ 10., 11., 12.]]])
In [38]: np.sqrt(np.sum(x**2, axis=-1))
Out[38]:
array([[ 3.74165739, 8.77496439],
[ 13.92838828, 19.10497317]])
``` | I tend to solve this is by writing
```
x = np.atleast_2d(x)
norm = np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
Matlab doesn't have 1D arrays, so `b=[1 2 3]` is still a 2D array and indexing with two dimensions makes sense. It can be a novel concept for you, but they're quite useful in fact (you can stop worrying whether you need to multiply by the transpose, insert a row or a column in another array...)
By the way, you could write a fancier, more general norm like this:
```
x = np.atleast_2d(x)
norm = np.sqrt((x**2).sum(axis=1))
``` |
16,529,276 | I'm relatively new to python but I'm trying to understand something which seems basic.
Create a vector:
```
x = np.linspace(0,2,3)
Out[38]: array([ 0., 1., 2.])
```
now why isn't x[:,0] a value argument?
```
IndexError: invalid index
```
It must be x[0]. I have a function I am calling which calculates:
```
np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
Why can't what I have just be true regardless of the input? It many other languages, it is independent of there being other rows in the array. Perhaps I misunderstand something fundamental - sorry if so. I'd like to avoid putting:
```
if len(x) == 1:
norm = np.sqrt(x[0]**2 + x[1]**2 + x[2]**2)
else:
norm = np.sqrt(x[:,0]**2 + x[:,1]**2 + x[:,2]**2)
```
everywhere. Surely there is a way around this... thanks.
Edit: An example of it working in another language is Matlab:
```
>> b = [1,2,3]
b =
1 2 3
>> b(:,1)
ans =
1
>> b(1)
ans =
1
``` | 2013/05/13 | [
"https://Stackoverflow.com/questions/16529276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495869/"
] | It looks like the ellipsis as described by @JanneKarila has answered your question, but I'd like to point out how you might make your code a bit more "numpythonic". It appears you want to handle an n-dimensional array with the shape (d\_1, d\_2, ..., d\_{n-1}, 3), and compute the magnitudes of this collection of three-dimensional vectors, resulting in an (n-1)-dimensional array with shape (d\_1, d\_2, ..., d\_{n-1}). One simple way to do that is to square all the elements, then sum along the last axis, and then take the square root. If `x` is the array, that calculation can be written `np.sqrt(np.sum(x**2, axis=-1))`. The following shows a few examples.
x is 1-D, with shape (3,):
```
In [31]: x = np.array([1.0, 2.0, 3.0])
In [32]: np.sqrt(np.sum(x**2, axis=-1))
Out[32]: 3.7416573867739413
```
x is 2-D, with shape (2, 3):
```
In [33]: x = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
In [34]: x
Out[34]:
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
In [35]: np.sqrt(np.sum(x**2, axis=-1))
Out[35]: array([ 3.74165739, 8.77496439])
```
x is 3-D, with shape (2, 2, 3):
```
In [36]: x = np.arange(1.0, 13.0).reshape(2,2,3)
In [37]: x
Out[37]:
array([[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[ 7., 8., 9.],
[ 10., 11., 12.]]])
In [38]: np.sqrt(np.sum(x**2, axis=-1))
Out[38]:
array([[ 3.74165739, 8.77496439],
[ 13.92838828, 19.10497317]])
``` | The problem is that x[:,0] in Python isn't the same as in Matlab.
If you want to extract the first element in the single row vector you should go with
```
x[:1]
```
This is called a "slice". In this example it means that you take everything in the array from the first element to the element with index 1 (not included).
Remember that Python has zero-based numbering.
Another example may be:
```
x[0:2]
```
which would return the first and the second element of the array. |
20,641,922 | I have question regarding the performance factor for the following question.
Consider a table : Users,
```
-----userId------- userName-----
1 ABC
2 XYZ
```
Another table : Transaction,
```
------createdBy----ReceivedBy----TransactionId
1 2 50
2 1 51
```
My required result is,
```
--------createdBy----ReceivedBy----TransactionId----userName_Creator-----userName_Receiver
1 2 50 ABC XYZ
2 1 51 XYZ ABC
```
I came out with two solutions,
1. Using a varied inner join,
>
> SELECT \* FROM
> Transaction T
> INNER JOIN
> (
> SELECT createdBy,userName FROM Transaction
> Inner Join
> Users
>
>
>
> ```
> )
> ON createdBy = userId
> INNER JOIN
> (
> SELECT ReceivedBy,userName FROM Transaction
> Inner Join
> Users
> )
> ON ReceivedBy= userId
> WHERE TransactionId = 51
>
> ```
>
>
2.To maintain an hashmap for all the distinct userId and username and package the output by a look up in the data layer.
Which of these solution is optimal ? Also better technique is welcome.
--Siva | 2013/12/17 | [
"https://Stackoverflow.com/questions/20641922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922998/"
] | Your query is a good start, but it is unnecessarily complex. Try the following:
```
SELECT createdBy, ReceivedBy, TransactionId, userName
FROM Transaction
INNER JOIN Users ON createdBy = userId
```
Update: Doing it in the query is the better way (in my opinion), since it makes sense to get your data from the database the way you want to have it if possible. If you do (unnecessary) extra operations on your query result, your code will probably be harder to understand. To put it in a query is probably faster too, since your DBMS is optimized for this kind of operation. | why not simply doing something like:
```
select t.createdBy, t.ReceivedBy, t.TransactionId, u.userName
from Transactions u, Users u
where t.createdBy = u.userId
``` |
20,641,922 | I have question regarding the performance factor for the following question.
Consider a table : Users,
```
-----userId------- userName-----
1 ABC
2 XYZ
```
Another table : Transaction,
```
------createdBy----ReceivedBy----TransactionId
1 2 50
2 1 51
```
My required result is,
```
--------createdBy----ReceivedBy----TransactionId----userName_Creator-----userName_Receiver
1 2 50 ABC XYZ
2 1 51 XYZ ABC
```
I came out with two solutions,
1. Using a varied inner join,
>
> SELECT \* FROM
> Transaction T
> INNER JOIN
> (
> SELECT createdBy,userName FROM Transaction
> Inner Join
> Users
>
>
>
> ```
> )
> ON createdBy = userId
> INNER JOIN
> (
> SELECT ReceivedBy,userName FROM Transaction
> Inner Join
> Users
> )
> ON ReceivedBy= userId
> WHERE TransactionId = 51
>
> ```
>
>
2.To maintain an hashmap for all the distinct userId and username and package the output by a look up in the data layer.
Which of these solution is optimal ? Also better technique is welcome.
--Siva | 2013/12/17 | [
"https://Stackoverflow.com/questions/20641922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922998/"
] | Your query is a good start, but it is unnecessarily complex. Try the following:
```
SELECT createdBy, ReceivedBy, TransactionId, userName
FROM Transaction
INNER JOIN Users ON createdBy = userId
```
Update: Doing it in the query is the better way (in my opinion), since it makes sense to get your data from the database the way you want to have it if possible. If you do (unnecessary) extra operations on your query result, your code will probably be harder to understand. To put it in a query is probably faster too, since your DBMS is optimized for this kind of operation. | use this format:
```
SELECT a.batsman_id,a.matchs,a.hundreds,b.country_type, c.player_name
FROM batsman a
INNER JOIN countrycode b ON a.country_code=b.country_code
INNER JOIN players c ON a.player_id=c.player_id
ORDER BY a.batsman_id;
``` |
41,041,983 | I'm running an rsync daemon (providing a mirror for the SaneSecurity signatures).
rsync is started like this (from runit):
```
/usr/bin/rsync -v --daemon --no-detach
```
And the config contains:
```
use chroot = no
munge symlinks = no
max connections = 200
timeout = 30
syslog facility = local5
transfer logging = no
log file = /var/log/rsync.log
reverse lookup = no
[sanesecurity]
comment = SaneSecurity ClamAV Mirror
path = /srv/mirror/sanesecurity
read only = yes
list = no
uid = nobody
gid = nogroup
```
But what I'm seeing is a lot of "lingering" rsync processes:
```
# ps auxwww|grep rsync
root 423 0.0 0.0 4244 1140 ? Ss Oct30 0:00 runsv rsync
root 2529 0.0 0.0 11156 2196 ? S 15:00 0:00 /usr/bin/rsync -v --daemon --no-detach
nobody 4788 0.0 0.0 20536 2860 ? S 15:10 0:00 /usr/bin/rsync -v --daemon --no-detach
nobody 5094 0.0 0.0 19604 2448 ? S 15:13 0:00 /usr/bin/rsync -v --daemon --no-detach
root 5304 0.0 0.0 11156 180 ? S 15:15 0:00 /usr/bin/rsync -v --daemon --no-detach
root 5435 0.0 0.0 11156 180 ? S 15:16 0:00 /usr/bin/rsync -v --daemon --no-detach
root 5797 0.0 0.0 11156 180 ? S 15:19 0:00 /usr/bin/rsync -v --daemon --no-detach
nobody 5913 0.0 0.0 20536 2860 ? S 15:20 0:00 /usr/bin/rsync -v --daemon --no-detach
nobody 6032 0.0 0.0 20536 2860 ? S 15:21 0:00 /usr/bin/rsync -v --daemon --no-detach
root 6207 0.0 0.0 11156 180 ? S 15:22 0:00 /usr/bin/rsync -v --daemon --no-detach
nobody 6292 0.0 0.0 20544 2744 ? S 15:23 0:00 /usr/bin/rsync -v --daemon --no-detach
root 6467 0.0 0.0 11156 180 ? S 15:25 0:00 /usr/bin/rsync -v --daemon --no-detach
root 6905 0.0 0.0 11156 180 ? S 15:29 0:00 /usr/bin/rsync -v --daemon --no-detach
```
(it's currently 15:30)
So there's processes (not even having dropped privileges!) hanging around since 15:10, 15:13 and the like.
And what are they doing?
Let's check:
```
# strace -p 5304
strace: Process 5304 attached
select(4, [3], NULL, [3], {25, 19185}^C
strace: Process 5304 detached
<detached ...>
# strace -p 5797
strace: Process 5797 attached
select(4, [3], NULL, [3], {48, 634487}^C
strace: Process 5797 detached
<detached ...>
```
This happended with both rsync from Ubuntu Xenial as well as installed from PPA (currently using rsync 3.1.2-1~ubuntu16.04.1york0 ) | 2016/12/08 | [
"https://Stackoverflow.com/questions/41041983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618343/"
] | You need to make 2 small changes to a single line
```
Ext.get('txtUsuEmail').setStyle('background-color','#DC143C'); //change this as per below
```
1) Target specifically the `<input>` textbox using `Ext.get('txtUsuEmail-inputEl').`
2) Change the `background` property not the `background-color`.
So the final would look like:
```
Ext.get('txtUsuEmail-inputEl').setStyle('background','#DC143C');
```
This should work. | You could give an id to the textfield and simply use the below setStyle:
```
Ext.get('YourTextFieldId').setStyle('background', '#ABCDEF');
``` |
58,536,220 | ```
<input
ngModel
name='quantity'
placeholder='Quantity'
type="number"
class="form-control"
pattern="^\d*(\.\d{0,2})?$"
required />
<input
ngModel
name='price'
class="form-control"
placeholder='Price'
type="number"
required />
<input
name='total'
class="form-control"
type="number"
[value]='addRowForm.value.quantity * addRowForm.value.price' />
```
I have three input fields **Quantity, Price, Total**, The multiplication of quantity and price should be shown in the Total field, I can do this in Typescript code, But I wonder there is a simple solution to do it solely in the template.
I have tried this but it doesn't work.
`[value]='addRowForm.value.quantity * addRowForm.value.price'` | 2019/10/24 | [
"https://Stackoverflow.com/questions/58536220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3709523/"
] | Add `[(ngModel)]` in the fields.
Try like this:
**[Working Demo](https://stackblitz.com/edit/angular-qqjhbx?embed=1&file=src/app/app.component.html)**
```
<input [(ngModel)]="quantity" name='quantity' placeholder='Quantity' type="number" class="form-control" pattern="^\d*(\.\d{0,2})?$" required />
<input [(ngModel)]="price" name='price' class="form-control" placeholder='Price' type="number" required />
<input name='total' class="form-control" type="number" [(ngModel)]='quantity * price' />
```
You can also use it like this:
**[Demo](https://stackblitz.com/edit/angular-lsgbfy?embed=1&file=src/app/app.component.html)**
TS:
```
newRowDetails = {}
```
Template:
```
<input [(ngModel)]="newRowDetails.quantity" name='quantity' placeholder='Quantity' type="number" class="form-control" pattern="^\d*(\.\d{0,2})?$" required />
<input [(ngModel)]="newRowDetails.price" name='price' class="form-control" placeholder='Price' type="number" required />
<input name='total' class="form-control" type="number" [(ngModel)]='newRowDetails.quantity * newRowDetails.price' />
``` | Try this, use *double quotes* to evaluate the value of your variable.
```
<input name="total" class="form-control" type="number" [value]="addRowForm.value.quantity * addRowForm.value.price" />
``` |
512,947 | There are unknown number of lines in a file. How to delete nth line (when counted from the bottom) with one-liner command (you may use more than one if it is necessary) on Unix platform. | 2019/04/17 | [
"https://unix.stackexchange.com/questions/512947",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/347577/"
] | if `$n` hold number of line to delete
to delete a single line use
```
printf "\$-%d+1,\$-%d+1d\nwq\n" $n $n| ed -s file
```
to delete n last lines
```
printf "\$-%d,\$d\nwq\n" $n | ed -s file
```
where
* `\$%d,\$d` tell ed to delete n last lines (printf will insert n)
* `wq` write and quit
* `-s` in `ed -s` will keep ed silent.
* note that no provision is made to check you have enough line to delete.
sadly range **from end** can't be specified in `sed` ... | An one-line, in-place solution:
With `gawk`, this will delete the 42nd line from the bottom:
```
gawk -i inplace 'i==0 {if(FNR>t){t=FNR}else{i=1}} i==1 && FNR!=t-42 {print}' input input
```
The 42 can be replaced with any number. If 0 is used then the last line is deleted.
Notice that the `input` file is specified twice. This forces two iterations of the file with gawk. In the first iteration (`i==0`) the total number of lines (`t`) is established. In the second iteration, the nth line from the end is not output.
The file is modified in place by using the `-i` option. |
512,947 | There are unknown number of lines in a file. How to delete nth line (when counted from the bottom) with one-liner command (you may use more than one if it is necessary) on Unix platform. | 2019/04/17 | [
"https://unix.stackexchange.com/questions/512947",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/347577/"
] | Pure `sed`:
* If *n* is 1:
```
sed '$ d'
```
This is simple: if it's the last line, delete the pattern space, so it's not printed.
* If *n* is greater than 1 (and available as `$n`):
```
sed "
: start
1,$((n-1)) { N; b start }
$ { t end; s/^//; D }
N
P
D
: end
"
```
Note `$((n-1))` is expanded by the shell before `sed` starts.
This fragment
```
: start
1,$((n-1)) { N; b start }
```
stores *n*-1 lines in the pattern space. If `sed` reaches the end of the input stream during this loop, the pattern space will be printed automatically (there is no n-th line from the end, no line will be deleted).
Suppose there is more input. Then, before we get to the last line, this fragment is iterated:
```
N # read the next line of input and append it to the pattern space
P # print the first line from the pattern space
D # delete the first line from the pattern space and start a new cycle
```
This way the pattern space is our buffer which makes the output several lines "late" according to the input. `N` from this fragment is able to read the last line of the input as well.
After the last line is read, this gets executed:
```
$ { t end; s/^//; D }
```
When this code is executed for the first time, `t` doesn't branch to `end` because there was no successful substitution before. Such no-op substitution `s/^//` is then performed and the first line from the pattern space is deleted (`D`) without being printed. This is exactly the line you want to be deleted. Since `D` starts a new cycle, the same line of code will eventually be executed again. This time `t` will branch to `end`.
When `sed` reaches the end of the script, the pattern space is printed automatically. This way all remaining lines get printed.
The command will generate the same output for `n=2` (valid) and `n=1` (invalid). I tried to find a single solution that works regardless of *n*. I failed, hence the special case when your *n* is 1. | An one-line, in-place solution:
With `gawk`, this will delete the 42nd line from the bottom:
```
gawk -i inplace 'i==0 {if(FNR>t){t=FNR}else{i=1}} i==1 && FNR!=t-42 {print}' input input
```
The 42 can be replaced with any number. If 0 is used then the last line is deleted.
Notice that the `input` file is specified twice. This forces two iterations of the file with gawk. In the first iteration (`i==0`) the total number of lines (`t`) is established. In the second iteration, the nth line from the end is not output.
The file is modified in place by using the `-i` option. |
512,947 | There are unknown number of lines in a file. How to delete nth line (when counted from the bottom) with one-liner command (you may use more than one if it is necessary) on Unix platform. | 2019/04/17 | [
"https://unix.stackexchange.com/questions/512947",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/347577/"
] | Pure `sed`:
* If *n* is 1:
```
sed '$ d'
```
This is simple: if it's the last line, delete the pattern space, so it's not printed.
* If *n* is greater than 1 (and available as `$n`):
```
sed "
: start
1,$((n-1)) { N; b start }
$ { t end; s/^//; D }
N
P
D
: end
"
```
Note `$((n-1))` is expanded by the shell before `sed` starts.
This fragment
```
: start
1,$((n-1)) { N; b start }
```
stores *n*-1 lines in the pattern space. If `sed` reaches the end of the input stream during this loop, the pattern space will be printed automatically (there is no n-th line from the end, no line will be deleted).
Suppose there is more input. Then, before we get to the last line, this fragment is iterated:
```
N # read the next line of input and append it to the pattern space
P # print the first line from the pattern space
D # delete the first line from the pattern space and start a new cycle
```
This way the pattern space is our buffer which makes the output several lines "late" according to the input. `N` from this fragment is able to read the last line of the input as well.
After the last line is read, this gets executed:
```
$ { t end; s/^//; D }
```
When this code is executed for the first time, `t` doesn't branch to `end` because there was no successful substitution before. Such no-op substitution `s/^//` is then performed and the first line from the pattern space is deleted (`D`) without being printed. This is exactly the line you want to be deleted. Since `D` starts a new cycle, the same line of code will eventually be executed again. This time `t` will branch to `end`.
When `sed` reaches the end of the script, the pattern space is printed automatically. This way all remaining lines get printed.
The command will generate the same output for `n=2` (valid) and `n=1` (invalid). I tried to find a single solution that works regardless of *n*. I failed, hence the special case when your *n* is 1. | if `$n` hold number of line to delete
to delete a single line use
```
printf "\$-%d+1,\$-%d+1d\nwq\n" $n $n| ed -s file
```
to delete n last lines
```
printf "\$-%d,\$d\nwq\n" $n | ed -s file
```
where
* `\$%d,\$d` tell ed to delete n last lines (printf will insert n)
* `wq` write and quit
* `-s` in `ed -s` will keep ed silent.
* note that no provision is made to check you have enough line to delete.
sadly range **from end** can't be specified in `sed` ... |
512,947 | There are unknown number of lines in a file. How to delete nth line (when counted from the bottom) with one-liner command (you may use more than one if it is necessary) on Unix platform. | 2019/04/17 | [
"https://unix.stackexchange.com/questions/512947",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/347577/"
] | To remove for example the 4th line from the bottom using `sed`:
```
tac input | sed '4d' | tac
```
To overwrite the input file:
```
tmpfile=$(mktemp)
tac input | sed '4d' | tac > "$tmpfile" && mv "$tmpfile" input
``` | if `$n` hold number of line to delete
to delete a single line use
```
printf "\$-%d+1,\$-%d+1d\nwq\n" $n $n| ed -s file
```
to delete n last lines
```
printf "\$-%d,\$d\nwq\n" $n | ed -s file
```
where
* `\$%d,\$d` tell ed to delete n last lines (printf will insert n)
* `wq` write and quit
* `-s` in `ed -s` will keep ed silent.
* note that no provision is made to check you have enough line to delete.
sadly range **from end** can't be specified in `sed` ... |
512,947 | There are unknown number of lines in a file. How to delete nth line (when counted from the bottom) with one-liner command (you may use more than one if it is necessary) on Unix platform. | 2019/04/17 | [
"https://unix.stackexchange.com/questions/512947",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/347577/"
] | To remove for example the 4th line from the bottom using `sed`:
```
tac input | sed '4d' | tac
```
To overwrite the input file:
```
tmpfile=$(mktemp)
tac input | sed '4d' | tac > "$tmpfile" && mv "$tmpfile" input
``` | Neither standard `sed` nor `awk` support editing in place.
For that, you better use `ed(1)` or `ex(1)`:
```
printf '$-%dd\nw\n' 1 | ed -s your_file
```
Or with here-doc
```
ed -s <<'EOT' your_file
$-1d
w
EOT
```
With advanced shells like `bash`, `zsh` or`ksh93` you can use the `$'...'` syntax and here-strings:
```
ed -s <<<$'$-1d\nw' your_file
```
Notice that the `$` address means the last line from the file; so the index 1 there is **0-based**; for the 1st line from the end replace the 1 with 0 (`$-0`), for the 3nd with 2 (`$-2`), etc.
Putting it in a function:
```
del_nth_line_from_end(){ printf '$-%dd\nw\n' "$(($2-1))" | ed -s "$1"; }
```
Instead of `ed -s` you can use `ex -s` or `vim -es` everywhere. |
512,947 | There are unknown number of lines in a file. How to delete nth line (when counted from the bottom) with one-liner command (you may use more than one if it is necessary) on Unix platform. | 2019/04/17 | [
"https://unix.stackexchange.com/questions/512947",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/347577/"
] | You can combine `head` and `tail` to achieve this.
If the *nth* line from the bottom needs to be deleted
1. `head` reads from standard input and reports to standard output *total -n* lines from the top
2. `tail` reads and reports to standard output the bottom *n-1* lines from standard input.
3. Taken as a whole, the lines are thus reported to standard output in order, with the \*nth` line from the end being skipped
This solution depends on `head` leaving the file offset of the open file description just after the last reported line - I believe GNU `head` does indeed do this when standard input is redirected from a file
```
n=200; tmpfile=$(mktemp) && { head -n -$n; tail -n -$((n-1)); }<file >"$tmpfile" \
&& mv -- "$tmpfile" file
``` | `sed` cannot calculate nth row from bottom by itself, so we need to that before, e.g. using `awk`:
Delete 4th row from bottom:
```
delrow=$(awk -v n=4 'END { print NR-n+1 }' file)
sed -i "${delrow}d" file
``` |
512,947 | There are unknown number of lines in a file. How to delete nth line (when counted from the bottom) with one-liner command (you may use more than one if it is necessary) on Unix platform. | 2019/04/17 | [
"https://unix.stackexchange.com/questions/512947",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/347577/"
] | Pure `sed`:
* If *n* is 1:
```
sed '$ d'
```
This is simple: if it's the last line, delete the pattern space, so it's not printed.
* If *n* is greater than 1 (and available as `$n`):
```
sed "
: start
1,$((n-1)) { N; b start }
$ { t end; s/^//; D }
N
P
D
: end
"
```
Note `$((n-1))` is expanded by the shell before `sed` starts.
This fragment
```
: start
1,$((n-1)) { N; b start }
```
stores *n*-1 lines in the pattern space. If `sed` reaches the end of the input stream during this loop, the pattern space will be printed automatically (there is no n-th line from the end, no line will be deleted).
Suppose there is more input. Then, before we get to the last line, this fragment is iterated:
```
N # read the next line of input and append it to the pattern space
P # print the first line from the pattern space
D # delete the first line from the pattern space and start a new cycle
```
This way the pattern space is our buffer which makes the output several lines "late" according to the input. `N` from this fragment is able to read the last line of the input as well.
After the last line is read, this gets executed:
```
$ { t end; s/^//; D }
```
When this code is executed for the first time, `t` doesn't branch to `end` because there was no successful substitution before. Such no-op substitution `s/^//` is then performed and the first line from the pattern space is deleted (`D`) without being printed. This is exactly the line you want to be deleted. Since `D` starts a new cycle, the same line of code will eventually be executed again. This time `t` will branch to `end`.
When `sed` reaches the end of the script, the pattern space is printed automatically. This way all remaining lines get printed.
The command will generate the same output for `n=2` (valid) and `n=1` (invalid). I tried to find a single solution that works regardless of *n*. I failed, hence the special case when your *n* is 1. | You can combine `head` and `tail` to achieve this.
If the *nth* line from the bottom needs to be deleted
1. `head` reads from standard input and reports to standard output *total -n* lines from the top
2. `tail` reads and reports to standard output the bottom *n-1* lines from standard input.
3. Taken as a whole, the lines are thus reported to standard output in order, with the \*nth` line from the end being skipped
This solution depends on `head` leaving the file offset of the open file description just after the last reported line - I believe GNU `head` does indeed do this when standard input is redirected from a file
```
n=200; tmpfile=$(mktemp) && { head -n -$n; tail -n -$((n-1)); }<file >"$tmpfile" \
&& mv -- "$tmpfile" file
``` |
512,947 | There are unknown number of lines in a file. How to delete nth line (when counted from the bottom) with one-liner command (you may use more than one if it is necessary) on Unix platform. | 2019/04/17 | [
"https://unix.stackexchange.com/questions/512947",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/347577/"
] | To remove for example the 4th line from the bottom using `sed`:
```
tac input | sed '4d' | tac
```
To overwrite the input file:
```
tmpfile=$(mktemp)
tac input | sed '4d' | tac > "$tmpfile" && mv "$tmpfile" input
``` | This is tagged with `sed` and `awk` but the question doesn't mention these as being required for the solution. Here's a Perl filter which removes the 4th-from-last line and prints the result. The output can written to a tmp file and then used to replace the original.
```
perl -e '@L = <STDIN>; splice(@L,-4,1); print @L' ./lines.txt
``` |
512,947 | There are unknown number of lines in a file. How to delete nth line (when counted from the bottom) with one-liner command (you may use more than one if it is necessary) on Unix platform. | 2019/04/17 | [
"https://unix.stackexchange.com/questions/512947",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/347577/"
] | if `$n` hold number of line to delete
to delete a single line use
```
printf "\$-%d+1,\$-%d+1d\nwq\n" $n $n| ed -s file
```
to delete n last lines
```
printf "\$-%d,\$d\nwq\n" $n | ed -s file
```
where
* `\$%d,\$d` tell ed to delete n last lines (printf will insert n)
* `wq` write and quit
* `-s` in `ed -s` will keep ed silent.
* note that no provision is made to check you have enough line to delete.
sadly range **from end** can't be specified in `sed` ... | `sed` cannot calculate nth row from bottom by itself, so we need to that before, e.g. using `awk`:
Delete 4th row from bottom:
```
delrow=$(awk -v n=4 'END { print NR-n+1 }' file)
sed -i "${delrow}d" file
``` |
512,947 | There are unknown number of lines in a file. How to delete nth line (when counted from the bottom) with one-liner command (you may use more than one if it is necessary) on Unix platform. | 2019/04/17 | [
"https://unix.stackexchange.com/questions/512947",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/347577/"
] | Neither standard `sed` nor `awk` support editing in place.
For that, you better use `ed(1)` or `ex(1)`:
```
printf '$-%dd\nw\n' 1 | ed -s your_file
```
Or with here-doc
```
ed -s <<'EOT' your_file
$-1d
w
EOT
```
With advanced shells like `bash`, `zsh` or`ksh93` you can use the `$'...'` syntax and here-strings:
```
ed -s <<<$'$-1d\nw' your_file
```
Notice that the `$` address means the last line from the file; so the index 1 there is **0-based**; for the 1st line from the end replace the 1 with 0 (`$-0`), for the 3nd with 2 (`$-2`), etc.
Putting it in a function:
```
del_nth_line_from_end(){ printf '$-%dd\nw\n' "$(($2-1))" | ed -s "$1"; }
```
Instead of `ed -s` you can use `ex -s` or `vim -es` everywhere. | An one-line, in-place solution:
With `gawk`, this will delete the 42nd line from the bottom:
```
gawk -i inplace 'i==0 {if(FNR>t){t=FNR}else{i=1}} i==1 && FNR!=t-42 {print}' input input
```
The 42 can be replaced with any number. If 0 is used then the last line is deleted.
Notice that the `input` file is specified twice. This forces two iterations of the file with gawk. In the first iteration (`i==0`) the total number of lines (`t`) is established. In the second iteration, the nth line from the end is not output.
The file is modified in place by using the `-i` option. |
6,853,088 | I have a **need to find ALL files on my hard drive** (in the C: partition), regardless of permissions.
(Windows XP Pro, using C#)
In an earlier question, I was told:
>
> The "C:\System Volume Inforamtion" folder cannot be viewed because it is assigned only to the SYSTEM user. In order to see inside of it you need to take ownership of it. However, this is not recommended for security reasons. – Alex Mendez
>
>
>
I've worked with Windows for years, and this is the first time that I have heard about a SYSTEM user (which explains many frustrations I have had in the past). I had assumed that the "Administrator" was similar to the "root" user in UNIX, that has access to everything.
**In Windows, is there an ultimate user that owns EVERYTHING?**
If so, who is that user?
If so, how do I run my C# program as that user so I can see all the files?
If not, is there some other method? (Other programs do it.) | 2011/07/28 | [
"https://Stackoverflow.com/questions/6853088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10722/"
] | I've had this problem. It's because your browser now assumes /page/ is the root where it should start looking for css files etc, Simply put:
```
<base href="/">
```
In your
```
<head>.
```
Your browser will now strt looking for css files etc from the root of your website.
**edit: nvm, messed up formatting because posting from my iPod but I see you resolved the issue already :)** | To solve this issue, I had to put
in the head of my page. The javascript files I had to make absolute paths since different browsers handle the base tag differently. |
35,679,352 | I have a data table with the structure as given below:
```
structure(list(GVKEY1 = c(2721, 113609, 62634, NA, 62599, 15855,
15855, NA, NA, NA), GVKEY2 = c(NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_
), GVKEY3 = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), GVKEY4 = c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_), GVKEY5 = c(NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_
)), .Names = c("GVKEY1", "GVKEY2", "GVKEY3", "GVKEY4", "GVKEY5"
), class = c("data.table", "data.frame"), row.names = c(NA, -10L
))
```
I want to create a new column which is the maximum value of all the five columns. Notice that the data has a lot of NAs.
I wrote the following line
```
patent <- patent[, GVKEY := lapply(.SD, max, na.rm = TRUE), .SDcols = c('GVKEY1', 'GVKEY2', 'GVKEY3', 'GVKEY4', 'GVKEY5')]
```
I get the following output.
>
> Warning messages:
>
> 1: In `[.data.table`(patent, , `:=`(GVKEY, lapply(.SD, max, na.rm = TRUE)), :
>
> Supplied 5 items to be assigned to 3280338 items of column 'GVKEY' (recycled leaving remainder of 3 items).
>
> 2: In `[.data.table`(patent, , `:=`(GVKEY, lapply(.SD, max, na.rm = TRUE)), :
>
> Coerced 'list' RHS to 'double' to match the column's type. Either change the target column to 'list' first (by creating a new 'list' vector length 3280338 (nrows of entire table) and assign that; i.e. 'replace' column), or coerce RHS to 'double' (e.g. 1L, NA\_[real|integer]\_, as.\*, etc) to make your intent clear and for speed. Or, set the column type correctly up front when you create the table and stick to it, please.
>
>
>
Not sure what I am doing wrong. It would be great if someone can help me. | 2016/02/28 | [
"https://Stackoverflow.com/questions/35679352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243796/"
] | You can use the vectorized `pmax` function combined with `do.call` in order to avoid by row operation. This is uses the fact that `data.table` and `data.frame` are both lists (check out `is.list(patent)`), compared to `apply` which converts the `data.table` to a matrix. Also, as mentioned in the comments, the `:=` updates *by reference* so please don't use it combined with the `<-` operator
```
patent[, GVKEY := do.call(pmax, c(na.rm = TRUE, .SD))]
``` | A slight change for you, `apply` instead of `lapply`, and when using `:=`, you don't use the `<-` assignment operator\*.
```
patent[, GVKEY := apply(.SD, 1, max, na.rm = TRUE), .SDcols = c('GVKEY1', 'GVKEY2', 'GVKEY3', 'GVKEY4', 'GVKEY5')]
```
\*References:
* <https://stackoverflow.com/a/10226454/5977215>
* [data.table reference semantics](https://rawgit.com/wiki/Rdatatable/data.table/vignettes/datatable-reference-semantics.html) |
110,492 | I have a table `SUBSCRIBER` and in it the data is stored in a way that `bars` is a multi-valued column . Different values of bars are stored in different rows with the `ID` as following :
```none
ID BARS
1 , BAR1
1 , BAR2
1 , BAR3
2 , BAR4
2 , BAR3
3 , BAR3
4 , BAR1
4 , BAR4
```
OUTPUT for the data set should be the following:
```none
1,BAR1,
2,,BAR4
3,,,
4,BAR1,BAR4
```
So the query should be extracting 2 particular BAR values from the multi valued column(BARS) and gives the result for a report based on the conditions as following:
```none
ID,BAR1,BAR4 : WHEN BOTH BAR1 AND BAR4 EXIST
ID,BAR1,, : WHEN BAR1 EXISTS AND BAR4 IS NOT PRESENT
ID,,BAR4 : WHEN BAR4 EXISTS AND BAR1 IS NOT PRESENT
ID,,, : WHEN BOTH BAR1 AND BAR4 ARE NOT PRESENT
``` | 2015/08/09 | [
"https://dba.stackexchange.com/questions/110492",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/72427/"
] | If you don't need the extra commas, then:
```
SELECT CONCAT(id, ',',
GROUP_CONCAT(bars ORDER BY bars))
FROM subscriber
WHERE bars IN ('bar1', 'bar4')
GROUP BY id;
```
If you do need the commas, then search for "pivoting". | You can use `GROUP_CONCAT` and `CASE`:
**Query:**
```
SELECT
SUBSCRIBER.ID,
CASE
WHEN GROUP_CONCAT(CASE WHEN BARS='BAR1' OR BARS='BAR4' THEN BARS END) LIKE '%BAR1%' OR GROUP_CONCAT(CASE WHEN BARS='BAR1' OR BARS='BAR4' THEN BARS END) LIKE '%BAR4%' THEN GROUP_CONCAT(CASE WHEN BARS='BAR1' OR BARS='BAR4' THEN BARS END)
ELSE
GROUP_CONCAT(",") END AS BARS
FROM test.SUBSCRIBER
GROUP BY SUBSCRIBER.ID;
```
**Test:**
```
mysql> SELECT
-> SUBSCRIBER.ID,
-> CASE
-> WHEN GROUP_CONCAT(CASE WHEN BARS='BAR1' OR BARS='BAR4' THEN BARS END) LIKE '%BAR1%' OR GROUP_CONCAT(CASE WHEN BARS='BAR1' OR BARS='BAR4' THEN BARS END) LIKE '%BAR4%' THEN GROUP_CONCAT(CASE WHEN BARS='BAR1' OR BARS='BAR4' THEN BARS END)
-> ELSE
-> GROUP_CONCAT(",") END AS BARS
-> FROM test.SUBSCRIBER
-> GROUP BY SUBSCRIBER.ID;
+----+-----------+
| ID | BARS |
+----+-----------+
| 1 | BAR1 |
| 2 | BAR4 |
| 3 | , |
| 4 | BAR1,BAR4 |
+----+-----------+
4 rows in set (0.00 sec)
mysql>
``` |
37,366,964 | I'm trying to translate a simple button hover example to emca6 (I'm using babel) and keep failing. I guess that my bind is wrong somehow but I'm new to jscript and don't completely understand the:
`
```
constructor(props) {
super(props);`
```
I mean I get that it's like super in python, but why the weird syntax with props passed as parameter?
```
/* non emca6 */
import React from 'react'
var HoverButton = React.createClass({
getInitialState: function () {
return {hover: false};
},
mouseOver: function () {
this.setState({hover: true});
},
mouseOut: function () {
this.setState({hover: false});
},
render: function() {
var label = "foo";
if (this.state.hover) {
label = "bar";
}
return React.createElement(
"button",
{onMouseOver: this.mouseOver, onMouseOut: this.mouseOut},
label
);
}
});
React.render(React.createElement(HoverButton, null), document.body);
export default HoverButton;
/* emca6 */
import React from 'react';
class HoverButton extends React.Component {
constructor(props) {
super(props);
this.state = ({hover: false});
this.mouseOver = this.mouseOver.bind(this);
this.mouseOut = this.mouseOut.bind(this);
}
mouseOver(){
this.setState = ({hover: true});
}
mouseOut(){
this.setState = ({hover: false});
}
render() {
var label = "idle";
if (this.state.hover) {
label = "active";
}
return React.createElement(
"button",
{onMouseEnter: this.mouseOver, onMouseOut: this.mouseOut},
label,
);
}
}
export default HoverButton;
``` | 2016/05/21 | [
"https://Stackoverflow.com/questions/37366964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5797730/"
] | Josh,
Sorry your experience had been frustrating. I'm not at a computer at the moment but wanted to see if I could provide some help and will try to repro your scenario as soon as I can.
* All types that compose your function (either in a single or multiple .csx files) are compiled into a single assembly. So the error coming from EF is indeed puzzling.
* App.config is not supported in functions.
One approach you can try in the meantime (until we can find what is causing the issue you're running into), is to deploy your EF types and POCO as a separate assembly that you can then reference from your function. To do so, just copy that assembly into a bin folder under your function folder and add `#r "YourAssemblyName.dll"` to the top of your function file. Hopefully this will unblock you.
I'll post an update when I'm able to repro your scenario and have more information. | Use latest version of Entity Framework, I have tested using `version 6.1.3`. Then no need to specify any `DbConfiguartion`. You can safely remove the `DbConfiguration` code, just keep the `DbContext` this will not throw the exception and hopefully everything will work.
```
using System.Net;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
using (var db = new MyDbContext("...")) {
log.Info(db.Events.First().id.ToString());
}
}
#region POCOs
public class Event {
public long id {get;set;}
public string data {get;set;}
}
#endregion
public partial class MyDbContext : System.Data.Entity.DbContext {
public MyDbContext(string cs) : base(cs) { }
public DbSet<Event> Events {get;set;}
}
``` |
19,502,359 | I'd like to see the number of visitors on a specific page (for which I have URL).
I don't find in Analytics where to enter a URL in order to look for statistics for this specific page. | 2013/10/21 | [
"https://Stackoverflow.com/questions/19502359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422096/"
] | Go to Behavior > Site Content > All Pages and put your URI into the search box. | As Blexy already [answered](https://stackoverflow.com/a/19502866/1476885), go to "Behavior > Site Content > All Pages".
Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:
[](https://i.stack.imgur.com/1pSaO.png) |
19,502,359 | I'd like to see the number of visitors on a specific page (for which I have URL).
I don't find in Analytics where to enter a URL in order to look for statistics for this specific page. | 2013/10/21 | [
"https://Stackoverflow.com/questions/19502359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422096/"
] | Go to Behavior > Site Content > All Pages and put your URI into the search box. | If you want to know the number of ***visitors*** (as is titled in the question) and not the number of ***pageviews***, then you'll need to create a custom report.
Terminology
-----------
---
Google Analytics has changed the terminology they use within the reports. Now, visits is named "[sessions](https://support.google.com/analytics/answer/2731565?hl=en)" and unique visitors is named "[users](https://support.google.com/analytics/answer/2992042?hl=en)."
**User** - A unique person who has visited your website. Users may visit your website multiple times, and they will only be counted once.
**Session** - The number of different times that a visitor came to your site.
**Pageviews** - The total number of pages that a user has accessed.
Creating a Custom Report
------------------------
---
1. To create a custom report, click on the "Customization" item in the left navigation menu, and then click on "Custom Reports".
[](https://i.stack.imgur.com/teFbr.jpg)
2. The "Create Custom Report" page will open.
3. Enter a name for your report.
4. In the "Metric Groups" section, enter either "Users" or "Sessions" depending on what information you want to collect (see *Terminology*, above).
5. In the "Dimension Drilldowns" section, enter "Page".
6. Under "Filters" enter the individual page (exact) or group of pages (using regex) that you would like to see the data for.
[](https://i.stack.imgur.com/uXHBr.jpg)
7. Save the report and run it. |
1,029,463 | There is a set a set $S$ of numbers. i.e. $(s\_1, s\_2, s\_3, s\_4, s\_5, ..., s\_n)$. The average of the numbers in the set is $N$. How do I prove that at least one of the numbers in the set is greater than or equal to $N$?
I am thinking that a proof by contradiction is probably the easiest way.
I could do a proof by contradiction by supposing that no $s\_i$ in $S$ is greater than or equal to $N$. But then I am stuck on how to proceed to show that it is False and the original statement is true. | 2014/11/19 | [
"https://math.stackexchange.com/questions/1029463",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/180481/"
] | Suppose there are $n$ elements $s\_i \in S$ and the largest is $M$.
Then looking at the mean we have $\dfrac{\sum\_i s\_i} {n}=N$, and each $s\_i \le M$,
so $ nN=\sum\_i s\_i \le \sum\_i M=nM$ meaning $nN \le nM$ and so $$N \le M$$ i.e. the mean is less than or equal to the maximum.
No need to look for a contradiction. | Enumerate the elements of $S$ as $S=\{s\_1,\ldots,s\_K\}$. Suppose that it was true that $s\_i<N$ for all $i$. Then,
$$
\sum\_{i=1}^K s\_i<\sum\_{i=1}^K N=K\times N=K\frac{\sum\_{i=1}^K s\_i}{K}=\sum\_{i=1}^K s\_i.
$$
The leftmost term and rightmost term are the same so you have a contradiction. |
4,118,128 | Generally speaking, I’m wondering what the usual identities for Gaussian multiple integrals with a positive definite matrix become when the matrix is only positive semidefinite.
I could not find anything about this in the literature, any reference is welcome.
For instance, if ${\mathbf{A}}$ is positive definite, then we have
$\mathbb{E}{x\_i} = \frac{{\int\limits\_{\,{\mathbf{x}}} {{x\_i}{e^{ - \frac{1}{2}{{\mathbf{x}}^{\mathbf{T}}}{\mathbf{Ax}} + {{\mathbf{J}}^{\mathbf{T}}}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} }}{{\int\limits\_{\,{\mathbf{x}}} {{e^{ - \frac{1}{2}{{\mathbf{x}}^{\mathbf{T}}}{\mathbf{Ax}} + {{\mathbf{J}}^{\mathbf{T}}}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} }} = {\left( {{{\mathbf{A}}^{ - 1}}{\mathbf{J}}} \right)\_i}$
If ${\mathbf{A}}$ is only positive semidefinite, do we have
$\mathbb{E}{x\_i} = \frac{{\int\limits\_{\,{\mathbf{x}}} {{x\_i}{e^{ - \frac{1}{2}{{\mathbf{x}}^{\mathbf{T}}}{\mathbf{Ax}} + {{\mathbf{J}}^{\mathbf{T}}}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} }}{{\int\limits\_{\,{\mathbf{x}}} {{e^{ - \frac{1}{2}{{\mathbf{x}}^{\mathbf{T}}}{\mathbf{Ax}} + {{\mathbf{J}}^{\mathbf{T}}}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} }} = {\left( {{{\mathbf{A}}^ + }{\mathbf{J}}} \right)\_i}$
where ${{\mathbf{A}}^ + }$ is the Moore-Penrose pseudo-inverse of ${\mathbf{A}}$ ?
P.S. Of course, as pointed out by Gyu Eun below, both integrals become infinite with a psd matrix. But this does not imply that the ratio itself is infinite. The situation looks similar to Feynman path integrals in QM and QFT: we can talk only about ratios of path integrals since both integrals are infinite because they are infinite-dimensional. But the ratio is finite, otherwise path integrals would not exist. Hence my question is: do we have the same kind of infinity cancellation phenomenon with ratios of finite-dimensional Gaussian integrals with a psd matrix as with e.g. infinite-dimensional Gaussian path integrals with a non-singular operator?
The second formula with the pseudo-inverse holds with very high probability, that's an experimental fact. Indeed, when used in applications, it finally gives meaningful and useful results, everything works fine. It is possible that the formula holds only in special cases, including my own. But my own ${\mathbf{A}}$ and ${\mathbf{J}}$ are pretty random, so that the formula is likely to hold without conditions. But proving it under suitable conditions would be great too. | 2021/04/27 | [
"https://math.stackexchange.com/questions/4118128",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/318721/"
] | If $\mathbf{A}$ is only positive semidefinite, then the corresponding Gaussian integrals are not necessarily defined. In one dimension the only positive semidefinite matrix which is not positive definite is the zero matrix, and $x^t\mathbf{A}x = 0$ for all $x\in\mathbb{R}$, so
$$
\int\_{-\infty}^\infty e^{-x^t\mathbf{A}x}~dx = \int\_{-\infty}^\infty 1~dx = \infty.
$$
In higher dimensions the same holds for the same reasons. For instance the Gaussian integral with the matrix
$$
\mathbf{A} =
\begin{bmatrix}
1 & 0\\
0 & 0
\end{bmatrix}
$$
is infinite because you run into the same one-dimensional integral once you reduce to an iterated integral. | Here is a very partial answer.
**Theorem** : if ${\mathbf{A}}$ is positive semidefinite and ${\mathbf{J}} = {\mathbf{A}}{{\mathbf{A}}^ + }{\mathbf{J}}$, then $\mathbb{E}{\mathbf{x}} = {{\mathbf{A}}^ + }{\mathbf{J}}$ , provided we allow ourself to cancel out terms like $\frac{a}{a}$ even if $a$ is infinite.
**Proof** : recall one of the usual proofs of the identity
$\int\limits\_{{\mathbb{R}^n}} {{e^{ - \frac{1}{2}{{\mathbf{x}}^{\mathbf{T}}}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} = \frac{{{{\left( {2\pi } \right)}^{\frac{n}{2}}}}}{{\sqrt {\left| {\mathbf{A}} \right|} }}{e^{\frac{1}{2}{{\mathbf{J}}^T}{{\mathbf{A}}^{ - 1}}{\mathbf{J}}}}$
for a positive definite matrix ${\mathbf{A}}$ .
Substitute ${\mathbf{x}}$ by ${\mathbf{y}} = {\mathbf{x}} - {{\mathbf{A}}^{ - 1}}{\mathbf{J}}$
${{\text{d}}^n}{\mathbf{x}} = {{\text{d}}^n}{\mathbf{y}}$
$ - \frac{1}{2}{{\mathbf{x}}^T}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}} = - \frac{1}{2}{\left( {{\mathbf{y}} + {{\mathbf{A}}^{ - 1}}{\mathbf{J}}} \right)^T}{\mathbf{A}}\left( {{\mathbf{y}} + {{\mathbf{A}}^{ - 1}}{\mathbf{J}}} \right) + {{\mathbf{J}}^T}\left( {{\mathbf{y}} + {{\mathbf{A}}^{ - 1}}{\mathbf{J}}} \right) = \\
- \frac{1}{2}\left( {{{\mathbf{J}}^T}{{\mathbf{A}}^{ - 1}}{\mathbf{J}} + {{\mathbf{J}}^T}{\mathbf{y}} + {{\mathbf{y}}^T}{\mathbf{J}} + {{\mathbf{y}}^T}{\mathbf{Ay}}} \right) + {{\mathbf{J}}^T}{{\mathbf{A}}^{ - 1}}{\mathbf{J}} + {{\mathbf{J}}^T}{\mathbf{y}} = \\
\frac{1}{2}{{\mathbf{J}}^T}{{\mathbf{A}}^{ - 1}}{\mathbf{J}} - \frac{1}{2}{{\mathbf{y}}^T}{\mathbf{Ay}} \\ $
Therefore
$\int\limits\_{{\mathbb{R}^n}} {{e^{ - \frac{1}{2}{{\mathbf{x}}^T}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} = {e^{\frac{1}{2}{{\mathbf{J}}^T}{{\mathbf{A}}^{ - 1}}{\mathbf{J}}}}\int\limits\_{{\mathbb{R}^n}} {{e^{ - \frac{1}{2}{{\mathbf{y}}^T}{\mathbf{Ay}}}}{\text{d}}{\mathbf{y}}} = \frac{{{{\left( {2\pi } \right)}^{\frac{n}{2}}}}}{{\sqrt {\left| {\mathbf{A}} \right|} }}{e^{\frac{1}{2}{{\mathbf{J}}^T}{{\mathbf{A}}^{ - 1}}{\mathbf{J}}}}$
Then, by the Leibniz rule/Feynman trick
$ \frac{{\partial \int\limits\_{{\mathbb{R}^n}} {{e^{ - \frac{1}{2}{{\mathbf{x}}^T}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} }}{{\partial {{\mathbf{J}}\_i}}} = \int\limits\_{{\mathbb{R}^n}} {\frac{{\partial {e^{ - \frac{1}{2}{{\mathbf{x}}^T}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}}}}}}{{\partial {{\mathbf{J}}\_i}}}{\text{d}}{\mathbf{x}}} = \int\limits\_{{\mathbb{R}^n}} {{x\_i}{e^{ - \frac{1}{2}{{\mathbf{x}}^T}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} = \\
\frac{{{{\left( {2\pi } \right)}^{\frac{n}{2}}}}}{{\sqrt {\left| {\mathbf{A}} \right|} }}\frac{{\partial {e^{\frac{1}{2}{{\mathbf{J}}^T}{{\mathbf{A}}^{ - 1}}{\mathbf{J}}}}}}{{\partial {{\mathbf{J}}\_i}}} = \frac{1}{2}\int\limits\_{{\mathbb{R}^n}} {{e^{ - \frac{1}{2}{{\mathbf{x}}^T}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} \frac{\partial }{{\partial {{\mathbf{J}}\_i}}}{{\mathbf{J}}^T}{{\mathbf{A}}^{ - 1}}{\mathbf{J}} \\ $
Hence
$\mathbb{E}{x\_i} = \frac{{\int\limits\_{\,{\mathbf{x}}} {{x\_i}{e^{ - \frac{1}{2}{{\mathbf{x}}^T}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} }}{{\int\limits\_{\,{\mathbf{x}}} {{e^{ - \frac{1}{2}{{\mathbf{x}}^T}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} }} = \frac{1}{2}\frac{\partial }{{\partial {{\mathbf{J}}\_i}}}{{\mathbf{J}}^T}{{\mathbf{A}}^{ - 1}}{\mathbf{J}} = {\left( {{{\mathbf{A}}^{ - 1}}{\mathbf{J}}} \right)\_i}$
Now, for a positive semidefinite matrix ${\mathbf{A}}$, substitute ${\mathbf{x}}$ by ${\mathbf{y}} = {\mathbf{x}} - {{\mathbf{A}}^ + }{\mathbf{J}}$
$ - \frac{1}{2}{{\mathbf{x}}^T}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}} = - \frac{1}{2}{\left( {{\mathbf{y}} + {{\mathbf{A}}^ + }{\mathbf{J}}} \right)^T}{\mathbf{A}}\left( {{\mathbf{y}} + {{\mathbf{A}}^ + }{\mathbf{J}}} \right) + {{\mathbf{J}}^T}\left( {{\mathbf{y}} + {{\mathbf{A}}^ + }{\mathbf{J}}} \right) = \\
- \frac{1}{2}\left( {{{\mathbf{J}}^T}\underbrace {{{\mathbf{A}}^ + }{\mathbf{A}}{{\mathbf{A}}^ + }}\_{{{\mathbf{A}}^ + }}{\mathbf{J}} + {{\mathbf{J}}^T}{{\mathbf{A}}^ + }{\mathbf{Ay}} + {{\mathbf{y}}^T}{\mathbf{A}}{{\mathbf{A}}^ + }{\mathbf{J}} + {{\mathbf{y}}^T}{\mathbf{Ay}}} \right) + {{\mathbf{J}}^T}{{\mathbf{A}}^ + }{\mathbf{J}} + {{\mathbf{J}}^T}{\mathbf{y}} = \\
\frac{1}{2}{{\mathbf{J}}^T}{{\mathbf{A}}^ + }{\mathbf{J}} - \frac{1}{2}{{\mathbf{y}}^T}{\mathbf{Ay}} + {{\mathbf{J}}^T}\left( {{\mathbf{I}} - {{\mathbf{A}}^ + }{\mathbf{A}}} \right){\mathbf{y}} \\ $
The integral
$\int\limits\_{\,{\mathbf{x}}} {{e^{ - \frac{1}{2}{{\mathbf{y}}^T}{\mathbf{Ay}}}}{\text{d}}{\mathbf{y}}} $
now is infinite. But it is not a big deal because it cancels out in the Leibniz rule/Feynman trick above (please tell me).
Therefore, the term ${{\mathbf{J}}^T}\left( {{\mathbf{I}} - {{\mathbf{A}}^ + }{\mathbf{A}}} \right){\mathbf{y}}$ , where ${\mathbf{I}} - {{\mathbf{A}}^ + }{\mathbf{A}}$ is the orthogonal projector on $\ker {\mathbf{A}}$, is the main obstruction against the generalized formula.
So, if ${{\mathbf{J}}^T}\left( {{\mathbf{I}} - {{\mathbf{A}}^ + }{\mathbf{A}}} \right) = 0 \Leftrightarrow {\mathbf{J}} = {\mathbf{A}}{{\mathbf{A}}^ + }{\mathbf{J}}$ then
$\int\limits\_{{\mathbb{R}^n}} {{e^{ - \frac{1}{2}{{\mathbf{x}}^T}{\mathbf{Ax}} + {{\mathbf{J}}^T}{\mathbf{x}}}}{\text{d}}{\mathbf{x}}} \propto {e^{\frac{1}{2}{{\mathbf{J}}^T}{{\mathbf{A}}^ + }{\mathbf{J}}}}$
and the generalized formula
$\mathbb{E}{\mathbf{x}} = {{\mathbf{A}}^ + }{\mathbf{J}}$
follows by the Leibniz rule/Feynman trick.
Perhaps this condition is fulfilled with my own ${\mathbf{A}}$ and ${\mathbf{J}}$, I need to check. |
25,062,844 | I have a stream that watch output of multi file in a directory, process data and put it to HDFS. Here is my stream creat command:
```
stream create --name fileHdfs --definition "file --dir=/var/log/supervisor/ --pattern=tracker.out-*.log --outputType=text/plain | logHdfsTransformer | hdfs --fsUri=hdfs://192.168.1.115:8020 --directory=/data/log/appsync --fileName=log --partitionPath=path(dateFormat('yyyy/MM/dd'))" --deploy
```
Problem is source:file module send all data read from file to log processing module instead of one line each turn, becase of that, payload string have millions of char, i can't process it. Ex:
```
--- PAYLOAD LENGTH---- 9511284
```
Please tell me how to read line by line when use source:file module, thanks !!! | 2014/07/31 | [
"https://Stackoverflow.com/questions/25062844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3172277/"
] | It's not currently supported, but it would be easy to write a custom `source` using a Spring Integration `inbound-channel-adapter` to invoke a POJO that reads a line at a time.
Please open a [new feature JIRA issue](https://jira.spring.io/browse/XD).
You could also do it with a `job` instead of a `stream` in XD. | Spring Integration has a FileSplitter that splits a text file into lines. You can use this to create a custom processor module, let's call it file-split:
1. Create file-split.xml file with the following content:
```
<?xml version="1.0" encoding="UTF-8"?>
beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<int:splitter input-channel="input" output-channel="output">
<bean class="org.springframework.integration.file.splitter.FileSplitter">
<constructor-arg value="false"/>
</bean>
</int:splitter>
<int:channel id="output"/>
</beans>
```
2. Copy the file to ${XD\_HOME}/xd/modules/processor/file-split/config/ (create the path if needed)
3. Sample usage:
```
stream create --name splitFile --definition "file --dir=/data --ref=true | file-split | log" --deploy
```
You can further customize the module to take more options if needed. |
25,062,844 | I have a stream that watch output of multi file in a directory, process data and put it to HDFS. Here is my stream creat command:
```
stream create --name fileHdfs --definition "file --dir=/var/log/supervisor/ --pattern=tracker.out-*.log --outputType=text/plain | logHdfsTransformer | hdfs --fsUri=hdfs://192.168.1.115:8020 --directory=/data/log/appsync --fileName=log --partitionPath=path(dateFormat('yyyy/MM/dd'))" --deploy
```
Problem is source:file module send all data read from file to log processing module instead of one line each turn, becase of that, payload string have millions of char, i can't process it. Ex:
```
--- PAYLOAD LENGTH---- 9511284
```
Please tell me how to read line by line when use source:file module, thanks !!! | 2014/07/31 | [
"https://Stackoverflow.com/questions/25062844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3172277/"
] | It's not currently supported, but it would be easy to write a custom `source` using a Spring Integration `inbound-channel-adapter` to invoke a POJO that reads a line at a time.
Please open a [new feature JIRA issue](https://jira.spring.io/browse/XD).
You could also do it with a `job` instead of a `stream` in XD. | you can try using the **--mode=lines** option while deploying the stream.
Please check below documentation reference : <http://docs.spring.io/spring-xd/docs/current/reference/html/#file>
Hope this helps!
Cheers,
Pratik |
25,062,844 | I have a stream that watch output of multi file in a directory, process data and put it to HDFS. Here is my stream creat command:
```
stream create --name fileHdfs --definition "file --dir=/var/log/supervisor/ --pattern=tracker.out-*.log --outputType=text/plain | logHdfsTransformer | hdfs --fsUri=hdfs://192.168.1.115:8020 --directory=/data/log/appsync --fileName=log --partitionPath=path(dateFormat('yyyy/MM/dd'))" --deploy
```
Problem is source:file module send all data read from file to log processing module instead of one line each turn, becase of that, payload string have millions of char, i can't process it. Ex:
```
--- PAYLOAD LENGTH---- 9511284
```
Please tell me how to read line by line when use source:file module, thanks !!! | 2014/07/31 | [
"https://Stackoverflow.com/questions/25062844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3172277/"
] | I know that this may be late, but for any googlers out there looking for the solution:
Even though there is no module or option that does it automatically, it's as simple as adding a splitter that separates the incoming message into multiple outgoing messages.
Please note that you have to decide between using \n and \r\n. Check your files to see what they're using.
Example:
```
stream create --name filetest --definition "file --outputType=text/plain --dir=/tmp/examplefiles/| splitter --expression=payload.split('\\n') | log" --deploy
```
Cheers! | Spring Integration has a FileSplitter that splits a text file into lines. You can use this to create a custom processor module, let's call it file-split:
1. Create file-split.xml file with the following content:
```
<?xml version="1.0" encoding="UTF-8"?>
beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<int:splitter input-channel="input" output-channel="output">
<bean class="org.springframework.integration.file.splitter.FileSplitter">
<constructor-arg value="false"/>
</bean>
</int:splitter>
<int:channel id="output"/>
</beans>
```
2. Copy the file to ${XD\_HOME}/xd/modules/processor/file-split/config/ (create the path if needed)
3. Sample usage:
```
stream create --name splitFile --definition "file --dir=/data --ref=true | file-split | log" --deploy
```
You can further customize the module to take more options if needed. |
25,062,844 | I have a stream that watch output of multi file in a directory, process data and put it to HDFS. Here is my stream creat command:
```
stream create --name fileHdfs --definition "file --dir=/var/log/supervisor/ --pattern=tracker.out-*.log --outputType=text/plain | logHdfsTransformer | hdfs --fsUri=hdfs://192.168.1.115:8020 --directory=/data/log/appsync --fileName=log --partitionPath=path(dateFormat('yyyy/MM/dd'))" --deploy
```
Problem is source:file module send all data read from file to log processing module instead of one line each turn, becase of that, payload string have millions of char, i can't process it. Ex:
```
--- PAYLOAD LENGTH---- 9511284
```
Please tell me how to read line by line when use source:file module, thanks !!! | 2014/07/31 | [
"https://Stackoverflow.com/questions/25062844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3172277/"
] | I know that this may be late, but for any googlers out there looking for the solution:
Even though there is no module or option that does it automatically, it's as simple as adding a splitter that separates the incoming message into multiple outgoing messages.
Please note that you have to decide between using \n and \r\n. Check your files to see what they're using.
Example:
```
stream create --name filetest --definition "file --outputType=text/plain --dir=/tmp/examplefiles/| splitter --expression=payload.split('\\n') | log" --deploy
```
Cheers! | you can try using the **--mode=lines** option while deploying the stream.
Please check below documentation reference : <http://docs.spring.io/spring-xd/docs/current/reference/html/#file>
Hope this helps!
Cheers,
Pratik |
25,062,844 | I have a stream that watch output of multi file in a directory, process data and put it to HDFS. Here is my stream creat command:
```
stream create --name fileHdfs --definition "file --dir=/var/log/supervisor/ --pattern=tracker.out-*.log --outputType=text/plain | logHdfsTransformer | hdfs --fsUri=hdfs://192.168.1.115:8020 --directory=/data/log/appsync --fileName=log --partitionPath=path(dateFormat('yyyy/MM/dd'))" --deploy
```
Problem is source:file module send all data read from file to log processing module instead of one line each turn, becase of that, payload string have millions of char, i can't process it. Ex:
```
--- PAYLOAD LENGTH---- 9511284
```
Please tell me how to read line by line when use source:file module, thanks !!! | 2014/07/31 | [
"https://Stackoverflow.com/questions/25062844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3172277/"
] | Spring Integration has a FileSplitter that splits a text file into lines. You can use this to create a custom processor module, let's call it file-split:
1. Create file-split.xml file with the following content:
```
<?xml version="1.0" encoding="UTF-8"?>
beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd">
<int:splitter input-channel="input" output-channel="output">
<bean class="org.springframework.integration.file.splitter.FileSplitter">
<constructor-arg value="false"/>
</bean>
</int:splitter>
<int:channel id="output"/>
</beans>
```
2. Copy the file to ${XD\_HOME}/xd/modules/processor/file-split/config/ (create the path if needed)
3. Sample usage:
```
stream create --name splitFile --definition "file --dir=/data --ref=true | file-split | log" --deploy
```
You can further customize the module to take more options if needed. | you can try using the **--mode=lines** option while deploying the stream.
Please check below documentation reference : <http://docs.spring.io/spring-xd/docs/current/reference/html/#file>
Hope this helps!
Cheers,
Pratik |
26,195,949 | A CSS animation is continuously playing behind an image. When the image is not loaded it will display, but when loaded the image will overlap the animation. I'm using z-index to achieve this, but it's not working.
The image should hide loading animation with the z-index property.
**Note:** I can't use any javascript solution to hide the loading animation and show it after image load.
CSS / HTML / Demo
```css
.leftprev {
overflow:auto;
position:absolute;
height:99%;
width:85%;
}
.loadingslide {
z-index: 50; /* Loading div's z-index */
}
.spinner.big {
display: block;
height: 40px;
}
.spinner {
bottom: 0;
display: none;
font-size: 10px;
height: 30px;
left: 0;
margin: auto;
position: absolute;
right: 0;
text-align: center;
top: 0;
width: 60px;
}
.spinner.big > div {
width: 6px;
}
.spinner > div {
animation: 1.2s ease-in-out 0s normal none infinite stretchdelay;
background-color: #333;
display: inline-block;
height: 100%;
width: 6px;
}
a {
color: #470a09;
text-decoration: none;
}
.slideshow .slidebro .leftprev #slideshowpic {
display: block;
margin: 0 auto;
width: auto;
z-index: 100; /* image's z-index */
}
```
```html
<div class="leftprev">
<div class="loadingslide"> <!-- Loading Animation div (should be running in background of the image) -->
<div id="tracking" class="spinner big">
<div class="rect1"></div>
<div class="rect2"></div>
<div class="rect3"></div>
<div class="rect4"></div>
<div class="rect5"></div>
</div>
</div>
<a id="targetslide" target="_blank" title="Click to view fit to screen" href="">
<img src="http://www.placehold.it/500" alt="" id="slideshowpic" /> <!-- The image (should mask the loading animation div) -->
</a>
</div>
``` | 2014/10/04 | [
"https://Stackoverflow.com/questions/26195949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3710243/"
] | You have to add **position** to the element that you want to apply **z-index**.
From CSS-tricks:
>
> The z-index property in CSS controls the vertical stacking order of
> elements that overlap. As in, which one appears as if it is physically
> closer to you. z-index only effects elements that have a position
> value other than static (the default).
>
>
>
<http://css-tricks.com/almanac/properties/z/z-index/> | To position the loading animation correctly:
* Place the loading div inside the container
* Set the container as `position: relative` so that the loading div is positioned in relation to it
To hide the loading animation when the image is loaded:
* The loading div is given `z-index: 1`
* The image is given `position: relative` so that it can have a z-index property
* The image is given `z-index: 2` and will overlap
In this example the image is half the width of the container and you can see how it overlaps the loading div.
CSS / HTML / Demo
```css
html, body {
height: 100%;
margin: 0;
}
.content {
height: 500px;
width: 500px;
background: #e91e63;
margin: 0 auto;
position: relative;
}
.content img {
z-index: 2;
position: relative;
width: 250px;
height: 500px;
}
.loading {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100px;
height: 1em;
padding: 20px;
background: #FF0;
text-align: center;
font-weight: bold;
z-index: 1;
}
```
```html
<div class="content">
<div class="loading">I am loading</div>
<img src="http://www.placehold.it/250X500" />
</div>
``` |
58,984,073 | i need a help when i execute the following MYSQL command in Navicat i get
```
mysql> SELECT Password FROM workers;
+----------+
| Password |
+----------+
| A |
| B |
| B |
| B |
| B |
```
when i fire it in java i get
```
java.sql.SQLException: Column Index out of range, 3 > 2.
```
Code :-
```
try {
ArrayList<String> A = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");
int c =1;
while(rs.next())
{
A.add(rs.getString(c));
c++;
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
``` | 2019/11/21 | [
"https://Stackoverflow.com/questions/58984073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11752429/"
] | You need to add the version to. Like this:
```
composer require symfony/web-server-bundle --dev ^4.4.2
```
You can check for the latest version here:
<https://packagist.org/packages/symfony/web-server-bundle> | Install Symfony <https://symfony.com/download>
and use :
* `symfony server:start`
* or `symfony server:start -d` |
58,984,073 | i need a help when i execute the following MYSQL command in Navicat i get
```
mysql> SELECT Password FROM workers;
+----------+
| Password |
+----------+
| A |
| B |
| B |
| B |
| B |
```
when i fire it in java i get
```
java.sql.SQLException: Column Index out of range, 3 > 2.
```
Code :-
```
try {
ArrayList<String> A = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");
int c =1;
while(rs.next())
{
A.add(rs.getString(c));
c++;
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
``` | 2019/11/21 | [
"https://Stackoverflow.com/questions/58984073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11752429/"
] | Install Symfony <https://symfony.com/download>
and use :
* `symfony server:start`
* or `symfony server:start -d` | The development web-server is included in the symfony client.
Install the symfony cli : <https://symfony.com/download>
Then, you can start the dev web server
```sh
symfony server:start
``` |
58,984,073 | i need a help when i execute the following MYSQL command in Navicat i get
```
mysql> SELECT Password FROM workers;
+----------+
| Password |
+----------+
| A |
| B |
| B |
| B |
| B |
```
when i fire it in java i get
```
java.sql.SQLException: Column Index out of range, 3 > 2.
```
Code :-
```
try {
ArrayList<String> A = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");
int c =1;
while(rs.next())
{
A.add(rs.getString(c));
c++;
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
``` | 2019/11/21 | [
"https://Stackoverflow.com/questions/58984073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11752429/"
] | Install Symfony <https://symfony.com/download>
and use :
* `symfony server:start`
* or `symfony server:start -d` | If you are in development, you can simply use the inbuilt PHP server.
Change directory to your Symfony project directory and run the following
`php -S localhost:8001 -t public` |
58,984,073 | i need a help when i execute the following MYSQL command in Navicat i get
```
mysql> SELECT Password FROM workers;
+----------+
| Password |
+----------+
| A |
| B |
| B |
| B |
| B |
```
when i fire it in java i get
```
java.sql.SQLException: Column Index out of range, 3 > 2.
```
Code :-
```
try {
ArrayList<String> A = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");
int c =1;
while(rs.next())
{
A.add(rs.getString(c));
c++;
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
``` | 2019/11/21 | [
"https://Stackoverflow.com/questions/58984073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11752429/"
] | You need to add the version to. Like this:
```
composer require symfony/web-server-bundle --dev ^4.4.2
```
You can check for the latest version here:
<https://packagist.org/packages/symfony/web-server-bundle> | The development web-server is included in the symfony client.
Install the symfony cli : <https://symfony.com/download>
Then, you can start the dev web server
```sh
symfony server:start
``` |
58,984,073 | i need a help when i execute the following MYSQL command in Navicat i get
```
mysql> SELECT Password FROM workers;
+----------+
| Password |
+----------+
| A |
| B |
| B |
| B |
| B |
```
when i fire it in java i get
```
java.sql.SQLException: Column Index out of range, 3 > 2.
```
Code :-
```
try {
ArrayList<String> A = new ArrayList<String>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "123456");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Password FROM workers");
int c =1;
while(rs.next())
{
A.add(rs.getString(c));
c++;
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
``` | 2019/11/21 | [
"https://Stackoverflow.com/questions/58984073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11752429/"
] | You need to add the version to. Like this:
```
composer require symfony/web-server-bundle --dev ^4.4.2
```
You can check for the latest version here:
<https://packagist.org/packages/symfony/web-server-bundle> | If you are in development, you can simply use the inbuilt PHP server.
Change directory to your Symfony project directory and run the following
`php -S localhost:8001 -t public` |
40,616,704 | Can we use pair as an argument for another pair in C++.
Here is a test program to do that.
```
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<int**,<std::pair<int,int> > > i(p,m);
std::cout<<i[t];
return 0;
}
```
This is the error, I am getting.
```
Test.cpp: In function ‘int main()’:
Test.cpp:12:45: error: template argument 2 is invalid
std::pair<int**,<std::pair<int,int>>> i(p,m);
^
```
If I changed the format of declaration and wrote the program in the following way,
```
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<
int**,
<
std::pair<
int,
int
>
>
> i(p,m);
std::cout<<i[t];
return 0;
}
```
There is an additional error.
```
Test.cpp: In function ‘int main()’:
Test.cpp:20:7: error: template argument 2 is invalid
> i(p,m);
^
Test.cpp:20:14: error: expression list treated as compound expression in initializer [-fpermissive]
> i(p,m);
```
What might be the issue and how to solve it?
---
On a side note, I did a program and compiled it in an very old Dev-c++ compiler on a windows 7 machine which used a code similar to the above and it ran perfectly fine. It was a lab program in my college which had only that compiler.
The above code, I ran on both windows 7 and Ubuntu 16.04 using GNU g++ 5.4.0
Ideone: [Link to the actual program for reference](http://ideone.com/YA2W69)
You might also have a look at the actual error, I faced in the above link. | 2016/11/15 | [
"https://Stackoverflow.com/questions/40616704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4669984/"
] | You can use [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
```
var output = input.map(function(item) {
return item.messageid;
});
```
This will create an array that will look like `[582b4350af7cb8f21e4b7b43,582b4350af7cb8f21e4b7xb43]` | You could map the property `messageid`.
```js
var objectArray = [{ messageid: '582b4350af7cb8f21e4b7b43', _id: '582b4c79105387dd21e08004' }, { messageid: '582b4350af7cb8f21e4b7xb43', _id: '582b4c79105387dd21e08s004' }],
newArray = objectArray.map(function (o) {
return o.messageid;
});
console.log(newArray);
``` |
40,616,704 | Can we use pair as an argument for another pair in C++.
Here is a test program to do that.
```
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<int**,<std::pair<int,int> > > i(p,m);
std::cout<<i[t];
return 0;
}
```
This is the error, I am getting.
```
Test.cpp: In function ‘int main()’:
Test.cpp:12:45: error: template argument 2 is invalid
std::pair<int**,<std::pair<int,int>>> i(p,m);
^
```
If I changed the format of declaration and wrote the program in the following way,
```
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<
int**,
<
std::pair<
int,
int
>
>
> i(p,m);
std::cout<<i[t];
return 0;
}
```
There is an additional error.
```
Test.cpp: In function ‘int main()’:
Test.cpp:20:7: error: template argument 2 is invalid
> i(p,m);
^
Test.cpp:20:14: error: expression list treated as compound expression in initializer [-fpermissive]
> i(p,m);
```
What might be the issue and how to solve it?
---
On a side note, I did a program and compiled it in an very old Dev-c++ compiler on a windows 7 machine which used a code similar to the above and it ran perfectly fine. It was a lab program in my college which had only that compiler.
The above code, I ran on both windows 7 and Ubuntu 16.04 using GNU g++ 5.4.0
Ideone: [Link to the actual program for reference](http://ideone.com/YA2W69)
You might also have a look at the actual error, I faced in the above link. | 2016/11/15 | [
"https://Stackoverflow.com/questions/40616704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4669984/"
] | You can use [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
```
var output = input.map(function(item) {
return item.messageid;
});
```
This will create an array that will look like `[582b4350af7cb8f21e4b7b43,582b4350af7cb8f21e4b7xb43]` | Use `forEach` to loop through the array
```
var orArray = [{
messageid: '582b4350af7cb8f21e4b7b43',
_id: '582b4c79105387dd21e08004'
}, {
messageid: '582b4350af7cb8f21e4b7xb43',
_id: '582b4c79105387dd21e08s004'
}
];
var newArr = [];
orArray.forEach(function(item) {
newArr.push(item.messageid)
});
console.log(newArr)
```
[**DEMO**](https://jsfiddle.net/f885rah6/) |
40,616,704 | Can we use pair as an argument for another pair in C++.
Here is a test program to do that.
```
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<int**,<std::pair<int,int> > > i(p,m);
std::cout<<i[t];
return 0;
}
```
This is the error, I am getting.
```
Test.cpp: In function ‘int main()’:
Test.cpp:12:45: error: template argument 2 is invalid
std::pair<int**,<std::pair<int,int>>> i(p,m);
^
```
If I changed the format of declaration and wrote the program in the following way,
```
#include <iostream>
#include <utility>
int main()
{
std::pair<int,int> m;
m=std::make_pair(1,3);
int r = 3;
int *q = &r;
int **p =&q;
int **t = p;
std::pair<
int**,
<
std::pair<
int,
int
>
>
> i(p,m);
std::cout<<i[t];
return 0;
}
```
There is an additional error.
```
Test.cpp: In function ‘int main()’:
Test.cpp:20:7: error: template argument 2 is invalid
> i(p,m);
^
Test.cpp:20:14: error: expression list treated as compound expression in initializer [-fpermissive]
> i(p,m);
```
What might be the issue and how to solve it?
---
On a side note, I did a program and compiled it in an very old Dev-c++ compiler on a windows 7 machine which used a code similar to the above and it ran perfectly fine. It was a lab program in my college which had only that compiler.
The above code, I ran on both windows 7 and Ubuntu 16.04 using GNU g++ 5.4.0
Ideone: [Link to the actual program for reference](http://ideone.com/YA2W69)
You might also have a look at the actual error, I faced in the above link. | 2016/11/15 | [
"https://Stackoverflow.com/questions/40616704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4669984/"
] | You could map the property `messageid`.
```js
var objectArray = [{ messageid: '582b4350af7cb8f21e4b7b43', _id: '582b4c79105387dd21e08004' }, { messageid: '582b4350af7cb8f21e4b7xb43', _id: '582b4c79105387dd21e08s004' }],
newArray = objectArray.map(function (o) {
return o.messageid;
});
console.log(newArray);
``` | Use `forEach` to loop through the array
```
var orArray = [{
messageid: '582b4350af7cb8f21e4b7b43',
_id: '582b4c79105387dd21e08004'
}, {
messageid: '582b4350af7cb8f21e4b7xb43',
_id: '582b4c79105387dd21e08s004'
}
];
var newArr = [];
orArray.forEach(function(item) {
newArr.push(item.messageid)
});
console.log(newArr)
```
[**DEMO**](https://jsfiddle.net/f885rah6/) |
336,920 | I built this computer back in June and this has been an issue ever since I first built it. What happens is that my computer will POST just fine and then go to the black screen where it states "Loading Windows". Usually it sits there for a second and then it the pulsing Windows logo will appear, and after a few seconds, it brings me to the Windows login screen. However, about once a week at least, it will just sit there with a black screen and the "Loading Windows" text, but the logo will never appear. The hard drive indicator remains off and I don't hear any hard drive activity, which tells me that it's stuck. There's no error messages, but it never loads Windows. What I do here is just push the reset button and it will reboot. The "repair Windows" option never helps and is useless, so I just say "Load Windows normally", and it will load Windows fine 100% of the time, without fail. However, something must be wrong.
The computer started out with one 500GB hybrid SSD, and exhibited this behavior. I put in another and put it on RAID0 and it hasn't changed. It has 4 x 4GB of RAM, and a friend told me that perhaps the RAM is underpowered. So, every time this happens, I go into the BIOS and up the DRAM voltage one tick. I've been doing this for weeks and it hasn't done anything (first time I did it, I didn't see the issue for over a week, then it started happening again). I'm over 1.55V (I think 1.553V, if memory serves) but it's not even overclocked (they're 1333MHz) so I'm getting anxious that this won't solve the issue. I did both a full run of Memtest86+ and chkdsk and they both reported no errors. I've run several benchmarking suites (such as Heaven DX11 Benchmark, Crystal DiskMark, Furmark, 3DMark 11, and others, as well as playing games on high end settings and it never has given me any issues there, so it's not a hardware instability once Windows loads. I've even on one occasion had the computer up for a total of about 2 weeks straight and it didn't show any sign of glitching or malfunction.
This is the first computer I've built, and I am inexperienced with overclocking and dealing with power issues or other corner cases. Is my friend right that it's underpowered RAM? Or is there something else that could be afoot?
I have my computer specs below:
```
Computer: MSI MS-7640
CPU: AMD Phenom II X4 955 Black Edition (Deneb, RB-C3) @ 3200 MHz (16.00x200.0)
Motherboard: MSI 890FXA-GD65 (MS-7640)
Chipset: ATI RD890 + SB810/SB850
Memory: 16384 MBytes @ 666 MHz, 9.0-9-9-24
- 4096 MB PC10600 DDR3 SDRAM - Patriot Memory (PDP Systems) PSD34G13332
- 4096 MB PC10600 DDR3 SDRAM - Patriot Memory (PDP Systems) PSD34G13332
- 4096 MB PC10600 DDR3 SDRAM - Patriot Memory (PDP Systems) PSD34G13332
- 4096 MB PC10600 DDR3 SDRAM - Patriot Memory (PDP Systems) PSD34G13332
Graphics: MSI R6970 (MS-V237)
ATI RADEON HD 6970 (CAYMAN XT), 2048 MB GDDR5 SDRAM
Graphics: MSI R6970 (MS-V237)
ATI RADEON HD 6970 (CAYMAN XT), 0 MB
Drive: AMD 2+0 Stripe/RAID0, Disk drive
Drive: ATAPI iHBS212 2, BD-RE
Drive: ATAPI iHBS212 2, BD-RE
Drive: AMD RAID Console, Processor
Sound: ATI SB800/Hudson-1 - High Definition Audio Controller
Sound: ATI Cayman/Antilles - High Definition Audio Controller
Sound: ATI Cayman/Antilles - High Definition Audio Controller
Network: RealTek Semiconductor RTL8168/8111 PCI-E Gigabit Ethernet NIC
Network: Realtek PCIe GBE Family Controller
OS: Microsoft Windows 7 Professional (x64) Build 7601
```
As a note, I've been recommended in chat to enable boot logging and see if anything shows up. I've done that just now, and will post the results whenever this occurs again, if there's anything of interest.
**EDIT**
I've enabled verbose booting and boot logging, but so far have not seen the issue reappear within the past week or so. I will update when I do see it happen.
**EDIT #2 (11/25/2011)**
Since I've enabled the boot logging (and reverted back to stock DRAM voltages), I haven't seen the issue reappear. I feel it's worth noting that I also, during this time, installed Windows 8 Developer Preview as a second OS, and have it dual-boot using the Windows 7 boot loader. Would this extra delay (10 seconds, currently) before it attempts to load Windows 7 have any effect on its success in booting Windows? Does it make sense that it might have been getting to the "Loading Windows" step too quickly? Could this be an instability in the power supply?
By the way, the power supply is a [Thermaltake TPX-775M Toughpower XT 775W](http://www.tigerdirect.com/applications/SearchTools/item-details.asp?EdpNo=6624663).
**EDIT #3 (9/30/2011)**
I removed the Windows 8 Dev Preview partition so that it went back to the normal boot process. This morning, it hung at boot again. Since I was using verbose boot, it hung at the black screen before it started loading drivers. After I reset the computer and got into Windows, checking ntbtlog.txt didn't show anything logged for the failed boot session. So it apparently just sits there before it even starts loading drivers.
I think after work today I'm going to start the process of checking each stick of RAM. I've put that off long enough.
**EDIT #4 (10/21/2011)**
A little while ago, I found that one of my external USB hard drives had several bad sectors. Eventually it was unreadable. Since Windows likes to scan USB drives on startup, could this have caused the issue? I haven't seen the hang for quite some time now, after I ran `chkdsk` on the drive (currently it remains powered off, as I was able to recover the data on it). This drive has been hooked up since I built the computer. Perhaps Windows was finding bad sectors and didn't know how to proceed, even though it's an external HDD? | 2011/09/18 | [
"https://superuser.com/questions/336920",
"https://superuser.com",
"https://superuser.com/users/33595/"
] | You may have already tried this but, as no one else has suggested it...
Disable **ALL** overclocking features and next update **ALL** the drivers you can - never use the versions that come on disk and take a look at the AMD website and your motherboard company.
As it is happening at such an early stage, I believe the most likely cause is a bad I/O driver, but, it could be anything.
and finally if this doesn't solve it, we have to go the old fashioned way and disconnecting everything you can in case it is some sort of conflict/issue with third party hardware. | First; if you're overclocking, you need to step back down a notch once you start having problems. If you are having problems at the default BIOS settings then you have a hardware problem.
Memtest although great, does not always report errors. Try testing by taking out one stick at a time. I've had to do this recently with a machine. It took me 4 months to figure out which stick it was (failure once every 2-4 weeks in my case). Once I replaced the defective chip I have had a solid machine since (about 6 months now...)
Note: chkdsk only checks the file system structure. It does not check the disk itself. Look to see if the manufactirer has a tool to test the disk. Typically they will provide a bootable ISO for this. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.