prompt
stringlengths 48
2.37k
| chosen
stringlengths 7
4.28k
| rejected
stringlengths 11
4.44k
|
---|---|---|
Question: Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution?
Answer: | UPDATE: There is extensive analysis and commentary on this issue here:
<http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/>
---
This is an extremely frequently reported issue; usually it is reported as a compiler bug, but in fact the compiler is doing the right thing according to the specification. Anonymous functions close over *variables*, not *values*, and there is only a single foreach loop variable. Therefore each lambda closes over the same variable, and therefore gets the current value of that variable.
This is surprising to almost everyone, and leads to much confusion and many bug reports. We are *considering* changing the specification and implementation for a hypothetical future version of C# so that the loop variable is logically declared inside the looping construct, giving a "fresh" variable every time through the loop.
**This would be a breaking change**, but I suspect the number of people who depend on this strange behaviour is quite low. If you have opinions on this subject, feel free to add comments to the blog posts mentioned up the update above. Thanks! | ```
foreach(Item i on ItemCollection)
{
Something s = new Something(i);
s.EventX += (sender, eventArgs) => { ProcessItem(eventArgs.Item);};
SomethingCollection.Add(s);
}
```
would you not just pass 'i' in into your 'Something' Class and use it in EventX's event args |
Question: Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution?
Answer: | UPDATE: There is extensive analysis and commentary on this issue here:
<http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/>
---
This is an extremely frequently reported issue; usually it is reported as a compiler bug, but in fact the compiler is doing the right thing according to the specification. Anonymous functions close over *variables*, not *values*, and there is only a single foreach loop variable. Therefore each lambda closes over the same variable, and therefore gets the current value of that variable.
This is surprising to almost everyone, and leads to much confusion and many bug reports. We are *considering* changing the specification and implementation for a hypothetical future version of C# so that the loop variable is logically declared inside the looping construct, giving a "fresh" variable every time through the loop.
**This would be a breaking change**, but I suspect the number of people who depend on this strange behaviour is quite low. If you have opinions on this subject, feel free to add comments to the blog posts mentioned up the update above. Thanks! | If ItemCollection is a [(generic) List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) you can use its [ForEach](http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx)-method. It will give you a fresh scope per i:
```
ItemCollection.ForEach(
i =>
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
});
```
Or you can use any other suitable [Linq](http://msdn.microsoft.com/en-us/netframework/aa904594.aspx)-method - like [Select](http://msdn.microsoft.com/en-us/library/bb548891.aspx):
```
var somethings = ItemCollection.Select(
i =>
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
return s;
});
foreach(Something s in somethings)
SomethingCollection.Add(s);
``` |
Question: Let's take the function $f(x)=x^{-1}$. My question is this: Is the sum $$\frac{1}{x-a}+\frac{1}{x+a}$$ as $a\rightarrow 0$ near the point $x=0$ equal 0? And how would I proove this anytime I encounter this kind of limit? How would this work with derivatives or integrals?
Answer: | The quantity you seem to be asking about is $$\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}$$ "near" $x=0.$ Well, assuming that $x$ is not $0,$ then this is simply $$\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}=\frac1x+\frac1x=\frac2x$$ by continuity. Now, if $x=0,$ then we have $$\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}=\lim\_{a\to 0}-\frac{1}{a}+\frac{1}{a}=\lim\_{a\to 0}0=0.$$
This is a good example of why we can't always interchange limits, since $$\lim\_{a\to 0}\lim\_{x\to 0}\frac{1}{x-a}+\frac{1}{x+a}=0,$$ but $$\lim\_{x\to 0}\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}$$ does not exist. | Well, it depends what limit are you evaluating first.
First, $\lim\_{a\to 0}(\lim\_{x\to 0} (\frac{1}{x-a}+\frac{1}{x+a}))=\lim\_{a\to 0}0=0$, but, on the other hand, you have $\lim\_{x\to 0}(\lim\_{a\to 0} (\frac{1}{x-a}+\frac{1}{x+a}))=\lim\_{x\to 0}\frac{2}{x}$ and this limit does not exist. So, the order of taking these "iterated" limits in a two variable (or generally, $n$-variable) problems is important. |
Question: I am a 15-year-old female, and I am currently a high soprano. I can currently sing from a low C4 to a high F above the bar. Is there a way I could get higher and become a coloratura soprano or gain an octave?
Answer: | You already have a full soprano range: C4 to F6. Coloratura is a vocal quality, not a range. Coloratura voices generally have a light quality to them, as opposed to the more powerful voice of a dramatic soprano. Coloraturas specialize in highly decorative passages with lots of runs, trills, and other ornaments.
So coloratura is a skill to develop if you have a lighter-sounding voice. At 15 your vocal color may still be changing, but you'll have to wait and see.
---
Also of interest...
* [Lyrical Contralto vs Dramatic Mezzo-soprano](https://music.stackexchange.com/q/116076/70803)
* [Will my voice get any higher?](https://music.stackexchange.com/q/58355/70803) | You dont just simply add a octave. Most singers range is between an octave and maybe a 10th. Even then a 10th is extraordinary.
Singing around middle C is hard for soprano and very few ever get to the fabled nessum dorma high B.
Your range will gravitate between the E above middle C to the G a tenth above it. That is fine. You will have to become pretty great before any more is required.
Colatura as a style is not dependant on any particular range for the soprano at least. It is more to do with a style that is rich in ornamentation. This makes it very demanding to the singer and only the really great female singers ever excel at it.
Dame June Sutherland probably being the greatest singer of this type in 20th century. |
Question: Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
Answer: | Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.
In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:
* (primarily) security: since dapper doesn't have a concept of a context, it would be *really really* easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
* (secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be `null` in most cases) would have much impact
Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: `Debug.WriteLine` etc. | You should consider using SQL profiler located in the menu of *SQL Management Studio* ***→ Extras → SQL Server Profiler*** (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).
Then, start a new session.
You'll get something like this for example (you see all parameters and the complete SQL string):
```
exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = @appId AND (Blocked IS NULL OR Blocked = 0)
AND (Beta IS NULL OR Beta = 0 OR @includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(@langCode, '','')))',N'@appId nvarchar(4000),@includeBeta bit,@langCode nvarchar(4000)',@appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',@includeBeta=0,@langCode=N'de'
``` |
Question: Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
Answer: | I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget [MiniProfiler.Integrations](https://www.nuget.org/packages/MiniProfiler.Integrations/) I would like to share.
**Update V2**: it supports to work with other database servers, for MySQL it requires to have [MiniProfiler.Integrations.MySql](https://www.nuget.org/packages/MiniProfiler.Integrations.MySql/)
Below are steps to work with SQL Server:
1.Instantiate the connection
```
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
```
2.After all works done, write all commands to a file if you want
```
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
``` | You should consider using SQL profiler located in the menu of *SQL Management Studio* ***→ Extras → SQL Server Profiler*** (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).
Then, start a new session.
You'll get something like this for example (you see all parameters and the complete SQL string):
```
exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = @appId AND (Blocked IS NULL OR Blocked = 0)
AND (Beta IS NULL OR Beta = 0 OR @includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(@langCode, '','')))',N'@appId nvarchar(4000),@includeBeta bit,@langCode nvarchar(4000)',@appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',@includeBeta=0,@langCode=N'de'
``` |
Question: Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
Answer: | Try [Dapper.Logging](https://github.com/hryz/Dapper.Logging/tree/71f4f3de06b95f131e84171698e0d3ed7cb52f83).
-----------------------------------------------------------------------------------------------------------
You can get it from NuGet. The way it works is you pass your code that creates your actual database connection into a factory that creates wrapped connections. Whenever a wrapped connection is opened or closed or you run a query against it, it will be logged. You can configure the logging message templates and other settings like whether SQL parameters are saved. Elapsed time is also saved.
In my opinion, the only downside is that the documentation is sparse, but I think that's just because it's a new project (as of this writing). I had to dig through the repo for a bit to understand it and to get it configured to my liking, but now it's working great.
From the documentation:
>
> The tool consists of simple decorators for the `DbConnection` and
> `DbCommand` which track the execution time and write messages to the
> `ILogger<T>`. The `ILogger<T>` can be handled by any logging framework
> (e.g. Serilog). The result is similar to the default EF Core logging
> behavior.
>
>
> The lib declares a helper method for registering the
> `IDbConnectionFactory` in the IoC container. The connection factory is
> SQL Provider agnostic. That's why you have to specify the real factory
> method:
>
>
>
> ```
> services.AddDbConnectionFactory(prv => new SqlConnection(conStr));
>
> ```
>
> After registration, the `IDbConnectionFactory` can be injected into
> classes that need a SQL connection.
>
>
>
> ```
> private readonly IDbConnectionFactory _connectionFactory;
> public GetProductsHandler(IDbConnectionFactory connectionFactory)
> {
> _connectionFactory = connectionFactory;
> }
>
> ```
>
> The `IDbConnectionFactory.CreateConnection` will return a decorated
> version that logs the activity.
>
>
>
> ```
> using (DbConnection db = _connectionFactory.CreateConnection())
> {
> //...
> }
>
> ```
>
> | This is not exhaustive and is essentially a bit of hack, but if you have your SQL and you want to initialize your parameters, it's useful for basic debugging. Set up this extension method, then call it anywhere as desired.
```
public static class DapperExtensions
{
public static string ArgsAsSql(this DynamicParameters args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
var sb = new StringBuilder();
foreach (var name in args.ParameterNames)
{
var pValue = args.Get<dynamic>(name);
var type = pValue.GetType();
if (type == typeof(DateTime))
sb.AppendFormat("DECLARE @{0} DATETIME ='{1}'\n", name, pValue.ToString("yyyy-MM-dd HH:mm:ss.fff"));
else if (type == typeof(bool))
sb.AppendFormat("DECLARE @{0} BIT = {1}\n", name, (bool)pValue ? 1 : 0);
else if (type == typeof(int))
sb.AppendFormat("DECLARE @{0} INT = {1}\n", name, pValue);
else if (type == typeof(List<int>))
sb.AppendFormat("-- REPLACE @{0} IN SQL: ({1})\n", name, string.Join(",", (List<int>)pValue));
else
sb.AppendFormat("DECLARE @{0} NVARCHAR(MAX) = '{1}'\n", name, pValue.ToString());
}
return sb.ToString();
}
}
```
You can then just use this in the immediate or watch windows to grab the SQL. |
Question: Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
Answer: | You should consider using SQL profiler located in the menu of *SQL Management Studio* ***→ Extras → SQL Server Profiler*** (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).
Then, start a new session.
You'll get something like this for example (you see all parameters and the complete SQL string):
```
exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = @appId AND (Blocked IS NULL OR Blocked = 0)
AND (Beta IS NULL OR Beta = 0 OR @includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(@langCode, '','')))',N'@appId nvarchar(4000),@includeBeta bit,@langCode nvarchar(4000)',@appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',@includeBeta=0,@langCode=N'de'
``` | This is not exhaustive and is essentially a bit of hack, but if you have your SQL and you want to initialize your parameters, it's useful for basic debugging. Set up this extension method, then call it anywhere as desired.
```
public static class DapperExtensions
{
public static string ArgsAsSql(this DynamicParameters args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
var sb = new StringBuilder();
foreach (var name in args.ParameterNames)
{
var pValue = args.Get<dynamic>(name);
var type = pValue.GetType();
if (type == typeof(DateTime))
sb.AppendFormat("DECLARE @{0} DATETIME ='{1}'\n", name, pValue.ToString("yyyy-MM-dd HH:mm:ss.fff"));
else if (type == typeof(bool))
sb.AppendFormat("DECLARE @{0} BIT = {1}\n", name, (bool)pValue ? 1 : 0);
else if (type == typeof(int))
sb.AppendFormat("DECLARE @{0} INT = {1}\n", name, pValue);
else if (type == typeof(List<int>))
sb.AppendFormat("-- REPLACE @{0} IN SQL: ({1})\n", name, string.Join(",", (List<int>)pValue));
else
sb.AppendFormat("DECLARE @{0} NVARCHAR(MAX) = '{1}'\n", name, pValue.ToString());
}
return sb.ToString();
}
}
```
You can then just use this in the immediate or watch windows to grab the SQL. |
Question: Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
Answer: | I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget [MiniProfiler.Integrations](https://www.nuget.org/packages/MiniProfiler.Integrations/) I would like to share.
**Update V2**: it supports to work with other database servers, for MySQL it requires to have [MiniProfiler.Integrations.MySql](https://www.nuget.org/packages/MiniProfiler.Integrations.MySql/)
Below are steps to work with SQL Server:
1.Instantiate the connection
```
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
```
2.After all works done, write all commands to a file if you want
```
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
``` | This is not exhaustive and is essentially a bit of hack, but if you have your SQL and you want to initialize your parameters, it's useful for basic debugging. Set up this extension method, then call it anywhere as desired.
```
public static class DapperExtensions
{
public static string ArgsAsSql(this DynamicParameters args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
var sb = new StringBuilder();
foreach (var name in args.ParameterNames)
{
var pValue = args.Get<dynamic>(name);
var type = pValue.GetType();
if (type == typeof(DateTime))
sb.AppendFormat("DECLARE @{0} DATETIME ='{1}'\n", name, pValue.ToString("yyyy-MM-dd HH:mm:ss.fff"));
else if (type == typeof(bool))
sb.AppendFormat("DECLARE @{0} BIT = {1}\n", name, (bool)pValue ? 1 : 0);
else if (type == typeof(int))
sb.AppendFormat("DECLARE @{0} INT = {1}\n", name, pValue);
else if (type == typeof(List<int>))
sb.AppendFormat("-- REPLACE @{0} IN SQL: ({1})\n", name, string.Join(",", (List<int>)pValue));
else
sb.AppendFormat("DECLARE @{0} NVARCHAR(MAX) = '{1}'\n", name, pValue.ToString());
}
return sb.ToString();
}
}
```
You can then just use this in the immediate or watch windows to grab the SQL. |
Question: Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
Answer: | Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.
In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:
* (primarily) security: since dapper doesn't have a concept of a context, it would be *really really* easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
* (secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be `null` in most cases) would have much impact
Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: `Debug.WriteLine` etc. | This is not exhaustive and is essentially a bit of hack, but if you have your SQL and you want to initialize your parameters, it's useful for basic debugging. Set up this extension method, then call it anywhere as desired.
```
public static class DapperExtensions
{
public static string ArgsAsSql(this DynamicParameters args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
var sb = new StringBuilder();
foreach (var name in args.ParameterNames)
{
var pValue = args.Get<dynamic>(name);
var type = pValue.GetType();
if (type == typeof(DateTime))
sb.AppendFormat("DECLARE @{0} DATETIME ='{1}'\n", name, pValue.ToString("yyyy-MM-dd HH:mm:ss.fff"));
else if (type == typeof(bool))
sb.AppendFormat("DECLARE @{0} BIT = {1}\n", name, (bool)pValue ? 1 : 0);
else if (type == typeof(int))
sb.AppendFormat("DECLARE @{0} INT = {1}\n", name, pValue);
else if (type == typeof(List<int>))
sb.AppendFormat("-- REPLACE @{0} IN SQL: ({1})\n", name, string.Join(",", (List<int>)pValue));
else
sb.AppendFormat("DECLARE @{0} NVARCHAR(MAX) = '{1}'\n", name, pValue.ToString());
}
return sb.ToString();
}
}
```
You can then just use this in the immediate or watch windows to grab the SQL. |
Question: Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
Answer: | Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.
In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:
* (primarily) security: since dapper doesn't have a concept of a context, it would be *really really* easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
* (secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be `null` in most cases) would have much impact
Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: `Debug.WriteLine` etc. | Just to add an update here since I see this question still get's quite a few hits - these days I use either [Glimpse](http://getglimpse.com/) (seems it's dead now) or [Stackify Prefix](https://stackify.com/prefix/) which both have sql command trace capabilities.
It's not exactly what I was looking for when I asked the original question but solve the same problem. |
Question: Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
Answer: | I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget [MiniProfiler.Integrations](https://www.nuget.org/packages/MiniProfiler.Integrations/) I would like to share.
**Update V2**: it supports to work with other database servers, for MySQL it requires to have [MiniProfiler.Integrations.MySql](https://www.nuget.org/packages/MiniProfiler.Integrations.MySql/)
Below are steps to work with SQL Server:
1.Instantiate the connection
```
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
```
2.After all works done, write all commands to a file if you want
```
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
``` | Try [Dapper.Logging](https://github.com/hryz/Dapper.Logging/tree/71f4f3de06b95f131e84171698e0d3ed7cb52f83).
-----------------------------------------------------------------------------------------------------------
You can get it from NuGet. The way it works is you pass your code that creates your actual database connection into a factory that creates wrapped connections. Whenever a wrapped connection is opened or closed or you run a query against it, it will be logged. You can configure the logging message templates and other settings like whether SQL parameters are saved. Elapsed time is also saved.
In my opinion, the only downside is that the documentation is sparse, but I think that's just because it's a new project (as of this writing). I had to dig through the repo for a bit to understand it and to get it configured to my liking, but now it's working great.
From the documentation:
>
> The tool consists of simple decorators for the `DbConnection` and
> `DbCommand` which track the execution time and write messages to the
> `ILogger<T>`. The `ILogger<T>` can be handled by any logging framework
> (e.g. Serilog). The result is similar to the default EF Core logging
> behavior.
>
>
> The lib declares a helper method for registering the
> `IDbConnectionFactory` in the IoC container. The connection factory is
> SQL Provider agnostic. That's why you have to specify the real factory
> method:
>
>
>
> ```
> services.AddDbConnectionFactory(prv => new SqlConnection(conStr));
>
> ```
>
> After registration, the `IDbConnectionFactory` can be injected into
> classes that need a SQL connection.
>
>
>
> ```
> private readonly IDbConnectionFactory _connectionFactory;
> public GetProductsHandler(IDbConnectionFactory connectionFactory)
> {
> _connectionFactory = connectionFactory;
> }
>
> ```
>
> The `IDbConnectionFactory.CreateConnection` will return a decorated
> version that logs the activity.
>
>
>
> ```
> using (DbConnection db = _connectionFactory.CreateConnection())
> {
> //...
> }
>
> ```
>
> |
Question: Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
Answer: | I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget [MiniProfiler.Integrations](https://www.nuget.org/packages/MiniProfiler.Integrations/) I would like to share.
**Update V2**: it supports to work with other database servers, for MySQL it requires to have [MiniProfiler.Integrations.MySql](https://www.nuget.org/packages/MiniProfiler.Integrations.MySql/)
Below are steps to work with SQL Server:
1.Instantiate the connection
```
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
```
2.After all works done, write all commands to a file if you want
```
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
``` | Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.
In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:
* (primarily) security: since dapper doesn't have a concept of a context, it would be *really really* easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
* (secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be `null` in most cases) would have much impact
Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: `Debug.WriteLine` etc. |
Question: Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
Answer: | You should consider using SQL profiler located in the menu of *SQL Management Studio* ***→ Extras → SQL Server Profiler*** (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).
Then, start a new session.
You'll get something like this for example (you see all parameters and the complete SQL string):
```
exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = @appId AND (Blocked IS NULL OR Blocked = 0)
AND (Beta IS NULL OR Beta = 0 OR @includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(@langCode, '','')))',N'@appId nvarchar(4000),@includeBeta bit,@langCode nvarchar(4000)',@appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',@includeBeta=0,@langCode=N'de'
``` | Just to add an update here since I see this question still get's quite a few hits - these days I use either [Glimpse](http://getglimpse.com/) (seems it's dead now) or [Stackify Prefix](https://stackify.com/prefix/) which both have sql command trace capabilities.
It's not exactly what I was looking for when I asked the original question but solve the same problem. |
Question: I'm using Google Test Framework to set some unit tests. I have got three projects in my solution:
* FN (my project)
* FN\_test (my tests)
* gtest (Google Test Framework)
I set FN\_test to have FN and gtest as references (dependencies), and then I think I'm ready to set up my tests (I've already set everyone to /MTd (not doing this was leading me to linking errors before)).
Particularly, I define a class called Embark in FN I would like to test using FN\_test. So far, so good. Thus I write a classe called EmbarkTest using googletest, declare a member Embark\* and write inside the constructor:
```
EmbarkTest() {
e = new Embark(900,2010);
}
```
Then , F7 pressed, I get the following:
`1>FN_test.obj : error LNK2019: unresolved external symbol "public: __thiscall Embark::Embark(int,int)" (??0Embark@@QAE@HH@Z) referenced in function "protected: __thiscall EmbarkTest::EmbarkTest(void)" (??0EmbarkTest@@IAE@XZ)`
`1>D:\Users\lg\Product\code\FN\Debug\FN_test.exe : fatal error LNK1120: 1 unresolved externals`
Does someone know what have I done wrong and/or what can I do to settle this?
**EDIT**: *Relevant* code from Embark.h
```
class Embark
{
public:
//Constructor for initial state
Embark(int _id, int _year);
//Destructor
~Embark();
/* ... */
}
```
Answer: | I found the answer to be a rather simple one. After two days of intense headknocking, it's this:
**You have to compile your main project as `.lib` and not `.exe`**
After doing this, all linking went as a bliss. I thought Visual Studio would do this automatically for me, since I declared a dependency to FN from FN\_test: I assumed Visual Studio would create the libs. It didn't.
---
**RANT** (no need to read after this)
Since it's rather rare to link one project that makes an executable to another one which does the same thing, finding references on this kind of issue was somewhat hard. Google searches presented me no useful results. MSDN forums were also unhelpful.
But when you do unit testing on a application, will it be common to have this happening, say, a test project and a application project on the same solution? I have no knowledge about other testing frameworks for C++. I have chosen Google Test Framework for:
1. In Google we trust
2. Great documentation
3. Very simple to use and understand
But, however, it has no much merits on integration. I think other tools would integrate way better to Visual Studio, IDE responsiveness inclusive. But I preferred to suffer now than afterwards. I hope this tool keeps improving, for I liked it. | The linker can't find the definition of the `Embark` constructor.
* Have you defined that constructor somewhere?
* Is your test project actually linking to the FN library? |
Question: I'm using Google Test Framework to set some unit tests. I have got three projects in my solution:
* FN (my project)
* FN\_test (my tests)
* gtest (Google Test Framework)
I set FN\_test to have FN and gtest as references (dependencies), and then I think I'm ready to set up my tests (I've already set everyone to /MTd (not doing this was leading me to linking errors before)).
Particularly, I define a class called Embark in FN I would like to test using FN\_test. So far, so good. Thus I write a classe called EmbarkTest using googletest, declare a member Embark\* and write inside the constructor:
```
EmbarkTest() {
e = new Embark(900,2010);
}
```
Then , F7 pressed, I get the following:
`1>FN_test.obj : error LNK2019: unresolved external symbol "public: __thiscall Embark::Embark(int,int)" (??0Embark@@QAE@HH@Z) referenced in function "protected: __thiscall EmbarkTest::EmbarkTest(void)" (??0EmbarkTest@@IAE@XZ)`
`1>D:\Users\lg\Product\code\FN\Debug\FN_test.exe : fatal error LNK1120: 1 unresolved externals`
Does someone know what have I done wrong and/or what can I do to settle this?
**EDIT**: *Relevant* code from Embark.h
```
class Embark
{
public:
//Constructor for initial state
Embark(int _id, int _year);
//Destructor
~Embark();
/* ... */
}
```
Answer: | I found the answer to be a rather simple one. After two days of intense headknocking, it's this:
**You have to compile your main project as `.lib` and not `.exe`**
After doing this, all linking went as a bliss. I thought Visual Studio would do this automatically for me, since I declared a dependency to FN from FN\_test: I assumed Visual Studio would create the libs. It didn't.
---
**RANT** (no need to read after this)
Since it's rather rare to link one project that makes an executable to another one which does the same thing, finding references on this kind of issue was somewhat hard. Google searches presented me no useful results. MSDN forums were also unhelpful.
But when you do unit testing on a application, will it be common to have this happening, say, a test project and a application project on the same solution? I have no knowledge about other testing frameworks for C++. I have chosen Google Test Framework for:
1. In Google we trust
2. Great documentation
3. Very simple to use and understand
But, however, it has no much merits on integration. I think other tools would integrate way better to Visual Studio, IDE responsiveness inclusive. But I preferred to suffer now than afterwards. I hope this tool keeps improving, for I liked it. | The linker can't find `Embark::Embark(int, int)`
Here is what MSDN says about error [LNK2019](http://msdn.microsoft.com/en-us/library/799kze2z(VS.80).aspx). |
Question: What we take for granted in other languages and almost expect it to work in go, won't work - its almost so natural to do this, so why isn't the compiler happy? Just feeling like bailing out of go sometimes.
The only way to increment the value is to put it in its own separate line?
<http://play.golang.org/p/_UnpZVSN9n>
```
package main
import "fmt"
import "strconv"
func main() {
a := 1
//Evaluate expression and pass into function - won't work
fmt.Println(strconv.Itoa(a++))
//Braces around a++ also won't work
fmt.Println(strconv.Itoa((a++)))
}
```
Answer: | `++` and `--` are statements in golang, not expressions | Specifically, `++` and `--` are statements because it can be very difficult to understand the order of evaluation when they're in an expression.
Consider the following:
```
// This is not valid Go!
x := 1
x = x++ + x
y := 1
y = ++y + y
```
What would you expect `x` to be? What would you expect `y` to be? By contrast, the order of evaluation is very clear when this is a statement. |
Question: What we take for granted in other languages and almost expect it to work in go, won't work - its almost so natural to do this, so why isn't the compiler happy? Just feeling like bailing out of go sometimes.
The only way to increment the value is to put it in its own separate line?
<http://play.golang.org/p/_UnpZVSN9n>
```
package main
import "fmt"
import "strconv"
func main() {
a := 1
//Evaluate expression and pass into function - won't work
fmt.Println(strconv.Itoa(a++))
//Braces around a++ also won't work
fmt.Println(strconv.Itoa((a++)))
}
```
Answer: | `++` and `--` are statements in golang, not expressions | Just to help clarify, an expression has a `=`, `:=` or `+=` in them. A statement (such as `++` and `—`) does not. See <https://stackoverflow.com/a/1720029/12817546>.
```
package main
import "fmt"
var x int
func f(x int) {
x = x + 1 //expression
x++ //statement
fmt.Println(x) //2
}
func main() {
f(x) //expression statement
}
```
An "expression" specifies the computation of a value by applying operators and functions to operands. See <https://golang.org/ref/spec#Expressions>.
A "statement" controls execution. See <https://golang.org/ref/spec#Statements>.
An "expression statement" is a function and method call or receive operation that appears in a statement. See <https://golang.org/ref/spec#Expression_statements>. |
Question: What we take for granted in other languages and almost expect it to work in go, won't work - its almost so natural to do this, so why isn't the compiler happy? Just feeling like bailing out of go sometimes.
The only way to increment the value is to put it in its own separate line?
<http://play.golang.org/p/_UnpZVSN9n>
```
package main
import "fmt"
import "strconv"
func main() {
a := 1
//Evaluate expression and pass into function - won't work
fmt.Println(strconv.Itoa(a++))
//Braces around a++ also won't work
fmt.Println(strconv.Itoa((a++)))
}
```
Answer: | Specifically, `++` and `--` are statements because it can be very difficult to understand the order of evaluation when they're in an expression.
Consider the following:
```
// This is not valid Go!
x := 1
x = x++ + x
y := 1
y = ++y + y
```
What would you expect `x` to be? What would you expect `y` to be? By contrast, the order of evaluation is very clear when this is a statement. | Just to help clarify, an expression has a `=`, `:=` or `+=` in them. A statement (such as `++` and `—`) does not. See <https://stackoverflow.com/a/1720029/12817546>.
```
package main
import "fmt"
var x int
func f(x int) {
x = x + 1 //expression
x++ //statement
fmt.Println(x) //2
}
func main() {
f(x) //expression statement
}
```
An "expression" specifies the computation of a value by applying operators and functions to operands. See <https://golang.org/ref/spec#Expressions>.
A "statement" controls execution. See <https://golang.org/ref/spec#Statements>.
An "expression statement" is a function and method call or receive operation that appears in a statement. See <https://golang.org/ref/spec#Expression_statements>. |
Question: The charset is Unicode. I want to write a string of CString type into a file, and then read it out from the file afterwards.
I write the string into a file with CFile::Write() method:
```
int nLen = strSample.GetLength()*sizeof(TCHAR);
file.Write(strSample.GetBuffer(), nLen);
```
Here is the question: I want to obtain the CString from the file containing the content of strSample. How can I do it?
Thank you very much!
Answer: | ```
UINT nBytes = (UINT)file.GetLength();
int nChars = nBytes / sizeof(TCHAR);
nBytes = file.Read(strSample.GetBuffer(nChars), nBytes);
strSample.ReleaseBuffer(nChars);
``` | I think you forgot to include the '\0' at the end
strSample.GetLength() + 1 |
Question: The charset is Unicode. I want to write a string of CString type into a file, and then read it out from the file afterwards.
I write the string into a file with CFile::Write() method:
```
int nLen = strSample.GetLength()*sizeof(TCHAR);
file.Write(strSample.GetBuffer(), nLen);
```
Here is the question: I want to obtain the CString from the file containing the content of strSample. How can I do it?
Thank you very much!
Answer: | ```
UINT nBytes = (UINT)file.GetLength();
int nChars = nBytes / sizeof(TCHAR);
nBytes = file.Read(strSample.GetBuffer(nChars), nBytes);
strSample.ReleaseBuffer(nChars);
``` | I would try this, since it can be that the file is larger than what is read (DOS style end line). Read does not set the final \0, but ReleaseBuffer apparently does, if not called with -1.
```
UINT nBytes = (UINT)file.GetLength();
UINT nBytesRead = file.Read(strSample.GetBuffer(nBytes+1), nBytes);
strSample.ReleaseBuffer(nBytesRead);
``` |
Question: Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know.
Answer: | Here is my (very short) answer:
All the calculations in the frequency domain (transfer function, input-and output impedances, pole location,..) do consider STEADY STATE conditions for the circuit under test. Therefore - due to the time dependence of your input - you cannot expect that the circuit will react upon such an input as predicted by the pole analysis.
The observed response of the circuit will be dominated by the time domain behaviour (transient response)...
**Comment** (Edit): In his nice answer KD9PDP has shown that we must switch-over to the time domain - nevertheless, making use of the transfer function - to find the correct result. | It *is* ramping to infinity as you expected. The s-domain calculation is a steady-state calculation, and you have an initial transient (your input exponential was effectively a constant '1' for all t < 0). You have to wait for that to decay (i.e. become negligible) -- e.g. a long (infinite) time.
You can see that after 10 time constants, your 'gain' is already 10. |
Question: Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know.
Answer: | [KD9PDP's answer](https://electronics.stackexchange.com/a/551541/95619) alreay explains very nice (+1) why the result is as you see it, but there might be an easier way to do it. You already have the impulse response (1) and the input (2):
$$\begin{align}
h(t)&=\dfrac{1}{RC}\mathrm{e}^{-\frac{t}{RC}}\tag{1} \\
s(t)&=\mathrm{e}^{-\frac{t}{RC}}\tag{2}
\end{align}$$
The convolution integral is now simple because \$h(t)\$ and \$s(t)\$ are simplified before applying the integral:
$$\begin{align}
s(t)\star h(t)&=\int\_{\tau}{\dfrac{1}{RC}\mathrm{e}^{-\frac{\tau}{RC}}\cdot\mathrm{e}^{-\frac{t-\tau}{RC}}\mathrm{d}\tau} \\
{}&=\int\_{\tau}{\dfrac{1}{RC}\mathrm{e}^{-\frac{t}{RC}}\mathrm{d}\tau} \\
{}&=\dfrac{1}{RC}\mathrm{e}^{-\frac{t}{RC}}\cdot t\tag{3} \\
\end{align}$$
Since the variable is \$\tau\$, the integrand is a constant, and integrating it means adding \$t\$, which is the only difference between (3) and (1). As noted in the other answer, it's also a matter of initial conditions (\$\mathrm{i.c.}\$), since LTspice assumes those to be given by the value of the behavioural expression at `t=0`, which is `1`. | It *is* ramping to infinity as you expected. The s-domain calculation is a steady-state calculation, and you have an initial transient (your input exponential was effectively a constant '1' for all t < 0). You have to wait for that to decay (i.e. become negligible) -- e.g. a long (infinite) time.
You can see that after 10 time constants, your 'gain' is already 10. |
Question: Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know.
Answer: | If the system's impulse response is \$h(t)=e^{-at}u(t)\$, \$a>0\$, where \$u(t)\$ is the unit step function, and if its input is \$x(t)=e^{-at}u(t)\$, then its response is given by
$$y(t)=te^{-at}u(t)\tag{1}$$
which is a basic result. The function \$(1)\$ is just the inverse Laplace transform of a double real-valued pole:
$$Y(s)=\frac{1}{(s+a)^2}\tag{2}$$
Clearly, the output \$y(t)\$ decays to zero. However, the ratio \$y(t)/x(t)\$ is a ramp for \$t>0\$.
Please note that the ratio \$y(t)/x(t)\$ is not the system's transfer function. The transfer function is the ratio of the Laplace transforms of the input and output:
$$H(s)=\frac{Y(s)}{X(s)}\tag{3}$$
For a first-order lowpass filter with time constant \$\tau\$, \$H(s)\$ is given by
$$H(s)=\frac{1}{1+s\tau}\tag{4}$$ | It *is* ramping to infinity as you expected. The s-domain calculation is a steady-state calculation, and you have an initial transient (your input exponential was effectively a constant '1' for all t < 0). You have to wait for that to decay (i.e. become negligible) -- e.g. a long (infinite) time.
You can see that after 10 time constants, your 'gain' is already 10. |
Question: I am developing a node.js app, and I want to use a module I am creating for the node.js server also on the client side.
An example module would be circle.js:
```
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
```
and you do a simple
```
var circle = require('./circle')
```
to use it in node.
How could I use that same file in the web directory for my client side javascript?
Answer: | This seems to be how to make a module something you can use on the client side.
<https://caolan.org/posts/writing_for_node_and_the_browser.html>
mymodule.js:
```
(function(exports){
// your code goes here
exports.test = function(){
return 'hello world'
};
})(typeof exports === 'undefined'? this['mymodule']={}: exports);
```
And then to use the module on the client:
```
<script src="mymodule.js"></script>
<script>
alert(mymodule.test());
</script>
```
This code would work in node:
```
var mymodule = require('./mymodule');
``` | ![Browserify](https://i.stack.imgur.com/5FtLy.png)
[Browserify](https://github.com/substack/node-browserify)
It magically lets you do that. |
Question: I am developing a node.js app, and I want to use a module I am creating for the node.js server also on the client side.
An example module would be circle.js:
```
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
```
and you do a simple
```
var circle = require('./circle')
```
to use it in node.
How could I use that same file in the web directory for my client side javascript?
Answer: | ![Browserify](https://i.stack.imgur.com/5FtLy.png)
[Browserify](https://github.com/substack/node-browserify)
It magically lets you do that. | [Webmake](https://github.com/medikoo/modules-webmake) was made to port CommonJS/NodeJS modules to browser. Give it a try |
Question: I am developing a node.js app, and I want to use a module I am creating for the node.js server also on the client side.
An example module would be circle.js:
```
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
```
and you do a simple
```
var circle = require('./circle')
```
to use it in node.
How could I use that same file in the web directory for my client side javascript?
Answer: | This seems to be how to make a module something you can use on the client side.
<https://caolan.org/posts/writing_for_node_and_the_browser.html>
mymodule.js:
```
(function(exports){
// your code goes here
exports.test = function(){
return 'hello world'
};
})(typeof exports === 'undefined'? this['mymodule']={}: exports);
```
And then to use the module on the client:
```
<script src="mymodule.js"></script>
<script>
alert(mymodule.test());
</script>
```
This code would work in node:
```
var mymodule = require('./mymodule');
``` | [Webmake](https://github.com/medikoo/modules-webmake) was made to port CommonJS/NodeJS modules to browser. Give it a try |
Question: say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs?
Answer: | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. | Not currently, other than templates as others have mentioned. What you could do, however, is to include the initial HTML code in your main document, and then set the values with `rightPane.val(task.data1);`, etc. |
Question: say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs?
Answer: | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. | You can try to do something like this: [Format a string using placeholders and an object of substitutions?](https://stackoverflow.com/questions/7975005/format-a-string-using-placeholders-and-an-object-of-substitutions)
but as Hacketo suggests it would be better to learn to use templates. Take for instance look at underscore.js (<http://underscorejs.org/#template>) |
Question: say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs?
Answer: | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. | One alternative way of approaching this would be :
```
var $h2 = $("<h2>", {text : task.task});
var $data1 = $("<input>", {type : 'text', value : task.data1});
var $data2 = $("<input>", {type : 'text', value : task.data2});
var $data3 = $("<input>", {type : 'text', value : task.data3});
var $button = $("<input>", {type : 'button', value : 'Save'});
rightPane.append($h2, $data1, $data2, $data3, $button);
```
This might be a little easier to follow when scanning over the code, rather than shifting through the `.html()` function. |
Question: say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs?
Answer: | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. | You could take a look at a JavaScript templating engine. Such as Handlebars, Mustache etc. You can see some of the popular ones [here](http://www.creativebloq.com/web-design/templating-engines-9134396): You can *kind* of view these as user controls similar to what you get in ASP.NET
This is an example of Handlebars for your code:
```
<h2>{{task}}<h2> <hr />
data1: <input type="text" id="data1" value="{{data1}}" /> <br />
data2: <input type="text" id="data2" value="{{data2}}" /> <br />
data1: <input type="text" id="data3" value="{{data3}}" /> <br />
<input type="button" id="subUpdated" value="Save">
``` |
Question: say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs?
Answer: | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. | You could create your own super-simple 'template engine'.
* Write your template in the markup of your page as you would a usual element.
* Give the template container element an attribute to denote its role as a template, for example a data attribute of `data-template`.
* Clone and detach all `data-template` elements when the DOM is ready.
* On some event, insert your values as you like, then re-insert the compiled template into the page.
For example:
```js
$(document).ready(function() {
var template = $('[data-template]').detach().clone();
var values = { foo: 'bar', yipee: 'yahoo' };
$('button').click(function() {
for(var prop in values) {
template.find('[data-value="' + prop + '"]').html(values[prop]);
$('#container').append(template);
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Insert</button>
<div id="container"></div>
<div data-template>
<div data-value="foo"></div>
<div>
<div data-value="yipee"></div>
</div>
</div>
``` |
Question: say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs?
Answer: | You could create your own super-simple 'template engine'.
* Write your template in the markup of your page as you would a usual element.
* Give the template container element an attribute to denote its role as a template, for example a data attribute of `data-template`.
* Clone and detach all `data-template` elements when the DOM is ready.
* On some event, insert your values as you like, then re-insert the compiled template into the page.
For example:
```js
$(document).ready(function() {
var template = $('[data-template]').detach().clone();
var values = { foo: 'bar', yipee: 'yahoo' };
$('button').click(function() {
for(var prop in values) {
template.find('[data-value="' + prop + '"]').html(values[prop]);
$('#container').append(template);
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Insert</button>
<div id="container"></div>
<div data-template>
<div data-value="foo"></div>
<div>
<div data-value="yipee"></div>
</div>
</div>
``` | Not currently, other than templates as others have mentioned. What you could do, however, is to include the initial HTML code in your main document, and then set the values with `rightPane.val(task.data1);`, etc. |
Question: say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs?
Answer: | You could create your own super-simple 'template engine'.
* Write your template in the markup of your page as you would a usual element.
* Give the template container element an attribute to denote its role as a template, for example a data attribute of `data-template`.
* Clone and detach all `data-template` elements when the DOM is ready.
* On some event, insert your values as you like, then re-insert the compiled template into the page.
For example:
```js
$(document).ready(function() {
var template = $('[data-template]').detach().clone();
var values = { foo: 'bar', yipee: 'yahoo' };
$('button').click(function() {
for(var prop in values) {
template.find('[data-value="' + prop + '"]').html(values[prop]);
$('#container').append(template);
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Insert</button>
<div id="container"></div>
<div data-template>
<div data-value="foo"></div>
<div>
<div data-value="yipee"></div>
</div>
</div>
``` | You can try to do something like this: [Format a string using placeholders and an object of substitutions?](https://stackoverflow.com/questions/7975005/format-a-string-using-placeholders-and-an-object-of-substitutions)
but as Hacketo suggests it would be better to learn to use templates. Take for instance look at underscore.js (<http://underscorejs.org/#template>) |
Question: say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs?
Answer: | You could create your own super-simple 'template engine'.
* Write your template in the markup of your page as you would a usual element.
* Give the template container element an attribute to denote its role as a template, for example a data attribute of `data-template`.
* Clone and detach all `data-template` elements when the DOM is ready.
* On some event, insert your values as you like, then re-insert the compiled template into the page.
For example:
```js
$(document).ready(function() {
var template = $('[data-template]').detach().clone();
var values = { foo: 'bar', yipee: 'yahoo' };
$('button').click(function() {
for(var prop in values) {
template.find('[data-value="' + prop + '"]').html(values[prop]);
$('#container').append(template);
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Insert</button>
<div id="container"></div>
<div data-template>
<div data-value="foo"></div>
<div>
<div data-value="yipee"></div>
</div>
</div>
``` | One alternative way of approaching this would be :
```
var $h2 = $("<h2>", {text : task.task});
var $data1 = $("<input>", {type : 'text', value : task.data1});
var $data2 = $("<input>", {type : 'text', value : task.data2});
var $data3 = $("<input>", {type : 'text', value : task.data3});
var $button = $("<input>", {type : 'button', value : 'Save'});
rightPane.append($h2, $data1, $data2, $data3, $button);
```
This might be a little easier to follow when scanning over the code, rather than shifting through the `.html()` function. |
Question: say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs?
Answer: | You could create your own super-simple 'template engine'.
* Write your template in the markup of your page as you would a usual element.
* Give the template container element an attribute to denote its role as a template, for example a data attribute of `data-template`.
* Clone and detach all `data-template` elements when the DOM is ready.
* On some event, insert your values as you like, then re-insert the compiled template into the page.
For example:
```js
$(document).ready(function() {
var template = $('[data-template]').detach().clone();
var values = { foo: 'bar', yipee: 'yahoo' };
$('button').click(function() {
for(var prop in values) {
template.find('[data-value="' + prop + '"]').html(values[prop]);
$('#container').append(template);
}
});
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Insert</button>
<div id="container"></div>
<div data-template>
<div data-value="foo"></div>
<div>
<div data-value="yipee"></div>
</div>
</div>
``` | You could take a look at a JavaScript templating engine. Such as Handlebars, Mustache etc. You can see some of the popular ones [here](http://www.creativebloq.com/web-design/templating-engines-9134396): You can *kind* of view these as user controls similar to what you get in ASP.NET
This is an example of Handlebars for your code:
```
<h2>{{task}}<h2> <hr />
data1: <input type="text" id="data1" value="{{data1}}" /> <br />
data2: <input type="text" id="data2" value="{{data2}}" /> <br />
data1: <input type="text" id="data3" value="{{data3}}" /> <br />
<input type="button" id="subUpdated" value="Save">
``` |
Question: I need to write in a pure JavaScript function which will execute only for 5 seconds and will stop if either one of the following conditions (whichever comes first)
1. 5 seconds has elapsed
2. user inputted a field
I could only do condition 2 but can't figure out how to break the loop after 5 seconds:
```
function beginScanningForItemVer2(){
var userInput= false;
var element;
while (!userInput){
element = document.getElementById("input").value;
if (element != null){
userInput= true;
}
}
}
```
EDIT:
Thanks guys for helping me. Please keep helping me...
It seems I cannot use a while loop for detecting user input because my CPU usage goes up really fast while on the loop. Is there any way to accomplish both of these? Please help me
Answer: | Javascript tends to be very callback oriented, since by default all the Javascript on a page runs in a single thread, which means that the UI isn't responsive while other code is busy running. So rather than looping in a function and looking for input on each loop, you likely want to register a callback function which will be called when your input element experiences a change -- for example, the `onchange` listener will run your callback whenever the value of the element changes. You could unregister this callback 5 seconds later to stop anything from happening if the user inputs something after the 5 seconds are up.
Sparse example (referencing <http://www.w3schools.com/jsref/event_onchange.asp>):
```
// Set a function to be called when the value of the input element changes.
object.onchange = function() {
valueAfterChange = document.getElementById("input").value;
// Do something with valueAfterChange.
}
// window.setInterval calls a function after a set delay.
window.setInterval(function() {
object.onchange = null;
// Anything else you might want to do after 5 seconds.
}, 5000); // Call this function after 5000 milliseconds == 5 seconds.
``` | **Eddited**
You could combine `setInterval` and `setTimeout` to solve . Your code will look like this.
```
var interval = setInterval(function() {
var userInput= false;
var element;
while (!userInput){
element = document.getElementById("input").value;
if (element != null){
userInput= true;
}
}
}, 1000);
setTimeout(function() {
clearInterval(interval);
}, 5000)
```
You could see more information here. Cheers.
<https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers> |
Question: I am following [this thread](https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript) which shows how to generate DOM elements dynamically.
Suppose I have this snippet that generate a series of buttons:
```
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuMgtCategoryButtons.appendChild(menuCatButton);
}
```
How do I apply this set of style to all of the newly created buttons?
```
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
```
Answer: | You can add the class the element using `classList.add()`.
**Demo:**
```js
var result = [1,2];
var menuMgtCategoryButtons = document.getElementById('menuMgtCategoryButtons');
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuCatButton.textContent = "Button "+result[i]; // add the text to the button
menuCatButton.classList.add('new-button'); // add the class to the button
menuMgtCategoryButtons.appendChild(menuCatButton);
}
```
```css
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
```
```html
<div id="menuMgtCategoryButtons"></div>
``` | Add this line
```
menuCatButton.className="new-button"
``` |
Question: I am following [this thread](https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript) which shows how to generate DOM elements dynamically.
Suppose I have this snippet that generate a series of buttons:
```
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuMgtCategoryButtons.appendChild(menuCatButton);
}
```
How do I apply this set of style to all of the newly created buttons?
```
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
```
Answer: | You can add the class the element using `classList.add()`.
**Demo:**
```js
var result = [1,2];
var menuMgtCategoryButtons = document.getElementById('menuMgtCategoryButtons');
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuCatButton.textContent = "Button "+result[i]; // add the text to the button
menuCatButton.classList.add('new-button'); // add the class to the button
menuMgtCategoryButtons.appendChild(menuCatButton);
}
```
```css
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
```
```html
<div id="menuMgtCategoryButtons"></div>
``` | Just add the class to each element in the loop just after you have created the element.
```
menuCatButton.classList.add("new-button");
``` |
Question: Other people who have asked this question had answers about downloading Vim from Vim.org, but that website doesn't respond.
Are there other ways to use Vi on Windows?
Answer: | Use a mutation observer to watch the list item instead of watching the document as a whole.
```js
// The item we want to watch
var watch = document.querySelector('.active')
// The new observer with a callback to execute upon change
var observer = new MutationObserver((mutationsList) => {
console.log(new Date().toUTCString())
});
// Start observing the element using these settings
observer.observe(watch, { childList: true, subtree: true });
// Some random test function to modify the element
// This will make sure the callback is running correctly
setInterval(() => {
watch.innerHTML = Math.random() * 1000
}, 1000)
```
```html
<ul>
<li class="active"></li>
</ul>
``` | Most jQuery code has a similar counterpart available. The `$('li.active')` can be replaced with `document.querySelectorAll('li.active')`. This gives you all elements matching your selector. The `bind` call would be achieved by iterating over the elements and using `addEventListener('DOMSubtreeModified', function(event) { … })`. |
Question: When I closed MySql server, how can I understand that mysql server is gone away from my Qt program?
**Edit:**
Here my trial:
When I close MySql, I get these results, and I can't catch that MySql is closed.
My Code Snippet is
```
QSqlQuery query(db);
query.exec("SELECT * From RequestIds");
qDebug()<<query.lastError();
qDebug()<<db.lastError()<<QTime::currentTime();
qDebug()<<db.isOpen();
qDebug()<<db.isValid();
```
and output is:
```
QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")
QSqlError(-1, "", "") QTime("14:22:58")
true
true
```
I don't understand why db.isOpen() returns true.
Answer: | There is a bug related with QSqlDatabase::isOpen() in Qt.
<https://bugreports.qt.io/browse/QTBUG-223> | Your program has no idea of its surroundings. If something changes, you may be able to have the OS notify your program, or you'll have to test yourself.
If the database connection closes before your program, the status from the connection should return some kind of error code. You **are checking status** from the connection functions?
Write a simple program that opens a window and upon the click of a button, writes to the database. After writing to the database, the program should display the status in the window. Run your program. Press button to get the "controlled" response. Close the database then click on the button again.
You may be able to do this with a debugger, depending on the ability of the debugger & OS to queue up messages. |
Question: When I closed MySql server, how can I understand that mysql server is gone away from my Qt program?
**Edit:**
Here my trial:
When I close MySql, I get these results, and I can't catch that MySql is closed.
My Code Snippet is
```
QSqlQuery query(db);
query.exec("SELECT * From RequestIds");
qDebug()<<query.lastError();
qDebug()<<db.lastError()<<QTime::currentTime();
qDebug()<<db.isOpen();
qDebug()<<db.isValid();
```
and output is:
```
QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")
QSqlError(-1, "", "") QTime("14:22:58")
true
true
```
I don't understand why db.isOpen() returns true.
Answer: | There is a bug related with QSqlDatabase::isOpen() in Qt.
<https://bugreports.qt.io/browse/QTBUG-223> | `QSqlQuery::lastError()` should give you an error if your query via `QSqlQuery::exec()` has failed. Also `QSqlDatabase::isOpen()` should report the state of your connection, `QSqlDatabase::lastError()` is also available |
Question: When I closed MySql server, how can I understand that mysql server is gone away from my Qt program?
**Edit:**
Here my trial:
When I close MySql, I get these results, and I can't catch that MySql is closed.
My Code Snippet is
```
QSqlQuery query(db);
query.exec("SELECT * From RequestIds");
qDebug()<<query.lastError();
qDebug()<<db.lastError()<<QTime::currentTime();
qDebug()<<db.isOpen();
qDebug()<<db.isValid();
```
and output is:
```
QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")
QSqlError(-1, "", "") QTime("14:22:58")
true
true
```
I don't understand why db.isOpen() returns true.
Answer: | There is a bug related with QSqlDatabase::isOpen() in Qt.
<https://bugreports.qt.io/browse/QTBUG-223> | You can use `isOpenError` to determine whether opening the initial database connection was successfull. I agree that `isOpen` returning `true` is confusing.
To monitor the database connection I repeatedly try to open and close a lightweight MySQL connection (e.g. every 3 seconds):
```
#include <mysql/mysql.h>
mysql_init(&connection);
MYSQL *result = mysql_real_connect(&connection,
host.isNull() ? static_cast<const char *>(0) : host.toLocal8Bit().constData(),
user.isNull() ? static_cast<const char *>(0) : user.toLocal8Bit().constData(),
pass.isNull() ? static_cast<const char *>(0) : pass.toLocal8Bit().constData(),
dbName.isNull() ? static_cast<const char *>(0) : dbName.toLocal8Bit().constData(),
0,
0,
0);
bool currentlyConnected = (result != 0);
```
In the above example, `host`, `user`, `pass`, and `dbName` are `QString` instances containing the connection information. Note that you need the MySQL development headers. |
Question: My question maybe unheard of or may even be impractical.
But, I believe it is practical and acceptable.
**Problem: PHP request and response in background thread.**
Problem constraints:
1. You know it uses POST method.
2. It has two fields fname and lname as html ids that need to be filled.
3. You get response in the same page i.e. index.php .
Pseudocode to solve the problem:
1. Open the website in background. Something like openURL("xyz(dot)com");
2. Read the data sent in html format.
3. Change the value of the fields fname and lname to required fields "Allen" and "Walker."
4. Now, submit the fields back to the server. ( Page has a submit button.)
**Note:** PHP code has a standard if-else check to check for those values. If the field is properly set, it then says "Success" else "Failed"
5. Again, get the response sent by the server.
6. Check if "Success" was returned.
7. If "success" was returned, UPDATE UI thread for saying "JOB done".
Else, "Job failed."
**Note: I am not talking about using a** *WebView*. **Everything happens via a service or AsyncTask**.
---
Now, this is a simple question, and any ideas or a direction is acceptable.
**So, to recap. You have to open a webpage in background, change its field, submit it back and then get the response.**
---
I know we can open a website and get its content. But, I would also like to know if what I said is possible or not. And, I know it is possible. And, that I only lack the knowledge on Java Web API, could you please guide me on this.
Thank You. And, Have a Good day!
Answer: | use [this link](http://www.androidhive.info/2012/01/android-json-parsing-tutorial/) for best solution of calling web service without using WebView.
In this example fname and lname sent in namevaluepairs we get responce in json formet and parse json and get data also json parse defined in examples. | What you are trying to achieve is to create a webservice call using a [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html).
Like you have mentioned, you can make a post request within the AsyncTask, passing in the variables required for the request.
You can find a good example as shown: [Sending HTTP Post Request with Android](https://stackoverflow.com/questions/31552242/sending-http-post-request-with-android) |
Question: quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :(
Answer: | The song you quote with the bass line la,fa do,so and the chords Bm G D A can’t be identified as B minor or D major without listening to it.
vi IV I V is one possible solution referring to major (beginning on the 6th degree)
but this progression is ambivalent and it can be interpreted in Bm as i VI III bVII (b stands for the minor 7th degree of aeolian mode).
If we listen to the melody and we have somewhere a home feeling on each of these chords it may help us to decide whether the song is in Bm aeolian or in D major.
without a hint of tonic (see other answers): Yes it can be interpreted in both keys. But surely it makes sense to capital letters to assign Roman numbers of major chords and i, vi, for the minor chords.
If you have no other indications I agree with you that you say the song is in D as it begins with D.
But songs like this don’t need to be analyzed by R.N. It is sufficient that you know i VI ... in minor vi IV ... in major. You can practice this analogy back until to early Baroque music. | The answer to your question is **yes**.
The notation you use is relative to tonic. Establishing which sound is the tonic (and whether it changes) is completely outside of this tool. Consider anything noted as II-V as carrying a standard disclaimer "assuming that X is the tonic".
If you have a song with chords: C F C F C F, it might be a I-IV-I-IV, it might be a V-I-V-I. Depends on the rhythm, melody and even the listener. You can "make" yourself hear different tonics for the same progression in a similar way you can make yourself hear different "1" in a repeated drum loop.
There's some modern research concerning this, the classical theory just assumed that all people have roughly the same musical background and follow the same convention. |
Question: quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :(
Answer: | The scale/chords are good clues to the key of a song, but at least as important is the *tonal center*. That's not as easy to define but generally it's where the song comes back to a place of less musical tension.
IMHO the chord played when the song in question returns to a "rest" state is A major. Which means I would say the song is in A and the progression is ii - bVII - IV - I. That would suggest that the scale is actually A mixolydian (not pure major or minor), which is not unusual for rock.
The point is that the key of a song is not only about the scale. Learning to hear the tonal center is sometimes more important. | The answer to your question is **yes**.
The notation you use is relative to tonic. Establishing which sound is the tonic (and whether it changes) is completely outside of this tool. Consider anything noted as II-V as carrying a standard disclaimer "assuming that X is the tonic".
If you have a song with chords: C F C F C F, it might be a I-IV-I-IV, it might be a V-I-V-I. Depends on the rhythm, melody and even the listener. You can "make" yourself hear different tonics for the same progression in a similar way you can make yourself hear different "1" in a repeated drum loop.
There's some modern research concerning this, the classical theory just assumed that all people have roughly the same musical background and follow the same convention. |
Question: quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :(
Answer: | The answer lies in which chord is used to finish the piece (or section thereof.) If a piece ends with V-I (with I being D major and V being A major for example), one would say that that section (or piece) is in D major. To end a piece in the relative minor (same key signature but that's just for notational convenience and not universally used during the Baroque), one would have V-i with i being a b minor chord and V being F# major. (The V chords could be V7s without changing the analysis.)
Try playing A7-D or A-D then F#7-b or F#-b and listen to the difference. This applies to Common Practice Period harmony (which is still commonly used) where the chord on the dominant is a major (even if needing an accidental) in a cadence. (A almost said accidentally major....) | The answer to your question is **yes**.
The notation you use is relative to tonic. Establishing which sound is the tonic (and whether it changes) is completely outside of this tool. Consider anything noted as II-V as carrying a standard disclaimer "assuming that X is the tonic".
If you have a song with chords: C F C F C F, it might be a I-IV-I-IV, it might be a V-I-V-I. Depends on the rhythm, melody and even the listener. You can "make" yourself hear different tonics for the same progression in a similar way you can make yourself hear different "1" in a repeated drum loop.
There's some modern research concerning this, the classical theory just assumed that all people have roughly the same musical background and follow the same convention. |
Question: quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :(
Answer: | The problem goes away if you consider D and Bm to be two sides of the same key. They have the same key signature. The Roman numeral analysis system - in the form you talk about - assumes that either the major or minor side is clearly more prominent, in order to assign number one to a scale degree. You should make a decision: do you want to subscribe to this idea of two possible "ones", or normalize the situation and have the major side's tonic be number I always, even for tunes that are "in minor". Who cares about the numbers? You know where D and B are, what notes are in the default scale specified by the key signature, and how to play the song, isn't that enough?
The tonal center can sway back and forth in a song, and it's often more or less ambiguous. It can even feel like moving completely outside the original major and minor side tonics, and then we talk about a potential modulation. Insisting on moving the number one around all the time is useless IMO. The whole Roman numeral thing and functional harmony is a simplified model for harmony exercises and theory classes. Just a tool to get a perspective on a static harmonic snapshot. But real music isn't so clear and static, it moves and morphs around. | As others have pointed out, whether a song is in a major key or its relative minor is often a matter of debate or opinion. However, there are some clues that can point in one or other direction.
First, in specifically the *harmonic* minor there is a key difference, the raised leading note: thus here you would expect an A# in B minor but it would be difficult to explain in D major. Assuming that I've got the right song (["Take Me Home" by Avicii](https://www.youtube.com/watch?v=IcrbM1l_BoI)), there is an A# on the last beat of the bar every second time the chord sequence repeats, making a V-i progression back to the tonic. I would analyse the chord sequence (in the guitar at the beginning, which is a bit more revealing) as i - VI - IIIc - VII i7d - i - VI - IIIc - VII V.
Second, in the bass line, dominant to tonic is a very strong sequence to establish a tonal centre, so looking for F# - B or A - D progression at a cadence will also be helpful. Thinking of the *end* of the song now, we have the bassline
B - G - D - A - B - G - D - **F# - B**
For both of these reasons I'd say that the song is unambiguously in B minor. |
Question: quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :(
Answer: | As others have pointed out, whether a song is in a major key or its relative minor is often a matter of debate or opinion. However, there are some clues that can point in one or other direction.
First, in specifically the *harmonic* minor there is a key difference, the raised leading note: thus here you would expect an A# in B minor but it would be difficult to explain in D major. Assuming that I've got the right song (["Take Me Home" by Avicii](https://www.youtube.com/watch?v=IcrbM1l_BoI)), there is an A# on the last beat of the bar every second time the chord sequence repeats, making a V-i progression back to the tonic. I would analyse the chord sequence (in the guitar at the beginning, which is a bit more revealing) as i - VI - IIIc - VII i7d - i - VI - IIIc - VII V.
Second, in the bass line, dominant to tonic is a very strong sequence to establish a tonal centre, so looking for F# - B or A - D progression at a cadence will also be helpful. Thinking of the *end* of the song now, we have the bassline
B - G - D - A - B - G - D - **F# - B**
For both of these reasons I'd say that the song is unambiguously in B minor. | The answer to your question is **yes**.
The notation you use is relative to tonic. Establishing which sound is the tonic (and whether it changes) is completely outside of this tool. Consider anything noted as II-V as carrying a standard disclaimer "assuming that X is the tonic".
If you have a song with chords: C F C F C F, it might be a I-IV-I-IV, it might be a V-I-V-I. Depends on the rhythm, melody and even the listener. You can "make" yourself hear different tonics for the same progression in a similar way you can make yourself hear different "1" in a repeated drum loop.
There's some modern research concerning this, the classical theory just assumed that all people have roughly the same musical background and follow the same convention. |
Question: quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :(
Answer: | A complete song need not be just in one key, and stay in that key throughout. I guess that's one good thing about relative key signatures - they are identical.
There are many songs which may be in relative major for the verse, and move to relative minor for the chorus - or vice versa. There are many songs which move between the two relatives *during* the verse/chorus.
Often a telling clue is the dominant harmony - but not always. In the relative minor, often its dominant will use a 'proper' leading note - let's take key C/Am. In key C there's a G note, whereas in key Am, that often gets changed to G♯ - the leading note of *that* key, but not actually part of the diatonic set of notes making up C major. There again, that may just be a move to modulate for a short time *to* the relative minor, or even just to get to a bar or two where Am fits best.
Most pieces have a **tonal centre**, which feels to most like 'home'. This is usually the clue to the piece's key. Does it feel like it can stop at that bar, and be at rest, finished? In a piece such as you proffer, which sounds most like 'at home'? As mentioned in the previous para., a perfect cadence will usually offer the best clue.
Incidentally, *major* chords are written using capital RN, *minors* use lower case.
And with some pieces, it's (almost!) impossible to say what the key is!
Sweet Home Alabama, Unforgettable and Fly me to the Moon come immediately to mind. Maybe someone can convince everyone which key is accurately the 'correct' one for each! But does it *really* matter?
EDIT: to directly answer what I think is the question - let's take a sequence vi, IV, I, V. That could also be written in relative minor as i, VI, III, VII. In any given key, that sequence will be the same chords - e.g. in key C - Am, F, C, G. | The answer lies in which chord is used to finish the piece (or section thereof.) If a piece ends with V-I (with I being D major and V being A major for example), one would say that that section (or piece) is in D major. To end a piece in the relative minor (same key signature but that's just for notational convenience and not universally used during the Baroque), one would have V-i with i being a b minor chord and V being F# major. (The V chords could be V7s without changing the analysis.)
Try playing A7-D or A-D then F#7-b or F#-b and listen to the difference. This applies to Common Practice Period harmony (which is still commonly used) where the chord on the dominant is a major (even if needing an accidental) in a cadence. (A almost said accidentally major....) |
Question: quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :(
Answer: | The scale/chords are good clues to the key of a song, but at least as important is the *tonal center*. That's not as easy to define but generally it's where the song comes back to a place of less musical tension.
IMHO the chord played when the song in question returns to a "rest" state is A major. Which means I would say the song is in A and the progression is ii - bVII - IV - I. That would suggest that the scale is actually A mixolydian (not pure major or minor), which is not unusual for rock.
The point is that the key of a song is not only about the scale. Learning to hear the tonal center is sometimes more important. | As others have pointed out, whether a song is in a major key or its relative minor is often a matter of debate or opinion. However, there are some clues that can point in one or other direction.
First, in specifically the *harmonic* minor there is a key difference, the raised leading note: thus here you would expect an A# in B minor but it would be difficult to explain in D major. Assuming that I've got the right song (["Take Me Home" by Avicii](https://www.youtube.com/watch?v=IcrbM1l_BoI)), there is an A# on the last beat of the bar every second time the chord sequence repeats, making a V-i progression back to the tonic. I would analyse the chord sequence (in the guitar at the beginning, which is a bit more revealing) as i - VI - IIIc - VII i7d - i - VI - IIIc - VII V.
Second, in the bass line, dominant to tonic is a very strong sequence to establish a tonal centre, so looking for F# - B or A - D progression at a cadence will also be helpful. Thinking of the *end* of the song now, we have the bassline
B - G - D - A - B - G - D - **F# - B**
For both of these reasons I'd say that the song is unambiguously in B minor. |
Question: quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :(
Answer: | The answer lies in which chord is used to finish the piece (or section thereof.) If a piece ends with V-I (with I being D major and V being A major for example), one would say that that section (or piece) is in D major. To end a piece in the relative minor (same key signature but that's just for notational convenience and not universally used during the Baroque), one would have V-i with i being a b minor chord and V being F# major. (The V chords could be V7s without changing the analysis.)
Try playing A7-D or A-D then F#7-b or F#-b and listen to the difference. This applies to Common Practice Period harmony (which is still commonly used) where the chord on the dominant is a major (even if needing an accidental) in a cadence. (A almost said accidentally major....) | As others have pointed out, whether a song is in a major key or its relative minor is often a matter of debate or opinion. However, there are some clues that can point in one or other direction.
First, in specifically the *harmonic* minor there is a key difference, the raised leading note: thus here you would expect an A# in B minor but it would be difficult to explain in D major. Assuming that I've got the right song (["Take Me Home" by Avicii](https://www.youtube.com/watch?v=IcrbM1l_BoI)), there is an A# on the last beat of the bar every second time the chord sequence repeats, making a V-i progression back to the tonic. I would analyse the chord sequence (in the guitar at the beginning, which is a bit more revealing) as i - VI - IIIc - VII i7d - i - VI - IIIc - VII V.
Second, in the bass line, dominant to tonic is a very strong sequence to establish a tonal centre, so looking for F# - B or A - D progression at a cadence will also be helpful. Thinking of the *end* of the song now, we have the bassline
B - G - D - A - B - G - D - **F# - B**
For both of these reasons I'd say that the song is unambiguously in B minor. |
Question: quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :(
Answer: | The scale/chords are good clues to the key of a song, but at least as important is the *tonal center*. That's not as easy to define but generally it's where the song comes back to a place of less musical tension.
IMHO the chord played when the song in question returns to a "rest" state is A major. Which means I would say the song is in A and the progression is ii - bVII - IV - I. That would suggest that the scale is actually A mixolydian (not pure major or minor), which is not unusual for rock.
The point is that the key of a song is not only about the scale. Learning to hear the tonal center is sometimes more important. | The problem goes away if you consider D and Bm to be two sides of the same key. They have the same key signature. The Roman numeral analysis system - in the form you talk about - assumes that either the major or minor side is clearly more prominent, in order to assign number one to a scale degree. You should make a decision: do you want to subscribe to this idea of two possible "ones", or normalize the situation and have the major side's tonic be number I always, even for tunes that are "in minor". Who cares about the numbers? You know where D and B are, what notes are in the default scale specified by the key signature, and how to play the song, isn't that enough?
The tonal center can sway back and forth in a song, and it's often more or less ambiguous. It can even feel like moving completely outside the original major and minor side tonics, and then we talk about a potential modulation. Insisting on moving the number one around all the time is useless IMO. The whole Roman numeral thing and functional harmony is a simplified model for harmony exercises and theory classes. Just a tool to get a perspective on a static harmonic snapshot. But real music isn't so clear and static, it moves and morphs around. |
Question: quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :(
Answer: | A complete song need not be just in one key, and stay in that key throughout. I guess that's one good thing about relative key signatures - they are identical.
There are many songs which may be in relative major for the verse, and move to relative minor for the chorus - or vice versa. There are many songs which move between the two relatives *during* the verse/chorus.
Often a telling clue is the dominant harmony - but not always. In the relative minor, often its dominant will use a 'proper' leading note - let's take key C/Am. In key C there's a G note, whereas in key Am, that often gets changed to G♯ - the leading note of *that* key, but not actually part of the diatonic set of notes making up C major. There again, that may just be a move to modulate for a short time *to* the relative minor, or even just to get to a bar or two where Am fits best.
Most pieces have a **tonal centre**, which feels to most like 'home'. This is usually the clue to the piece's key. Does it feel like it can stop at that bar, and be at rest, finished? In a piece such as you proffer, which sounds most like 'at home'? As mentioned in the previous para., a perfect cadence will usually offer the best clue.
Incidentally, *major* chords are written using capital RN, *minors* use lower case.
And with some pieces, it's (almost!) impossible to say what the key is!
Sweet Home Alabama, Unforgettable and Fly me to the Moon come immediately to mind. Maybe someone can convince everyone which key is accurately the 'correct' one for each! But does it *really* matter?
EDIT: to directly answer what I think is the question - let's take a sequence vi, IV, I, V. That could also be written in relative minor as i, VI, III, VII. In any given key, that sequence will be the same chords - e.g. in key C - Am, F, C, G. | The problem goes away if you consider D and Bm to be two sides of the same key. They have the same key signature. The Roman numeral analysis system - in the form you talk about - assumes that either the major or minor side is clearly more prominent, in order to assign number one to a scale degree. You should make a decision: do you want to subscribe to this idea of two possible "ones", or normalize the situation and have the major side's tonic be number I always, even for tunes that are "in minor". Who cares about the numbers? You know where D and B are, what notes are in the default scale specified by the key signature, and how to play the song, isn't that enough?
The tonal center can sway back and forth in a song, and it's often more or less ambiguous. It can even feel like moving completely outside the original major and minor side tonics, and then we talk about a potential modulation. Insisting on moving the number one around all the time is useless IMO. The whole Roman numeral thing and functional harmony is a simplified model for harmony exercises and theory classes. Just a tool to get a perspective on a static harmonic snapshot. But real music isn't so clear and static, it moves and morphs around. |
Question: On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad.
Answer: | Windows can be installed on a different harddrive and or in a different folder. Use the %windir% or %systemroot% environment variables to get you to the windows folder and append system32. Or use the %path% variable, it's usually the first entrance and the preferred method of searching for files such as dlls AFAIK. As per comments: don't rely too much on the system32 dir being the first item. I do think it's safe to assume it's in %path% somewhere though. | Just an FYI, but in a Terminal Server environment (ie, Citrix), GetWindowsDirectory() may return a unique path for a remote user.
[link text](http://msdn.microsoft.com/en-us/library/ms724454(VS.85).aspx)
As more and more companies use virtualized desktops, developers need to keep this in mind. |
Question: On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad.
Answer: | You definitely cannot assume that: Windows could be installed on a different drive letter, or in a different directory. On a previous work PC Windows was installed in D:\WINNT, for example.
The short answer is to use the API call GetSystemDirectory(), which will return the path you are after.
The longer answer is to ask: do you really need to know this? If you're using it to copy files into the Windows directory, I'd suggest you ask if you really want to do this. Copying into the Windows directory is not encouraged, as you can mess up other applications very easily. If you're using the path to find DLLs, why not just rely on the OS to find the appropriate one without giving a path? If you're digging into bits of the OS files, consider: is that going to work in future? In general it's better to not explicitly poke around in the Windows directory if you want your program to work on future Windows versions. | Windows can be installed on a different harddrive and or in a different folder. Use the %windir% or %systemroot% environment variables to get you to the windows folder and append system32. Or use the %path% variable, it's usually the first entrance and the preferred method of searching for files such as dlls AFAIK. As per comments: don't rely too much on the system32 dir being the first item. I do think it's safe to assume it's in %path% somewhere though. |
Question: On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad.
Answer: | Windows can be installed on a different harddrive and or in a different folder. Use the %windir% or %systemroot% environment variables to get you to the windows folder and append system32. Or use the %path% variable, it's usually the first entrance and the preferred method of searching for files such as dlls AFAIK. As per comments: don't rely too much on the system32 dir being the first item. I do think it's safe to assume it's in %path% somewhere though. | I would use the **GetWindowsDirectory** Win32 API to get the current Windows directory, append **System32** to it an then check if it exists. |
Question: On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad.
Answer: | You definitely cannot assume that: Windows could be installed on a different drive letter, or in a different directory. On a previous work PC Windows was installed in D:\WINNT, for example.
The short answer is to use the API call GetSystemDirectory(), which will return the path you are after.
The longer answer is to ask: do you really need to know this? If you're using it to copy files into the Windows directory, I'd suggest you ask if you really want to do this. Copying into the Windows directory is not encouraged, as you can mess up other applications very easily. If you're using the path to find DLLs, why not just rely on the OS to find the appropriate one without giving a path? If you're digging into bits of the OS files, consider: is that going to work in future? In general it's better to not explicitly poke around in the Windows directory if you want your program to work on future Windows versions. | No, you can't assume that.
Windows can be installed to a different path. One solution is to look for it by calling GetSystemDirectory (implemented as part of the Windows API). |
Question: On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad.
Answer: | Windows can be installed on a different harddrive and or in a different folder. Use the %windir% or %systemroot% environment variables to get you to the windows folder and append system32. Or use the %path% variable, it's usually the first entrance and the preferred method of searching for files such as dlls AFAIK. As per comments: don't rely too much on the system32 dir being the first item. I do think it's safe to assume it's in %path% somewhere though. | It might be safer to use the "windir" environment variable and then append the "System32" to the end of that path. Sometimes windows could be under a different folder or different drive so "windir" will tell you where it is.
As far as i know, the system32 folder should always exist under the windows folder. |
Question: On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad.
Answer: | You definitely cannot assume that: Windows could be installed on a different drive letter, or in a different directory. On a previous work PC Windows was installed in D:\WINNT, for example.
The short answer is to use the API call GetSystemDirectory(), which will return the path you are after.
The longer answer is to ask: do you really need to know this? If you're using it to copy files into the Windows directory, I'd suggest you ask if you really want to do this. Copying into the Windows directory is not encouraged, as you can mess up other applications very easily. If you're using the path to find DLLs, why not just rely on the OS to find the appropriate one without giving a path? If you're digging into bits of the OS files, consider: is that going to work in future? In general it's better to not explicitly poke around in the Windows directory if you want your program to work on future Windows versions. | I would use the **GetWindowsDirectory** Win32 API to get the current Windows directory, append **System32** to it an then check if it exists. |
Question: On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad.
Answer: | No, you can't assume that.
Windows can be installed to a different path. One solution is to look for it by calling GetSystemDirectory (implemented as part of the Windows API). | I would use the **GetWindowsDirectory** Win32 API to get the current Windows directory, append **System32** to it an then check if it exists. |
Question: On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad.
Answer: | You definitely cannot assume that: Windows could be installed on a different drive letter, or in a different directory. On a previous work PC Windows was installed in D:\WINNT, for example.
The short answer is to use the API call GetSystemDirectory(), which will return the path you are after.
The longer answer is to ask: do you really need to know this? If you're using it to copy files into the Windows directory, I'd suggest you ask if you really want to do this. Copying into the Windows directory is not encouraged, as you can mess up other applications very easily. If you're using the path to find DLLs, why not just rely on the OS to find the appropriate one without giving a path? If you're digging into bits of the OS files, consider: is that going to work in future? In general it's better to not explicitly poke around in the Windows directory if you want your program to work on future Windows versions. | Just an FYI, but in a Terminal Server environment (ie, Citrix), GetWindowsDirectory() may return a unique path for a remote user.
[link text](http://msdn.microsoft.com/en-us/library/ms724454(VS.85).aspx)
As more and more companies use virtualized desktops, developers need to keep this in mind. |
Question: On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad.
Answer: | No, you can't assume that.
Windows can be installed to a different path. One solution is to look for it by calling GetSystemDirectory (implemented as part of the Windows API). | It might be safer to use the "windir" environment variable and then append the "System32" to the end of that path. Sometimes windows could be under a different folder or different drive so "windir" will tell you where it is.
As far as i know, the system32 folder should always exist under the windows folder. |
Question: On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad.
Answer: | No, you can't assume that.
Windows can be installed to a different path. One solution is to look for it by calling GetSystemDirectory (implemented as part of the Windows API). | Just an FYI, but in a Terminal Server environment (ie, Citrix), GetWindowsDirectory() may return a unique path for a remote user.
[link text](http://msdn.microsoft.com/en-us/library/ms724454(VS.85).aspx)
As more and more companies use virtualized desktops, developers need to keep this in mind. |
Question: I have a requirement where in the function takes different parameters and returns unique objects. All these functions perform the same operation.
ie.
```
public returnObject1 myfunction( paramObject1 a, int a) {
returnObject1 = new returnObject1();
returnObject1.a = paramObject1.a;
return returnObject1;
}
public returnOject2 myfunction( paramObject2 a, int a){
returnObject2 = new returnObject2();
returnObject2.a = paramObject2.a;
return returnObject2;
}
```
As you can see above, both the function do the same task but they take different parameters as input and return different objects.
I would like to minimize writing different functions that does the same task.
Is it possible to write a generic method for this that can substitute the parameters based on the call to the function?
paramObject and returnObject are basically two classes that have different variables. They are not related to each other.
My objective is that I do not want to do function overloading since the functions do almost the same work. I would like to have a single function that can handle different input and different return output.
my aim is to do something like this (if possible):
```
public static < E > myfunction( T a, int a ) {
// do work
}
```
The return type E and the input T can keep varying.
Answer: | Make `interface Foo` and implement this `interface` in both `paramObject1` and `paramObject2` class. Now your method should be look like:
```
public Foo myFunction(Foo foo, int a){
//Rest of the code.
return foo;
}
``` | you can using the 3rd `apply` method to remove the code duplications, you separate creation & initialization from the `apply` method in this approach. and don't care about which type of `T` is used. for example:
```
returnObject1 myfunction(paramObject1 a, int b) {
return apply(returnObject1::new, b, value -> {
//uses paramObject1
//populates returnObject1
//for example:
value.foo = a.bar;
});
}
returnOject2 myfunction(paramObject2 a, int b) {
return apply(returnOject2::new, b, value -> {
//uses paramObject2
//populates returnObject2
//for example:
value.key = a.value;
});
}
<T> T apply(Supplier<T> factory, int b, Consumer<T> initializer) {
T value = factory.get();
initializer.accept(value);
//does work ...
return value;
}
```
*Note* the 2 `myfunction` is optional, you can remove them from you source code, and call the `apply` method directly, for example:
```
paramObject2 a = ...;
returnObject2 result = apply(returnOject2::new, 2, value -> {
//for example:
value.key = a.value;
});
``` |
Question: Does anyone know if its possible to add specific files uncompressed to a Android APK file during the ANT build process using build.xml? All my files live in the *assets* folder and use the same extension. I do realise that i could use a different extension for the files that i don't want to be added compressed and specify, for example:
```
<nocompress extension="NoCompress" />
```
but this currently isn't an option for me.
I tried adding my own *aapt add* step after the *appt package* step in the *package-resource* section in *build.xml*:
```
<exec executable="${aapt}" taskName="add">
<arg value="add" />
<arg value="-v" />
<arg value="${out.absolute.dir}/TestAndroid.ap_" />
<arg value="${asset.absolute.dir}/notcompressed.and" />
</exec>
```
Which did add the file to the APK but it was compressed. :)
Is this possible or is a different extension the only way?
Thanks!
Answer: | Have a look [here](http://ponystyle.com/blog/2010/03/26/dealing-with-asset-compression-in-android-apps/)
>
> The only way (that I’ve discovered, as of this writing) to control
> this behavior is by using the -0 (zero) flag to aapt on the command
> line. This flag, passed without any accompanying argument, will tell
> aapt to disable compression for all types of assets. Typically you
> will not want to use this exact option, because for most assets,
> compression is a desirable thing. Sometimes, however, you will have a
> specific type of asset (say, a database), that you do not want to
> apply compression to. In this case, you have two options.
>
>
> First, you can give your asset file an extension in the list above.
> While this does not necessarily make sense, it can be an easy
> workaround if you don’t want to deal with aapt on the command line.
> The other option is to pass a specific extension to the -0 flag, such
> as -0 db, to disable compression for assets with that extension. You
> can pass the -0 flag multiple times, and each time with a separate
> extension, if you need more than one type to be uncompressed.
>
>
> Currently, there is no way to pass these extra flags to aapt when
> using the ADT within Eclipse, so if you don’t want to sacrifice the
> ease of use of the GUI tools, you will have to go with the first
> option, and rename your file’s extension.
>
>
> | Just to provide closure for this one.
I don't think it is possible to mark individual files to be added uncompressed to the APK.
Being able to mark individual files as uncompressed to *aapt* could be useful. As would the addition of a *nocompress file* tag, eg:
```
<nocompress file="FileNoCompress.abc" />
```
:) |
Question: Does anyone know if its possible to add specific files uncompressed to a Android APK file during the ANT build process using build.xml? All my files live in the *assets* folder and use the same extension. I do realise that i could use a different extension for the files that i don't want to be added compressed and specify, for example:
```
<nocompress extension="NoCompress" />
```
but this currently isn't an option for me.
I tried adding my own *aapt add* step after the *appt package* step in the *package-resource* section in *build.xml*:
```
<exec executable="${aapt}" taskName="add">
<arg value="add" />
<arg value="-v" />
<arg value="${out.absolute.dir}/TestAndroid.ap_" />
<arg value="${asset.absolute.dir}/notcompressed.and" />
</exec>
```
Which did add the file to the APK but it was compressed. :)
Is this possible or is a different extension the only way?
Thanks!
Answer: | If building using gradle, then it seems you can provide the aapt flags like this:
```
android {
aaptOptions {
noCompress 'foo', 'bar'
ignoreAssetsPattern "!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"
}
}
```
<http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-aapt-options> | Just to provide closure for this one.
I don't think it is possible to mark individual files to be added uncompressed to the APK.
Being able to mark individual files as uncompressed to *aapt* could be useful. As would the addition of a *nocompress file* tag, eg:
```
<nocompress file="FileNoCompress.abc" />
```
:) |
Question: I have **two tables** for one is `category` and another one is `sub-category`. that two table is assigned to `FK` for many table. In some situation we will move one record of **sub-category** to **main category**. so this time occur constraints error because that **key** associated with other table. so i would not create this **schema**.
so now i plan to **create category** and **sub-category** in same table and **create relationship table** to make relationship between them.
`category table:`
```
id(PK,AUTO Increment),
item===>((1,phone),(2.computer),(3,ios),(4,android),(5,software),(6,hardware)).
```
`relationship table:`
```
id,cate_id(FK),
parentid(refer from category table)===>((1,1,0),(2,2,0),(3,3,1),
(4,4,1),(5,5,2),(5,5,3)).
```
in my side wouldnot go hierarchy level more than three.
if we easily move to subcategory to main category `ex:(4,4,1) to (4,4,0)` without affect any other table. is this good procedure?
if we will maintain millions record, will we face any other problem in future?
have any another idea means let me know?
Answer: | There might be a problem if you have multiple levels in the tree, and want to find all the subcategories of any category. This would require either multiple queries, or a recursive one.
You could instead look into the ["Nested Sets"](http://www.codeproject.com/Articles/4155/Improve-hierarchy-performance-using-nested-sets) data-structure. It supports effective querying of any sub-tree. It does have a costly update, but updates probably won't happen very often. If need be, you could batch the updates and run them over night.
```
create table Category (
Id int not null primary key auto_increment,
LeftExtent int not null,
RightExtent int not null,
Name varchar(100) not null
);
create table PendingCategoryUpdate (
Id int not null primary key auto_increment,
ParentCategoryId int null references Category ( Id ),
ParentPendingId int null references PendingCategoryUpdate ( Id ),
Name varchar(100) not null
);
```
---
If you have a small number of categories, a normal parent reference should be enough. You could even read the categories into memory for processing.
```
create table Category (
Id int not null primary key auto_increment,
ParentId int null references Category ( Id ),
Name varchar(100) not null
);
-- Just an example
create table Record (
Id int not null primary key auto_increment,
CategoryId int not null references Category ( Id )
);
select *
from Record
where CategoryId in (1, 2, 3); -- All the categories in the chosen sub-tree
``` | How about creating one table as following:
```
categories(
id int not null auto_increment primary key,
name char(10),
parent_id int not null default 0)
```
Where parent\_id is a FK to the id, which is the PK of the table.
When parent\_id is 0, then this category is a main one. When it is > 0, this is a sub category of this parent.
To find the parent of a category, you will do self-join. |
Question: I'm trying to write what must be the simplest angular directive which displays a Yes/No select list and is bound to a model containing a boolean value. Unfortunately the existing value is never preselected. My directive reads
```
return {
restrict: 'E',
replace: true,
template: '<select class="form-control"><option value="true">Yes</option><option value="false">No</option></select>',
scope: {
ngModel: '='
}
}
```
and I am calling the directive as
```
<yesno ng-model="brand.is_anchor"></yesno>
```
The select options display and the generated HTML reads as
```
<select class="form-control ng-isolate-scope ng-valid" ng-model="brand.is_anchor">
<option value="? boolean:false ?"></option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
```
The initial value of the bound model is "false" but it always displays an empty option and per the first option listed in the generated HTML.
Can anybody please advise?
Answer: | There is no need for a custom sentinel image, or messing with the network. See my [redis-ha-learning](https://github.com/asarkar/spring/tree/master/redis-ha-learning) project using [Spring Data Redis](https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#reference), [bitnami/redis](https://hub.docker.com/r/bitnami/redis) and [bitnami/redis-sentinel](https://hub.docker.com/r/bitnami/redis-sentinel) images. The Docker Compose file is [here](https://github.com/asarkar/spring/blob/master/redis-ha-learning/redis-sentinel.yaml).
My code auto detects the sentinels based on the Docker Compose container names. | So, the solution that worked for me is simply reading the /etc/hosts file on the source container. I busy wait till the link is established and then use that network interface IP to start the sentinel process. This is just a stop gap solution and it is not scalable. Redis-sentinel is still not production ready in dockerizable format as confirmed in this [post](https://stackoverflow.com/questions/25914814/redis-sentinel-docker-image-dockerfile%20post). So I decided to install Redis/sentinel on the physical hosts. |
Question: I'm trying to write what must be the simplest angular directive which displays a Yes/No select list and is bound to a model containing a boolean value. Unfortunately the existing value is never preselected. My directive reads
```
return {
restrict: 'E',
replace: true,
template: '<select class="form-control"><option value="true">Yes</option><option value="false">No</option></select>',
scope: {
ngModel: '='
}
}
```
and I am calling the directive as
```
<yesno ng-model="brand.is_anchor"></yesno>
```
The select options display and the generated HTML reads as
```
<select class="form-control ng-isolate-scope ng-valid" ng-model="brand.is_anchor">
<option value="? boolean:false ?"></option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
```
The initial value of the bound model is "false" but it always displays an empty option and per the first option listed in the generated HTML.
Can anybody please advise?
Answer: | I have this configuration example here using docker compose that can be of help.
<https://github.com/oneyottabyte/redis_sentinel> | So, the solution that worked for me is simply reading the /etc/hosts file on the source container. I busy wait till the link is established and then use that network interface IP to start the sentinel process. This is just a stop gap solution and it is not scalable. Redis-sentinel is still not production ready in dockerizable format as confirmed in this [post](https://stackoverflow.com/questions/25914814/redis-sentinel-docker-image-dockerfile%20post). So I decided to install Redis/sentinel on the physical hosts. |
Question: ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help.
Answer: | Let $V$ be the volume of the hanging block, $A$ the area of the water surface, $\rho$ the density of water, and $g$ the acceleration due to gravity.
The extra hydrostatic force felt by the bottom of the container after lowering the block is
$$\Delta F = \rho gA\Delta h,$$
where $\Delta h$ is the change in water height ($\rho g \Delta h$ would be the change in hydrostatic pressure). Because water is not compressible, $A\Delta h$ must be the volume of the submerged block.
$$\Delta F = \rho g V.$$
Notice that this is exactly equal to the buoyant force on the block, so the two new forces created after the block is submerged negate each other. | EDIT:
-----
Since this answer is not being very well received I will just say that *if* we neglect gravitational forces due to the height difference between the mass in the upper and lower pictures; then yes, the scales *will* be balanced as there is simply no net torque.
---
However, since the question did **not** stipulate these assumptions then the answer below is the correct one:
Look at the RHS of the scale and consider Newton's Law of Gravitation $$F=-\frac{G \cdot m\cdot m\_E}{d^2}$$ On the RHS consider $m$ to be the mass of block suspended by the string and $m\_E$ is the mass of the Earth $\approx 6\times 10^{24}$kg. $G$ is the gravitational constant and $d$ is the distance of the string between the block in the top picture and the one in the bottom *plus* the distance to the centre of the earth.
Now let $m\_{s}$ be the mass of the submerged block in the container of the lower RHS and $d\_E$ is the distance to the centre of the earth.
$$F=-\frac{G \cdot m\_{s}\cdot m\_E}{d\_E^2}$$
The gravitational force acting on the RHS of lower system is therefore greater by Newton's inverse square law.
Can you now understand why once the block is dropped into the fluid the RHS of the lower image will weigh more and hence tilt clockwise? |
Question: ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help.
Answer: | **The scale will not move.**
You don't need to think about buoyancy at all to answer this question. In the first picture, the scale is balanced, because the net force on each side (the weight) is equal. No mass is added to or removed from either side, so the net forces remain the same. | So various forces neglected (including gravity, air resistance, thermal forces, air pressure) - but your question suggest this is an inquiry about the effect of bouyancy.
That being the case, lowering the mass into the water brings into effect its bouyancy. This is a force lifting the mass and acting down on the water.
However, as the mass is tethered to the scale the force acting down the string is reduced by the same amount as the bouyancy, and the net effect on the scale is zero.
(Also neglecting rotating frames of reference, light pressure, stress and young's modulus, magnetically induce currents etc) |
Question: ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help.
Answer: | So various forces neglected (including gravity, air resistance, thermal forces, air pressure) - but your question suggest this is an inquiry about the effect of bouyancy.
That being the case, lowering the mass into the water brings into effect its bouyancy. This is a force lifting the mass and acting down on the water.
However, as the mass is tethered to the scale the force acting down the string is reduced by the same amount as the bouyancy, and the net effect on the scale is zero.
(Also neglecting rotating frames of reference, light pressure, stress and young's modulus, magnetically induce currents etc) | Let $V$ be the volume of the hanging block, $A$ the area of the water surface, $\rho$ the density of water, and $g$ the acceleration due to gravity.
The extra hydrostatic force felt by the bottom of the container after lowering the block is
$$\Delta F = \rho gA\Delta h,$$
where $\Delta h$ is the change in water height ($\rho g \Delta h$ would be the change in hydrostatic pressure). Because water is not compressible, $A\Delta h$ must be the volume of the submerged block.
$$\Delta F = \rho g V.$$
Notice that this is exactly equal to the buoyant force on the block, so the two new forces created after the block is submerged negate each other. |
Question: ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help.
Answer: | So various forces neglected (including gravity, air resistance, thermal forces, air pressure) - but your question suggest this is an inquiry about the effect of bouyancy.
That being the case, lowering the mass into the water brings into effect its bouyancy. This is a force lifting the mass and acting down on the water.
However, as the mass is tethered to the scale the force acting down the string is reduced by the same amount as the bouyancy, and the net effect on the scale is zero.
(Also neglecting rotating frames of reference, light pressure, stress and young's modulus, magnetically induce currents etc) | EDIT:
-----
Since this answer is not being very well received I will just say that *if* we neglect gravitational forces due to the height difference between the mass in the upper and lower pictures; then yes, the scales *will* be balanced as there is simply no net torque.
---
However, since the question did **not** stipulate these assumptions then the answer below is the correct one:
Look at the RHS of the scale and consider Newton's Law of Gravitation $$F=-\frac{G \cdot m\cdot m\_E}{d^2}$$ On the RHS consider $m$ to be the mass of block suspended by the string and $m\_E$ is the mass of the Earth $\approx 6\times 10^{24}$kg. $G$ is the gravitational constant and $d$ is the distance of the string between the block in the top picture and the one in the bottom *plus* the distance to the centre of the earth.
Now let $m\_{s}$ be the mass of the submerged block in the container of the lower RHS and $d\_E$ is the distance to the centre of the earth.
$$F=-\frac{G \cdot m\_{s}\cdot m\_E}{d\_E^2}$$
The gravitational force acting on the RHS of lower system is therefore greater by Newton's inverse square law.
Can you now understand why once the block is dropped into the fluid the RHS of the lower image will weigh more and hence tilt clockwise? |
Question: ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help.
Answer: | **The scale will not move.**
You don't need to think about buoyancy at all to answer this question. In the first picture, the scale is balanced, because the net force on each side (the weight) is equal. No mass is added to or removed from either side, so the net forces remain the same. | EDIT:
-----
Since this answer is not being very well received I will just say that *if* we neglect gravitational forces due to the height difference between the mass in the upper and lower pictures; then yes, the scales *will* be balanced as there is simply no net torque.
---
However, since the question did **not** stipulate these assumptions then the answer below is the correct one:
Look at the RHS of the scale and consider Newton's Law of Gravitation $$F=-\frac{G \cdot m\cdot m\_E}{d^2}$$ On the RHS consider $m$ to be the mass of block suspended by the string and $m\_E$ is the mass of the Earth $\approx 6\times 10^{24}$kg. $G$ is the gravitational constant and $d$ is the distance of the string between the block in the top picture and the one in the bottom *plus* the distance to the centre of the earth.
Now let $m\_{s}$ be the mass of the submerged block in the container of the lower RHS and $d\_E$ is the distance to the centre of the earth.
$$F=-\frac{G \cdot m\_{s}\cdot m\_E}{d\_E^2}$$
The gravitational force acting on the RHS of lower system is therefore greater by Newton's inverse square law.
Can you now understand why once the block is dropped into the fluid the RHS of the lower image will weigh more and hence tilt clockwise? |
Question: ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help.
Answer: | If you consider everything put in the right side of balance scale as one system, only the internal forces are changed which will not affect the balance.
No external force is applied and hence the balance will be maintained. | Let $V$ be the volume of the hanging block, $A$ the area of the water surface, $\rho$ the density of water, and $g$ the acceleration due to gravity.
The extra hydrostatic force felt by the bottom of the container after lowering the block is
$$\Delta F = \rho gA\Delta h,$$
where $\Delta h$ is the change in water height ($\rho g \Delta h$ would be the change in hydrostatic pressure). Because water is not compressible, $A\Delta h$ must be the volume of the submerged block.
$$\Delta F = \rho g V.$$
Notice that this is exactly equal to the buoyant force on the block, so the two new forces created after the block is submerged negate each other. |
Question: ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help.
Answer: | The balance will be maintained because there is no EXTERNAL force applied on left or right side. This is because of the same reason you can't push a car while sitting in it! | So various forces neglected (including gravity, air resistance, thermal forces, air pressure) - but your question suggest this is an inquiry about the effect of bouyancy.
That being the case, lowering the mass into the water brings into effect its bouyancy. This is a force lifting the mass and acting down on the water.
However, as the mass is tethered to the scale the force acting down the string is reduced by the same amount as the bouyancy, and the net effect on the scale is zero.
(Also neglecting rotating frames of reference, light pressure, stress and young's modulus, magnetically induce currents etc) |
Question: ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help.
Answer: | The balance will be maintained because there is no EXTERNAL force applied on left or right side. This is because of the same reason you can't push a car while sitting in it! | EDIT:
-----
Since this answer is not being very well received I will just say that *if* we neglect gravitational forces due to the height difference between the mass in the upper and lower pictures; then yes, the scales *will* be balanced as there is simply no net torque.
---
However, since the question did **not** stipulate these assumptions then the answer below is the correct one:
Look at the RHS of the scale and consider Newton's Law of Gravitation $$F=-\frac{G \cdot m\cdot m\_E}{d^2}$$ On the RHS consider $m$ to be the mass of block suspended by the string and $m\_E$ is the mass of the Earth $\approx 6\times 10^{24}$kg. $G$ is the gravitational constant and $d$ is the distance of the string between the block in the top picture and the one in the bottom *plus* the distance to the centre of the earth.
Now let $m\_{s}$ be the mass of the submerged block in the container of the lower RHS and $d\_E$ is the distance to the centre of the earth.
$$F=-\frac{G \cdot m\_{s}\cdot m\_E}{d\_E^2}$$
The gravitational force acting on the RHS of lower system is therefore greater by Newton's inverse square law.
Can you now understand why once the block is dropped into the fluid the RHS of the lower image will weigh more and hence tilt clockwise? |
Question: ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help.
Answer: | The balance will be maintained because there is no EXTERNAL force applied on left or right side. This is because of the same reason you can't push a car while sitting in it! | If you consider everything put in the right side of balance scale as one system, only the internal forces are changed which will not affect the balance.
No external force is applied and hence the balance will be maintained. |
Question: ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help.
Answer: | The balance will be maintained because there is no EXTERNAL force applied on left or right side. This is because of the same reason you can't push a car while sitting in it! | Let $V$ be the volume of the hanging block, $A$ the area of the water surface, $\rho$ the density of water, and $g$ the acceleration due to gravity.
The extra hydrostatic force felt by the bottom of the container after lowering the block is
$$\Delta F = \rho gA\Delta h,$$
where $\Delta h$ is the change in water height ($\rho g \Delta h$ would be the change in hydrostatic pressure). Because water is not compressible, $A\Delta h$ must be the volume of the submerged block.
$$\Delta F = \rho g V.$$
Notice that this is exactly equal to the buoyant force on the block, so the two new forces created after the block is submerged negate each other. |
Question: i want to find out total number of android APIs (Classes and Methods) used in my android application source code. but i want to do it programmatically. can any one suggest me how can i do so??
Thanks in Advance
Answer: | You can do it with [Reflections API](http://code.google.com/p/reflections/).
You can get the list of classes using the following code :
```
Reflections ref = new Reflections("package_name");
Set<Class<?>> classes = ref.getSubTypesOf(Object.class);
```
Then by using the [Class.getDeclaredMethods()](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getDeclaredMethods%28%29) or [Class.getMethods()](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getMethods%28%29) you can get the list of methods. | The eclipse metrics plugin looks promising. It is not specially designed for android but there's a chance that it will provide you with (most of) the informations you need.
**Reference**
* [project on sourceforge](http://metrics2.sourceforge.net/) |
Question: I have a text as follows.
```
mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday"
```
I want to convert it to lowercase, except the words that has `_ABB` in it.
So, my output should look as follows.
```
mytext = "this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday"
```
My current code is as follows.
```
splits = mytext.split()
newtext = []
for item in splits:
if not '_ABB' in item:
item = item.lower()
newtext.append(item)
else:
newtext.append(item)
```
However, I want to know if there is any easy way of doing this, possibly in one line?
Answer: | You can use a one liner splitting the string into words, check the words with `str.endswith()` and then join the words back together:
```
' '.join(w if w.endswith('_ABB') else w.lower() for w in mytext.split())
# 'this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday'
```
Of course use the `in` operator rather than `str.endswith()` if `'_ABB'` can actually occur anywhere in the word and not just at the end. | Extended *regex* approach:
```
import re
mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday"
result = re.sub(r'\b((?!_ABB)\S)+\b', lambda m: m.group().lower(), mytext)
print(result)
```
The output:
```
this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday
```
---
Details:
* `\b` - word boundary
* `(?!_ABB)` - lookahead negative assertion, ensures that the given pattern will not match
* `\S` - non-whitespace character
* `\b((?!_ABB)\S)+\b` - the whole pattern matches a word NOT containing substring `_ABB` |
Question: I have a text as follows.
```
mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday"
```
I want to convert it to lowercase, except the words that has `_ABB` in it.
So, my output should look as follows.
```
mytext = "this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday"
```
My current code is as follows.
```
splits = mytext.split()
newtext = []
for item in splits:
if not '_ABB' in item:
item = item.lower()
newtext.append(item)
else:
newtext.append(item)
```
However, I want to know if there is any easy way of doing this, possibly in one line?
Answer: | You can use a one liner splitting the string into words, check the words with `str.endswith()` and then join the words back together:
```
' '.join(w if w.endswith('_ABB') else w.lower() for w in mytext.split())
# 'this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday'
```
Of course use the `in` operator rather than `str.endswith()` if `'_ABB'` can actually occur anywhere in the word and not just at the end. | Here is another possible(not elegant) one-liner:
```
mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday"
print(' '.join(map(lambda x : x if '_ABB' in x else x.lower(), mytext.split())))
```
Which Outputs:
```
this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday
```
**Note:** This assumes that your text will only seperate the words by spaces, so `split()` suffices here. If your text includes punctuation such as`",!."`, you will need to use regex instead to split up the words. |
Question: I have a text as follows.
```
mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday"
```
I want to convert it to lowercase, except the words that has `_ABB` in it.
So, my output should look as follows.
```
mytext = "this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday"
```
My current code is as follows.
```
splits = mytext.split()
newtext = []
for item in splits:
if not '_ABB' in item:
item = item.lower()
newtext.append(item)
else:
newtext.append(item)
```
However, I want to know if there is any easy way of doing this, possibly in one line?
Answer: | Extended *regex* approach:
```
import re
mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday"
result = re.sub(r'\b((?!_ABB)\S)+\b', lambda m: m.group().lower(), mytext)
print(result)
```
The output:
```
this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday
```
---
Details:
* `\b` - word boundary
* `(?!_ABB)` - lookahead negative assertion, ensures that the given pattern will not match
* `\S` - non-whitespace character
* `\b((?!_ABB)\S)+\b` - the whole pattern matches a word NOT containing substring `_ABB` | Here is another possible(not elegant) one-liner:
```
mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday"
print(' '.join(map(lambda x : x if '_ABB' in x else x.lower(), mytext.split())))
```
Which Outputs:
```
this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday
```
**Note:** This assumes that your text will only seperate the words by spaces, so `split()` suffices here. If your text includes punctuation such as`",!."`, you will need to use regex instead to split up the words. |
Question: I have a simple table layout, in the one of the row, I have time for sun rise in a text view and I am trying to have sun with purple colour for the row as background. How can I achieve this? I tried creating an image 1000px x 500px with sun and purple background, However, it does not look good on different screen sizes. What is the solution for this?
Here is an image of what I am trying to achieve ![](https://i.imgur.com/rcjhYSE.png)
Answer: | You can set it programmatically by
```
[textField setSecureTextEntry:YES];
```
or in IB (secured checkbox at the bottom)
![enter image description here](https://i.stack.imgur.com/G8u20.png) | You could also try simply implementing your own "secure text field".
Simply create a normal, non-secure text field, and link it's "Editing Changed" action with a method in your view controller.
Then within that method you can take the new characters every time the text is changed, and add them to a private NSString property, and then set the textField's .text property to a string with just asterisks in it (or any other character if you prefer).
**Update:** as noted by *hayesk* below, this solution is no longer ideal, as the introduction of third-party keyboards exposes input on any non-secure text fields to the third-party application, risking them collecting that information, and/or adding it to the autocorrect database. |
Question: I'm using a jsonb field in my Rails application and have installed the [gem attr\_json](https://github.com/jrochkind/attr_json). Is there a way to receive the defined json\_attributes programmatically? With a "normal" rails attribute, I would just do @instance.attribute\_names. But with attr\_json is there any way how to have the json\_attributes returned?
```
class Vehicle < Item
include AttrJson::Record
attr_json :licence_plate, :string, container_attribute: "custom_attributes_indexed"
attr_json :brand, :string, container_attribute: "custom_attributes_indexed"
attr_json :serial_number, :string, container_attribute: "custom_attributes_indexed"
attr_json :inventory_number, :string, container_attribute: "custom_attributes_indexed"
end
```
For this code I would like to do something like @vehicle.json\_attribute\_names and have the following returned
```
["licence_plate", "brand", "serial_number", "inventory_number"]
```
Answer: | I think you should clear your previous model inside loop so you could use this function which is keras.backend.clear\_session().From <https://keras.io/backend/>:
This will be solved your problem. | From a very simplistic point of view, the data is fed in sequentially, which suggests that at the very least, it's possible for the data order to have an effect on the output. If the order doesn't matter, randomization certainly won't hurt. If the order does matter, randomization will help to smooth out those random effects so that they don't become systematic bias. In short, randomization is cheap and never hurts, and will often minimize data-ordering effects.
In other words, when you feed your neural network with different datasets, your model can get biased towards the latest dataset it was trained on.
You should always make sure that your are randomly sampling from all datasets you have. |
Question: As I am writing my first grails webflow I am asking myself if there is anyy tool or script what can visualize the flow?
Result can be a state diagram or some data to render in a graph tool like graphviz.
Answer: | There's no tool around currently that will do this for you I'm afraid. I've implemented something myself before, but this was very simple and was not automated in any way. It was a simple template where the model was a step number:
```
<g:render template="flowVisualiser" model="[step: 2]" />
```
You would have to put this in every view of the webflow, changing the number for whatever step it was. The template itself just had a row of images for each of the steps, and there was some gsp logic in the style of each image so that if the model passed in was step 2 (for instance) or above then this particular image would have opacity 1:
```
<li>
<div class="${step >= 2 ? 'step-completed' : 'step-todo'}">
<img src="${resource(dir:'images',file:'2.png')}" />
<h4>Do this step</h4>
</div>
</li>
...
```
I know it's not fancy and it's a bit of manual labor but it worked just fine for me :) | As far as I know there's only 2 plugin for Grails which do visualization, but only build a class-diagram, They are [Class diagram plugin](http://grails.org/plugin/class-diagram/) and [Create Domain UML](http://www.grails.org/plugin/create-domain-uml).
You can have a look at [this page](http://www.grails.org/plugin/category/all) for a quick review about all current Grails plugin. |
Question: As I am writing my first grails webflow I am asking myself if there is anyy tool or script what can visualize the flow?
Result can be a state diagram or some data to render in a graph tool like graphviz.
Answer: | There's no tool around currently that will do this for you I'm afraid. I've implemented something myself before, but this was very simple and was not automated in any way. It was a simple template where the model was a step number:
```
<g:render template="flowVisualiser" model="[step: 2]" />
```
You would have to put this in every view of the webflow, changing the number for whatever step it was. The template itself just had a row of images for each of the steps, and there was some gsp logic in the style of each image so that if the model passed in was step 2 (for instance) or above then this particular image would have opacity 1:
```
<li>
<div class="${step >= 2 ? 'step-completed' : 'step-todo'}">
<img src="${resource(dir:'images',file:'2.png')}" />
<h4>Do this step</h4>
</div>
</li>
...
```
I know it's not fancy and it's a bit of manual labor but it worked just fine for me :) | probably this could be a solution for all people using intellij: <http://www.slideshare.net/gr8conf/gr8conf-2011-grails-webflow>
Slide 25 |
Question: I want adding background image with css but it did not work.Browser show me a blank page.
my application.css
```
home-body {
background-image: url('/home.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
```
file home.jpg located in a directory /public/home.jpg.
How fix?
Answer: | Please use this code. Use background instead of background-image and make sure that you have inserted the correct image path in url().
```
html, body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.home-body {
background: url('/home.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
``` | very easy like this....
```
.play{
background: url("media_element/play.png") center center no-repeat;
position : absolute;
display:block;
top:20%;
width:50px;
margin:0 auto;
left:0px;
right:0px;
z-index:100
}
``` |
Question: I want adding background image with css but it did not work.Browser show me a blank page.
my application.css
```
home-body {
background-image: url('/home.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
```
file home.jpg located in a directory /public/home.jpg.
How fix?
Answer: | Please use this code. Use background instead of background-image and make sure that you have inserted the correct image path in url().
```
html, body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.home-body {
background: url('/home.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
``` | ```
body {
background-image: url('img-url');
background-size: cover;
background-repeat:no-repeat
}
``` |
Question: I want adding background image with css but it did not work.Browser show me a blank page.
my application.css
```
home-body {
background-image: url('/home.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
```
file home.jpg located in a directory /public/home.jpg.
How fix?
Answer: | If you are using an external CSS file... make sure to link the image file relative to the CSS file. For instance
`-ROOT
-css
-file.css
-background.jpg
-index.html`
you would need:
`background("../background.jpg");`
because ".." takes you up one directory :) | very easy like this....
```
.play{
background: url("media_element/play.png") center center no-repeat;
position : absolute;
display:block;
top:20%;
width:50px;
margin:0 auto;
left:0px;
right:0px;
z-index:100
}
``` |
Question: I want adding background image with css but it did not work.Browser show me a blank page.
my application.css
```
home-body {
background-image: url('/home.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
```
file home.jpg located in a directory /public/home.jpg.
How fix?
Answer: | If you are using an external CSS file... make sure to link the image file relative to the CSS file. For instance
`-ROOT
-css
-file.css
-background.jpg
-index.html`
you would need:
`background("../background.jpg");`
because ".." takes you up one directory :) | ```
body {
background-image: url('img-url');
background-size: cover;
background-repeat:no-repeat
}
``` |
Question: I want adding background image with css but it did not work.Browser show me a blank page.
my application.css
```
home-body {
background-image: url('/home.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
```
file home.jpg located in a directory /public/home.jpg.
How fix?
Answer: | it may be caused by 3 problem
1- home-body is not a tag of html.so it should be id or class name of a tag.so you should use `.home-body` for class name and `#home-body` for id name.
2- you do not address the background image correctly.if you want to make sure, give the url as an absolute path to your image like `http://yoursiteUrl/public/image/image.png`
3- your css file is not loaded on your page.try to make sure it is loaded on your site correctly if it is loaded then the problem is first or the second part mentioned here. | very easy like this....
```
.play{
background: url("media_element/play.png") center center no-repeat;
position : absolute;
display:block;
top:20%;
width:50px;
margin:0 auto;
left:0px;
right:0px;
z-index:100
}
``` |
Question: I want adding background image with css but it did not work.Browser show me a blank page.
my application.css
```
home-body {
background-image: url('/home.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
```
file home.jpg located in a directory /public/home.jpg.
How fix?
Answer: | it may be caused by 3 problem
1- home-body is not a tag of html.so it should be id or class name of a tag.so you should use `.home-body` for class name and `#home-body` for id name.
2- you do not address the background image correctly.if you want to make sure, give the url as an absolute path to your image like `http://yoursiteUrl/public/image/image.png`
3- your css file is not loaded on your page.try to make sure it is loaded on your site correctly if it is loaded then the problem is first or the second part mentioned here. | ```
body {
background-image: url('img-url');
background-size: cover;
background-repeat:no-repeat
}
``` |
Question: I have a vector class that has addition, multiplication, subtraction, division, etc operators. I'm trying to optimize my program (which does a lot of vector operations) and I'm realizing that about 50% of the time spent is in constructing and destructing vectors. I understand that this is because every time I call a non-compound mathematical operator for a vector, a new vector is constructed. Is there a way to prevent this without using compound operators or expanding vector operations?
If I have:
```
Vector a = Vector(x, y, z);
Vector b = Vector(a, b, c);
Vector c = a + b;
```
I can't use += because c is a completely new vector. I know I can speed it up with this:
```
c.x = a.x + b.x;
c.y = a.y + b.y;
c.z = a.z + b.z;
```
but that doesn't seem as clean as just using an operator.
Answer: | >
> I understand that this is because
> every time I call a non-compound
> mathematical operator for a vector, a
> new vector is constructed. Is there a
> way to prevent this without using
> compound operators or expanding vector
> operations?
>
>
>
Well, the nature of adding two things together to produce a third thing *requires* you to construct a third thing...so how is what you're asking even logically possible?
That being said, if you're concerned about the temporaries created by using the addition operator, these may be optimized out by the compiler if your compiler supports return value optimization. Alternatively, if your compiler doesn't support this and you really want to cut back on temporaries but keep the `+` operator, you may want to look into emulating C++0x move semantics, and provide your vector with a rvalue move constructor, which will be invoked when it returns a temporary by value. See the Section titled "Moving Objects" in [this article](http://www.ddj.com/cpp/184403806) for information on implementing move semantics in C++03. Once C++0x comes out, you can just replace these hacks with real move constructors using the `&&` operator for rvalue references. | Make sure you have optimizations turned on and that your compiler is applying [RVO](http://en.wikipedia.org/wiki/Return_value_optimization), which is designed for exactly this situation (but not required to be used). (You may have to use a form of NRVO in your op+ implementation, example below, which helps the compiler recognize and apply RVO.) Also, have you looked at [blitz++](http://www.oonumerics.org/blitz/)?
```
Vector operator+(Vector const& a, Vector const& b) {
Vector nrvo;
// or: Vector nrvo (ctor, parameters, here);
//...
return nrvo;
}
```
---
There are other alternatives too, such as doing an explicit copy and then using op+=, which serves in a situation where RVO doesn't apply:
```
Vector c; // created somewhere else, and we want to assign to it
// instead of create it "in-place" as RVO does
Vector a, b;
// instead of:
//c = a + b
// use:
c = a;
c += b;
```
This can be achieved with [expression templates](http://en.wikipedia.org/wiki/Expression_templates), like blitz++ uses, without changing your syntax from `c = a + b`. |
Question: I have a vector class that has addition, multiplication, subtraction, division, etc operators. I'm trying to optimize my program (which does a lot of vector operations) and I'm realizing that about 50% of the time spent is in constructing and destructing vectors. I understand that this is because every time I call a non-compound mathematical operator for a vector, a new vector is constructed. Is there a way to prevent this without using compound operators or expanding vector operations?
If I have:
```
Vector a = Vector(x, y, z);
Vector b = Vector(a, b, c);
Vector c = a + b;
```
I can't use += because c is a completely new vector. I know I can speed it up with this:
```
c.x = a.x + b.x;
c.y = a.y + b.y;
c.z = a.z + b.z;
```
but that doesn't seem as clean as just using an operator.
Answer: | >
> I understand that this is because
> every time I call a non-compound
> mathematical operator for a vector, a
> new vector is constructed. Is there a
> way to prevent this without using
> compound operators or expanding vector
> operations?
>
>
>
Well, the nature of adding two things together to produce a third thing *requires* you to construct a third thing...so how is what you're asking even logically possible?
That being said, if you're concerned about the temporaries created by using the addition operator, these may be optimized out by the compiler if your compiler supports return value optimization. Alternatively, if your compiler doesn't support this and you really want to cut back on temporaries but keep the `+` operator, you may want to look into emulating C++0x move semantics, and provide your vector with a rvalue move constructor, which will be invoked when it returns a temporary by value. See the Section titled "Moving Objects" in [this article](http://www.ddj.com/cpp/184403806) for information on implementing move semantics in C++03. Once C++0x comes out, you can just replace these hacks with real move constructors using the `&&` operator for rvalue references. | Whoa there. Your code is totally inefficient:
```
Vector a = Vector(x, y, z);
Vector b = Vector(a, b, c);
```
That's just inefficient. What you want to write is
```
Vector a(x, y, z);
Vector b(a, b, c);
``` |
Question: I maintain a set of command line bioinformatics tools which we distribute as source and binaries for Linux, Windows, and OS X. Currently the binary distribution for OS X is just a zip file containing directories for the binaries and the documentation. Our install guide directs the user to unzip the archive, copy the binaries to the desired location, and update their PATH to point to the binaries. That's fine for the command line savvy users, but some users have never heard of /usr/local/bin let alone PATH. We'd love to have an installer that's in more of the OS X idiom.
Creating an application bundle doesn't seem to do the trick because our tools are strictly command line and they'll need a terminal session to use them. It seems like we could have used PackageMaker to create an installer, but that's now deprecated.
Is there a current standard installer for command line tools on OS X, preferably one with CPACK support?
Answer: | The standard package format is the "pkg" format. It's not often used for applications, but it's fine for a terminal-only utility.
* My go-to tool for creating packages is called [Packages](http://s.sudre.free.fr/Software/Packages/about.html).
* I haven't used it myself, but it looks like CMake [supports PackageMaker](https://cmake.org/Wiki/CMake:CPackPackageGenerators#PackageMaker_.28OSX_only.29), which is a third party tool for creating OS X packages.
* There's also the built-in [pkgbuild](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/pkgbuild.1.html#//apple_ref/doc/man/1/pkgbuild) utility.
Just make sure you don't touch anything outside the [standard paths](https://support.apple.com/en-au/HT204899) (`/Library`, `/Applications`, or `/usr/local/`) and you'll be fine. | You may want to have a look at **[EPM](http://www.msweet.org/projects.php?Z2)**, the Easy Package Manager.
It can package Mac OS X `pkg` as well as RedHat `RPM`, Debian `deb` and then some more package formats -- all from the same source files, immediately after the build step.
It was originally written by Michael Sweet, the author of CUPS (who now works for Apple), and is still maintained by him.
The documentation is here:
* <http://www.msweet.org/documentation/project2/EPM.html>
EPM is available via MacPorts (albeit in an older version, v4.1, whereas the current one is v4.3).
To use it in your Makefile, it is as easy as adding an additional target like this:
```
osx:
epm -f osx -v -s doc/epmlogo.tif $(MY_PROJECT)
```
---
Of course, you can also use it standalone (not from the Makefile) to package your software.
It requires you to create a list of files with their paths, permissions and some other meta info which should be packaged. |
Question: a gem intends to support gems `a` or `b` as alternatives for a functionality.
In code I check with `defined?(A)` if I fall back to `b` that's fine.
But as a gem developer how to specify these dependencies?
1) what do I put in the Gemfile.
```
group :development, :test do
gem 'a', :require => false
gem 'b', :require => false
end
```
This allows `Bundle.require(:test)` not to auto-require a,b?
2) How can explicitly require `a` and `b` separately to mimic (or mock) the scenario when we fall back to `b` in my tests?
3) Also how do I specify that either `a` or `b` is prerequisite for the gem.
thanks
Answer: | Don't include the `a` gem in your dependencies, but `require` it anyway. If that fails, it will raise `LoadError`, from which you can rescue.
```
begin
require 'a'
rescue LoadError
# The 'a' gem is not installed
require 'b'
end
```
---
I believe this is the best way to use and test this setup:
1. Define an interface for your backend and allow a custom implementation to be easily plugged in.
```
module YourGem
class << self
attr_accessor :backend
def do_something_awesome
backend.do_something_awesome
end
end
end
```
2. Implement the `a` and `b` backends.
```
# your_gem/backends/a.rb
require 'a'
module YourGem::Backends::A
def self.do_something_awesome
# Do it
end
end
# your_gem/backends/b.rb
require 'b'
module YourGem::Backends::B
def self.do_something_awesome
# Do it
end
end
```
3. Set the one you want to use.
```
begin
require 'your_gem/backends/a'
Gem.backend = YourGem::Backends::A
rescue LoadError
require 'your_gem/backends/b'
Gem.backend = YourGem::Backends::B
end
```
This will use `YourGem::Backend::A` even if `b` is installed.
4. Before testing, make sure both `a` and `b` gems are installed, `require` both backends in the test code, run the tests with one backend, then run the tests again with the other backend. | I got this same question a while ago. My solution was to think that the developer should specify this behavior. I would not specify it on the gem, but on the wiki. I would recommend you to document it clearly that the developer need to define one of the dependencies.
To make it better, you can make a check on initialization of the gem, looking for the dependencies, if none can be found, just raise a runtime exception or if you prefer, your own exception. =) |
Question: Does anyone know what Facebook uses for their blurred toolbar?
![enter image description here](https://i.stack.imgur.com/RTmVf.png)
Now, I **KNOW** there are already countless threads about iOS 7 blur. They all come to these same solutions:
1. Use a UIToolbar with translucent set to YES, and then set its barTintColor property. The problem with this approach is that it significantly increases the lightness of the color. This is the approach that [AMBlurView](https://github.com/JagCesar/iOS-blur) uses. The nav bar in the Facebook app remains dark blue even when it's above white content. (with AMBlurView it becomes pastel blue)
2. Render the underlying view's in a graphic context, then blur that context, output it as a UIImage and use that as background view, repeat 30 times per second. (which hurts performance pretty bad). This is the approach that [FXBlurView](https://github.com/nicklockwood/FXBlurView) uses. It doesn't seem like Facebook is using that either.
I've read at length in the Apple Dev Forums and it seems like this is a technical challenge even for Apple engineers. With Facebook nailing the real-time blur with something else than the two approaches I described. Any idea?
Answer: | Apparently the trick here is to insert the translucent layer as a sublayer of the navigation bar. I take no credit for finding this, and the following snippet has been taken [**from this gist**](https://gist.github.com/alanzeino/6619253).
```
UIColor *barColour = [UIColor colorWithRed:0.13f green:0.14f blue:0.15f alpha:1.00f];
UIView *colourView = [[UIView alloc] initWithFrame:CGRectMake(0.f, -20.f, 320.f, 64.f)];
colourView.opaque = NO;
colourView.alpha = .7f;
colourView.backgroundColor = barColour;
self.navigationBar.barTintColor = barColour;
[self.navigationBar.layer insertSublayer:colourView.layer atIndex:1];
``` | I couldn't get the desired results unless I have added the following lines to the answer above:
```
[self.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
self.navigationBar.translucent = YES;
```
Here is the full code
```
[self.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
self.navigationBar.translucent = YES;
UIColor *barColour = [UIColor colorWithRed:0.13f green:0.14f blue:0.15f alpha:1.00f];
UIView *colourView = [[UIView alloc] initWithFrame:CGRectMake(0.f, -20.f, 320.f, 64.f)];
colourView.opaque = NO;
colourView.alpha = .7f;
colourView.backgroundColor = barColour;
self.navigationBar.barTintColor = barColour;
[self.navigationBar.layer insertSublayer:colourView.layer atIndex:1];
``` |
Question: Here is my original df:
```
my_df_1 <- data.frame(col_1 = c(rep('a',5), rep('b',5), rep('c', 5)),
col_2 = c(rep('x',3), rep('y', 9), rep('x', 3)))
```
I would like to group by `col_1` and return 1 if `col_2` for given group contains `x`, and 0 if not.
Here is how final result is supposed to look:
```
my_df_2 <- data.frame(col_1 = c(rep('a',5), rep('b',5), rep('c', 5)),
col_2 = c(rep('x',3), rep('y', 9), rep('x', 3)),
col_3 = c(rep(1,5), rep(0,5), rep(1, 5)))
```
I would prefer to get it done with `dplyr`, if possible. This is kind of `count if` predicate, but cannot find it.
Answer: | What about this?
```
do <- as.data.frame(do.call(rbind, lapply(my.stuff, as.vector)))
do <- cbind(my.var=rownames(do), do)
do[do == "NULL"] <- NA
```
***Result***
```
> do
my.var my.col1 my.col2 my.col3 my.col4
AA AA 1 4 NA NA
BB BB NA NA NA NA
CC CC 13 8 2 10
DD DD NA NA -5 7
```
### *Edit:*
If we don't want lists as column objects as @akrun reasonably suggests, we could do it this way:
```
u <- as.character(unlist(my.stuff, recursive=FALSE))
u[u == "NULL"] <- NA
do <- matrix(as.integer(u), nrow=4, byrow=TRUE,
dimnames=list(NULL, names(my.stuff[[1]])))
do <- data.frame(my.var=names(my.stuff), do, stringsAsFactors=FALSE)
```
***Test:***
```none
> all.equal(str(do), str(desired.object))
'data.frame': 4 obs. of 5 variables:
$ my.var : chr "AA" "BB" "CC" "DD"
$ my.col1: int 1 NA 13 NA
$ my.col2: int 4 NA 8 NA
$ my.col3: int NA NA 2 -5
$ my.col4: int NA NA 10 7
'data.frame': 4 obs. of 5 variables:
$ my.var : chr "AA" "BB" "CC" "DD"
$ my.col1: int 1 NA 13 NA
$ my.col2: int 4 NA 8 NA
$ my.col3: int NA NA 2 -5
$ my.col4: int NA NA 10 7
[1] TRUE
``` | We can use a recursive `map`
```
library(tidyverse)
map_df(my.stuff, ~ map_df(.x, ~
replace(.x, is.null(.x), NA)), .id = "my.var")
# A tibble: 4 x 5
# my.var my.col1 my.col2 my.col3 my.col4
# <chr> <dbl> <dbl> <dbl> <dbl>
#1 AA 1 4 NA NA
#2 BB NA NA NA NA
#3 CC 13 8 2 10
#4 DD NA NA -5 7
``` |