qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
|---|---|---|---|---|---|
1,419
|
As a follow on question from the 2012 [Uh oh. We have a [beginner] tag!](https://robotics.meta.stackexchange.com/questions/88/uh-oh-we-have-a-beginner-tag), I’ve noticed a couple of the meta tags discussed for deletion are still being used. Was this intentional or have they crept back into use somehow? Examples (see below) `beginner` and `research`.
[](https://i.stack.imgur.com/b3fJ4.jpg)
[](https://i.stack.imgur.com/DN9au.jpg)
|
2021/10/18
|
[
"https://robotics.meta.stackexchange.com/questions/1419",
"https://robotics.meta.stackexchange.com",
"https://robotics.meta.stackexchange.com/users/27817/"
] |
This is a complex question that doesn't have a great answer - while Ben's answer does give some good explanations for how the system has worked in the past and it's worth considering and following that guidance - we've changed how and when we take sites out of beta in recent years and that's impacted many of our older sites.
For the longest time, the guidance was that a site had to have various metrics (the stats in Area 51 Ben cites), with the most important being 10 questions per day. We set this restriction because we thought about sites leaving beta as ones that should be very active rather than relatively slow at least in part to the fact that leaving beta meant a site would have the higher privilege levels of graduated sites.
We were also limited in how many sites could leave beta at any given time by the fact that "Graduation" was tied to having a site theme created for the site by our design team, which was something that was very difficult to keep up with for us. So back in 2015 we made a change - [Graduation, site closure, and a clearer outlook on the health of SE sites](https://meta.stackexchange.com/questions/257614/graduation-site-closure-and-a-clearer-outlook-on-the-health-of-se-sites)
While we didn't remove the beta label from sites, we recognized that our practice of leaving sites in beta was having an impact and so we went to the effort of trying to help sites understand that being small was OK! That we wouldn't be closing a site down for being low-activity unless the moderation of the site started to fail.
Shortly after that discussion I (as a user, not staff) [proposed the idea](https://meta.stackexchange.com/questions/257317/can-beta-sites-slated-for-graduation-get-full-site-abilities-without-site-design) of separating site designs from graduation so that more sites could leave beta sooner without having to wait for artwork. This was [discussed](https://meta.stackexchange.com/questions/260754/feedback-requested-design-independent-graduation?rq=1) and then made into [policy](https://meta.stackexchange.com/questions/263905/design-independent-graduation-is-on-for-early-september?rq=1), so back in September 2015, we kicked a handful of sites out of beta without site designs.
In 2017 (still as a user) I asked a new question - [Let's break up with "Graduation" and remove a bunch of "Beta" labels](https://meta.stackexchange.com/questions/303727/lets-break-up-with-graduation-and-remove-a-bunch-of-beta-labels) - essentially, proposing the idea that the CMs consider changing their way of determining when a site should leave beta.
After getting hired, I worked with some coworkers to consider a new site lifecycle that included removing sites from beta sooner, without considering their stats on Area 51 at all. While that project was cancelled before it was completed, we [removed the beta label from 29 sites](https://meta.stackexchange.com/questions/331708/congratulations-to-our-29-oldest-beta-sites-theyre-now-no-longer-beta) two years ago because we felt that seven years was too long to be in beta.
Now, we're on the cusp of making such a change again. In the next six months or so, I'm expecting that we'll be able to remove the beta label from most sites across the network because they are - as Robotics is - not really a "beta" site and we need to change our practices about keeping sites in a perpetual beta phase.
We'll have more on this in the coming months but I want you to know that we, as a team, don't see beta status as a detriment to any site - though we know many of the people using the sites do - and that's something we want to change. We don't really treat beta sites any differently than non-beta sites.
In the end, there's nothing that y'all have done or failed to do that's kept you in beta - it's on us and we're working to address it.
|
Teaser: Take a deep breathe everyone... we might have some news soon...
|
328,622
|
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?
* Time between calculations?
* Current state of the CPU?
* Different hardware?
* Language / platform / OS?
* Solar flares?
I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.
I am currently working in Silverlight though would be interested to know if this question can be answered in general.
**Update:** The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.
|
2008/11/30
|
[
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
Also, while [Goldberg](http://docs.sun.com/source/806-3568/ncg_goldberg.html#3098) is a great reference, the original text is also wrong: **IEEE754 is not gaurenteed to be portable**. I can't emphasize this enough given how often this statement is made based on skimming the text. Later versions of the document include [a section that discusses this specifically](http://docs.sun.com/source/806-3568/ncg_goldberg.html#3098):
>
> Many programmers may not realize that even a program that uses only the numeric formats and operations prescribed by the IEEE standard can compute different results on different systems. In fact, the authors of the standard intended to allow different implementations to obtain different results.
>
>
>
|
HM. Since the OP asked for C#:
Is the C# bytecode JIT deterministic or does it generate different code between different runs? I don't know, but I wouldn't trust the Jit.
I could think of scenarios where the JIT has some quality of service features and decides to spend less time on optimization because the CPU is doing heavy number crunching somewhere else (think background DVD encoding)? This could lead to subtle differences that may result in huge differences later on.
Also if the JIT itself gets improved (maybe as part of a service pack maybe) the generated code will change for sure. The 80 bit internal precision issue has already been mentioned.
|
328,622
|
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?
* Time between calculations?
* Current state of the CPU?
* Different hardware?
* Language / platform / OS?
* Solar flares?
I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.
I am currently working in Silverlight though would be interested to know if this question can be answered in general.
**Update:** The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.
|
2008/11/30
|
[
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
This answer in the C++ FAQ probably describes it the best:
<http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18>
It is not only that different architectures or compiler might give you trouble, float pointing numbers already behave in weird ways within the same program. As the FAQ points out if `y == x` is true, that can still mean that `cos(y) == cos(x)` will be false. This is because the x86 CPU calculates the value with 80bit, while the value is stored as 64bit in memory, so you end up comparing a truncated 64bit value with a full 80bit value.
The calculation are still deterministic, in the sense that running the same compiled binary will give you the same result each time, but the moment you adjust the source a bit, the optimization flags or compile it with a different compiler all bets are off and anything can happen.
Practically speaking, I it is not quite that bad, I could reproduce simple float pointing math with different version of GCC on 32bit Linux bit for bit, but the moment I switched to 64bit Linux the result were no longer the same. Demos recordings created on 32bit wouldn't work on 64bit and vice versa, but would work fine when run on the same arch.
|
This is not a full answer to your question, but here is an example demonstrating that double calculations in C# are non-deterministic. I don't know why, but seemingly unrelated code can apparently affect the outcome of a downstream double calculation.
1. Create a new WPF application in Visual Studio Version 12.0.40629.00 Update 5, and accept all the default options.
2. Replace the contents of MainWindow.xaml.cs with this:
```
using System;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Content = FooConverter.Convert(new Point(950, 500), new Point(850, 500));
}
}
public static class FooConverter
{
public static string Convert(Point curIPJos, Point oppIJPos)
{
var ij = " Insulated Joint";
var deltaX = oppIJPos.X - curIPJos.X;
var deltaY = oppIJPos.Y - curIPJos.Y;
var teta = Math.Atan2(deltaY, deltaX);
string result;
if (-Math.PI / 4 <= teta && teta <= Math.PI / 4)
result = "Left" + ij;
else if (Math.PI / 4 < teta && teta <= Math.PI * 3 / 4)
result = "Top" + ij;
else if (Math.PI * 3 / 4 < teta && teta <= Math.PI || -Math.PI <= teta && teta <= -Math.PI * 3 / 4)
result = "Right" + ij;
else
result = "Bottom" + ij;
return result;
}
}
}
```
3. Set build configuration to "Release" and build, but do not run in Visual Studio.
4. Double-click the built exe to run it.
5. Note that the window shows "Bottom Insulated Joint".
6. Now add this line just before "string result":
```
string debug = teta.ToString();
```
7. Repeat steps 3 and 4.
8. Note that the window shows "Right Insulated Joint".
This behavior was confirmed on a colleague's machine. Note that the window consistently shows "Right Insulated Joint" if any of the following are true: the exe is run from within Visual Studio, the exe was built using the Debug configuration, or "Prefer 32-bit" is unchecked in project properties.
It's quite difficult to figure out what's going on, since any attempt to observe the process appears to change the result.
|
328,622
|
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?
* Time between calculations?
* Current state of the CPU?
* Different hardware?
* Language / platform / OS?
* Solar flares?
I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.
I am currently working in Silverlight though would be interested to know if this question can be answered in general.
**Update:** The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.
|
2008/11/30
|
[
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
From what I understand you're only guaranteed identical results provided that you're dealing with the same instruction set and compiler, and that any processors you run on adhere strictly to the relevant standards (ie IEEE754). That said, unless you're dealing with a particularly chaotic system any drift in calculation between runs isn't likely to result in buggy behavior.
Specific gotchas that I'm aware of:
1. some operating systems allow you to set the mode of the floating point processor in ways that break compatibility.
2. floating point intermediate results often use 80 bit precision in register, but only 64 bit in memory. If a program is recompiled in a way that changes register spilling within a function, it may return different results compared to other versions. Most platforms will give you a way to force all results to be truncated to the in memory precision.
3. standard library functions may change between versions. I gather that there are some not uncommonly encountered examples of this in gcc 3 vs 4.
4. The IEEE itself allows some binary representations to differ... specifically NaN values, but I can't recall the details.
|
Since your question is tagged C#, it's worth emphasising the issues faced on .NET:
1. Floating point maths is not associative - that is, `(a + b) + c` is not guaranteed to equal `a + (b + c)`;
2. Different compilers will optimize your code in different ways, and that may involve re-ordering arithmetic operations.
3. In .NET the CLR's JIT compiler will compile your code on the fly, so compilation is dependent upon the version of the .NET on the machine at runtime.
This means, that you shouldn't rely upon your .NET application producing the same floating point calculation results when run on different versions of the .NET CLR.
For example, in your case, if you record the initial state and inputs to your simulation, then install a service pack that updates the CLR, your simulation may not replay identically the next time you run it.
See Shawn Hargreaves's blog post [Is floating point math deterministic?](http://blogs.msdn.com/b/shawnhar/archive/2009/03/25/is-floating-point-math-deterministic.aspx) for further discussion relevant to .NET.
|
328,622
|
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?
* Time between calculations?
* Current state of the CPU?
* Different hardware?
* Language / platform / OS?
* Solar flares?
I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.
I am currently working in Silverlight though would be interested to know if this question can be answered in general.
**Update:** The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.
|
2008/11/30
|
[
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
Since your question is tagged C#, it's worth emphasising the issues faced on .NET:
1. Floating point maths is not associative - that is, `(a + b) + c` is not guaranteed to equal `a + (b + c)`;
2. Different compilers will optimize your code in different ways, and that may involve re-ordering arithmetic operations.
3. In .NET the CLR's JIT compiler will compile your code on the fly, so compilation is dependent upon the version of the .NET on the machine at runtime.
This means, that you shouldn't rely upon your .NET application producing the same floating point calculation results when run on different versions of the .NET CLR.
For example, in your case, if you record the initial state and inputs to your simulation, then install a service pack that updates the CLR, your simulation may not replay identically the next time you run it.
See Shawn Hargreaves's blog post [Is floating point math deterministic?](http://blogs.msdn.com/b/shawnhar/archive/2009/03/25/is-floating-point-math-deterministic.aspx) for further discussion relevant to .NET.
|
HM. Since the OP asked for C#:
Is the C# bytecode JIT deterministic or does it generate different code between different runs? I don't know, but I wouldn't trust the Jit.
I could think of scenarios where the JIT has some quality of service features and decides to spend less time on optimization because the CPU is doing heavy number crunching somewhere else (think background DVD encoding)? This could lead to subtle differences that may result in huge differences later on.
Also if the JIT itself gets improved (maybe as part of a service pack maybe) the generated code will change for sure. The 80 bit internal precision issue has already been mentioned.
|
328,622
|
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?
* Time between calculations?
* Current state of the CPU?
* Different hardware?
* Language / platform / OS?
* Solar flares?
I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.
I am currently working in Silverlight though would be interested to know if this question can be answered in general.
**Update:** The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.
|
2008/11/30
|
[
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
From what I understand you're only guaranteed identical results provided that you're dealing with the same instruction set and compiler, and that any processors you run on adhere strictly to the relevant standards (ie IEEE754). That said, unless you're dealing with a particularly chaotic system any drift in calculation between runs isn't likely to result in buggy behavior.
Specific gotchas that I'm aware of:
1. some operating systems allow you to set the mode of the floating point processor in ways that break compatibility.
2. floating point intermediate results often use 80 bit precision in register, but only 64 bit in memory. If a program is recompiled in a way that changes register spilling within a function, it may return different results compared to other versions. Most platforms will give you a way to force all results to be truncated to the in memory precision.
3. standard library functions may change between versions. I gather that there are some not uncommonly encountered examples of this in gcc 3 vs 4.
4. The IEEE itself allows some binary representations to differ... specifically NaN values, but I can't recall the details.
|
This is not a full answer to your question, but here is an example demonstrating that double calculations in C# are non-deterministic. I don't know why, but seemingly unrelated code can apparently affect the outcome of a downstream double calculation.
1. Create a new WPF application in Visual Studio Version 12.0.40629.00 Update 5, and accept all the default options.
2. Replace the contents of MainWindow.xaml.cs with this:
```
using System;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Content = FooConverter.Convert(new Point(950, 500), new Point(850, 500));
}
}
public static class FooConverter
{
public static string Convert(Point curIPJos, Point oppIJPos)
{
var ij = " Insulated Joint";
var deltaX = oppIJPos.X - curIPJos.X;
var deltaY = oppIJPos.Y - curIPJos.Y;
var teta = Math.Atan2(deltaY, deltaX);
string result;
if (-Math.PI / 4 <= teta && teta <= Math.PI / 4)
result = "Left" + ij;
else if (Math.PI / 4 < teta && teta <= Math.PI * 3 / 4)
result = "Top" + ij;
else if (Math.PI * 3 / 4 < teta && teta <= Math.PI || -Math.PI <= teta && teta <= -Math.PI * 3 / 4)
result = "Right" + ij;
else
result = "Bottom" + ij;
return result;
}
}
}
```
3. Set build configuration to "Release" and build, but do not run in Visual Studio.
4. Double-click the built exe to run it.
5. Note that the window shows "Bottom Insulated Joint".
6. Now add this line just before "string result":
```
string debug = teta.ToString();
```
7. Repeat steps 3 and 4.
8. Note that the window shows "Right Insulated Joint".
This behavior was confirmed on a colleague's machine. Note that the window consistently shows "Right Insulated Joint" if any of the following are true: the exe is run from within Visual Studio, the exe was built using the Debug configuration, or "Prefer 32-bit" is unchecked in project properties.
It's quite difficult to figure out what's going on, since any attempt to observe the process appears to change the result.
|
328,622
|
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?
* Time between calculations?
* Current state of the CPU?
* Different hardware?
* Language / platform / OS?
* Solar flares?
I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.
I am currently working in Silverlight though would be interested to know if this question can be answered in general.
**Update:** The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.
|
2008/11/30
|
[
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
Since your question is tagged C#, it's worth emphasising the issues faced on .NET:
1. Floating point maths is not associative - that is, `(a + b) + c` is not guaranteed to equal `a + (b + c)`;
2. Different compilers will optimize your code in different ways, and that may involve re-ordering arithmetic operations.
3. In .NET the CLR's JIT compiler will compile your code on the fly, so compilation is dependent upon the version of the .NET on the machine at runtime.
This means, that you shouldn't rely upon your .NET application producing the same floating point calculation results when run on different versions of the .NET CLR.
For example, in your case, if you record the initial state and inputs to your simulation, then install a service pack that updates the CLR, your simulation may not replay identically the next time you run it.
See Shawn Hargreaves's blog post [Is floating point math deterministic?](http://blogs.msdn.com/b/shawnhar/archive/2009/03/25/is-floating-point-math-deterministic.aspx) for further discussion relevant to .NET.
|
This is not a full answer to your question, but here is an example demonstrating that double calculations in C# are non-deterministic. I don't know why, but seemingly unrelated code can apparently affect the outcome of a downstream double calculation.
1. Create a new WPF application in Visual Studio Version 12.0.40629.00 Update 5, and accept all the default options.
2. Replace the contents of MainWindow.xaml.cs with this:
```
using System;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Content = FooConverter.Convert(new Point(950, 500), new Point(850, 500));
}
}
public static class FooConverter
{
public static string Convert(Point curIPJos, Point oppIJPos)
{
var ij = " Insulated Joint";
var deltaX = oppIJPos.X - curIPJos.X;
var deltaY = oppIJPos.Y - curIPJos.Y;
var teta = Math.Atan2(deltaY, deltaX);
string result;
if (-Math.PI / 4 <= teta && teta <= Math.PI / 4)
result = "Left" + ij;
else if (Math.PI / 4 < teta && teta <= Math.PI * 3 / 4)
result = "Top" + ij;
else if (Math.PI * 3 / 4 < teta && teta <= Math.PI || -Math.PI <= teta && teta <= -Math.PI * 3 / 4)
result = "Right" + ij;
else
result = "Bottom" + ij;
return result;
}
}
}
```
3. Set build configuration to "Release" and build, but do not run in Visual Studio.
4. Double-click the built exe to run it.
5. Note that the window shows "Bottom Insulated Joint".
6. Now add this line just before "string result":
```
string debug = teta.ToString();
```
7. Repeat steps 3 and 4.
8. Note that the window shows "Right Insulated Joint".
This behavior was confirmed on a colleague's machine. Note that the window consistently shows "Right Insulated Joint" if any of the following are true: the exe is run from within Visual Studio, the exe was built using the Debug configuration, or "Prefer 32-bit" is unchecked in project properties.
It's quite difficult to figure out what's going on, since any attempt to observe the process appears to change the result.
|
328,622
|
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?
* Time between calculations?
* Current state of the CPU?
* Different hardware?
* Language / platform / OS?
* Solar flares?
I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.
I am currently working in Silverlight though would be interested to know if this question can be answered in general.
**Update:** The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.
|
2008/11/30
|
[
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
I think your confusion lies in the type of inaccuracy around floating point. Most languages implement the [IEEE floating point standard](http://en.wikipedia.org/wiki/IEEE_floating-point_standard) This standard lays out how individual bits within a float/double are used to produce a number. Typically a float consists of a four bytes, and a double eight bytes.
A mathmatical operation between two floating point numbers will have the same value every single time (as specified within the standard).
The inaccuracy comes in the precision. Consider an int vs a float. Both typically take up the same number of bytes (4). Yet the maximum value each number can store is wildly different.
* int: roughly 2 billion
* float: 3.40282347E38 (quite a bit larger)
The difference is in the middle. int, can represent every number between 0 and roughly 2 billion. Float however cannot. It can represent 2 billion values between 0 and 3.40282347E38. But that leaves a whole range of values that cannot be represented. If a math equation hits one of these values it will have to be rounded out to a representable value and is hence considered "inaccurate". Your definition of inaccurate may vary :).
|
Also, while [Goldberg](http://docs.sun.com/source/806-3568/ncg_goldberg.html#3098) is a great reference, the original text is also wrong: **IEEE754 is not gaurenteed to be portable**. I can't emphasize this enough given how often this statement is made based on skimming the text. Later versions of the document include [a section that discusses this specifically](http://docs.sun.com/source/806-3568/ncg_goldberg.html#3098):
>
> Many programmers may not realize that even a program that uses only the numeric formats and operations prescribed by the IEEE standard can compute different results on different systems. In fact, the authors of the standard intended to allow different implementations to obtain different results.
>
>
>
|
328,622
|
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?
* Time between calculations?
* Current state of the CPU?
* Different hardware?
* Language / platform / OS?
* Solar flares?
I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.
I am currently working in Silverlight though would be interested to know if this question can be answered in general.
**Update:** The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.
|
2008/11/30
|
[
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
HM. Since the OP asked for C#:
Is the C# bytecode JIT deterministic or does it generate different code between different runs? I don't know, but I wouldn't trust the Jit.
I could think of scenarios where the JIT has some quality of service features and decides to spend less time on optimization because the CPU is doing heavy number crunching somewhere else (think background DVD encoding)? This could lead to subtle differences that may result in huge differences later on.
Also if the JIT itself gets improved (maybe as part of a service pack maybe) the generated code will change for sure. The 80 bit internal precision issue has already been mentioned.
|
Very few FPUs meet the IEEE standard (despite their claims). So running the same program in different hardware will indeed give you different results. The results are likely to be in corner cases that you should already avoid as part of using an FPU in your software.
IEEE bugs are often patched in software and are you sure that the operating system you are running today includes the proper traps and patches from the manufacturer? What about before or after the OS has an update? Are all bugs removed and bug fixes added? Is the C compiler in sync with all of this and is the C compiler producing the proper code?
Testing this may prove futile. You wont see the problem until you deliver the product.
Observe FP rule number 1: Never use an if(something==something) comparison. And rule number two IMO would have to do with ascii to fp or fp to ascii (printf, scanf, etc). There are more accuracy and bug problems there than in the hardware.
With each new generation of hardware (density) the affects from the sun are more apparent. We already have problems with SEU's on the planets surface, so independent of floating point calculations, you will have problems (few vendors have bothered to care, so expect crashes more often with new hardware).
By consuming enormous amounts of logic the fpu is likely to be a very fast (a single clock cycle). Not any slower than an integer alu. Do not confuse this with modern fpus being as simple as alus, fpus are expensive. (alus likewise consume more logic for multiply and divide to get that down to one clock cycle but its not nearly as big as the fpu).
Keep to the simple rules above, study floating point a bit more, understand the warts and traps that go with it. You may want to check for infinity or nans periodically. Your problems are more likely to be found in the compiler and operating system than the hardware (in general not just fp math). Modern hardware (and software) is, these days, by definition full of bugs, so just try to be less buggy than what your software runs on.
|
328,622
|
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?
* Time between calculations?
* Current state of the CPU?
* Different hardware?
* Language / platform / OS?
* Solar flares?
I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.
I am currently working in Silverlight though would be interested to know if this question can be answered in general.
**Update:** The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.
|
2008/11/30
|
[
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
This answer in the C++ FAQ probably describes it the best:
<http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18>
It is not only that different architectures or compiler might give you trouble, float pointing numbers already behave in weird ways within the same program. As the FAQ points out if `y == x` is true, that can still mean that `cos(y) == cos(x)` will be false. This is because the x86 CPU calculates the value with 80bit, while the value is stored as 64bit in memory, so you end up comparing a truncated 64bit value with a full 80bit value.
The calculation are still deterministic, in the sense that running the same compiled binary will give you the same result each time, but the moment you adjust the source a bit, the optimization flags or compile it with a different compiler all bets are off and anything can happen.
Practically speaking, I it is not quite that bad, I could reproduce simple float pointing math with different version of GCC on 32bit Linux bit for bit, but the moment I switched to 64bit Linux the result were no longer the same. Demos recordings created on 32bit wouldn't work on 64bit and vice versa, but would work fine when run on the same arch.
|
HM. Since the OP asked for C#:
Is the C# bytecode JIT deterministic or does it generate different code between different runs? I don't know, but I wouldn't trust the Jit.
I could think of scenarios where the JIT has some quality of service features and decides to spend less time on optimization because the CPU is doing heavy number crunching somewhere else (think background DVD encoding)? This could lead to subtle differences that may result in huge differences later on.
Also if the JIT itself gets improved (maybe as part of a service pack maybe) the generated code will change for sure. The 80 bit internal precision issue has already been mentioned.
|
328,622
|
I understand that floating point calculations have accuracy issues and there are plenty of questions explaining why. My question is if I run the same calculation twice, can I always rely on it to produce the same result? What factors might affect this?
* Time between calculations?
* Current state of the CPU?
* Different hardware?
* Language / platform / OS?
* Solar flares?
I have a simple physics simulation and would like to record sessions so that they can be replayed. If the calculations can be relied on then I should only need to record the initial state plus any user input and I should always be able to reproduce the final state exactly. If the calculations are not accurate errors at the start may have huge implications by the end of the simulation.
I am currently working in Silverlight though would be interested to know if this question can be answered in general.
**Update:** The initial answers indicate yes, but apparently this isn't entirely clear cut as discussed in the comments for the selected answer. It looks like I will have to do some tests and see what happens.
|
2008/11/30
|
[
"https://Stackoverflow.com/questions/328622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40944/"
] |
The short answer is that FP calculations are entirely deterministic, as per the [IEEE Floating Point Standard](http://en.wikipedia.org/wiki/IEEE_754), but that doesn't mean they're entirely reproducible across machines, compilers, OS's, etc.
The long answer to these questions and more can be found in what is probably the best reference on floating point, David Goldberg's [What Every Computer Scientist Should Know About Floating Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html). Skip to the section on the IEEE standard for the key details.
To answer your bullet points briefly:
* Time between calculations and state
of the CPU have little to do with
this.
* Hardware can affect things (e.g. some GPUs are not
IEEE floating point compliant).
* Language, platform, and OS can also
affect things. For a better description of this than I can offer, see Jason Watkins's answer. If you are using Java, take a look at Kahan's [rant on Java's floating point inadequacies](http://www.cs.berkeley.edu/~wkahan/JAVAhurt.pdf).
* Solar flares might matter, hopefully
infrequently. I wouldn't worry too much, because if
they do matter, then everything else is screwed up too. I would put this in the same category as worrying about [EMP](http://en.wikipedia.org/wiki/Effects_of_nuclear_explosions#Electromagnetic_pulse).
Finally, if you are doing the same *sequence* of floating point calculations on the same initial inputs, then things should be replayable exactly just fine. The exact sequence can change depending on your compiler/os/standard library, so you might get some small errors this way.
Where you usually run into problems in floating point is if you have a numerically unstable method and you start with FP inputs that are *approximately* the same but not quite. If your method's stable, you should be able to guarantee reproducibility within some tolerance. If you want more detail than this, then take a look at Goldberg's FP article linked above or pick up an intro text on numerical analysis.
|
Since your question is tagged C#, it's worth emphasising the issues faced on .NET:
1. Floating point maths is not associative - that is, `(a + b) + c` is not guaranteed to equal `a + (b + c)`;
2. Different compilers will optimize your code in different ways, and that may involve re-ordering arithmetic operations.
3. In .NET the CLR's JIT compiler will compile your code on the fly, so compilation is dependent upon the version of the .NET on the machine at runtime.
This means, that you shouldn't rely upon your .NET application producing the same floating point calculation results when run on different versions of the .NET CLR.
For example, in your case, if you record the initial state and inputs to your simulation, then install a service pack that updates the CLR, your simulation may not replay identically the next time you run it.
See Shawn Hargreaves's blog post [Is floating point math deterministic?](http://blogs.msdn.com/b/shawnhar/archive/2009/03/25/is-floating-point-math-deterministic.aspx) for further discussion relevant to .NET.
|
70,038,544
|
I need to find an element by ID "start-ads", but the numbers at the end change every time. Is it possible to search for an element not by the whole ID, but only by its part?
```
Full element id: <div id="start-ads-202308">
```
|
2021/11/19
|
[
"https://Stackoverflow.com/questions/70038544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17450315/"
] |
To identify the following element:
```
<div id="start-ads-202308">
```
considering the static part of the value of *`id`* attribute you can use either of the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
* Using `css_selector`:
```
element = driver.find_element(By.CSS_SELECTOR, "div[id^='start-ads-']")
```
where ^ denotes starts-with
* Using `xpath`:
```
element = driver.find_element(By.XPATH, "//div[starts-with(@id, 'start-ads-')]")
```
|
You can use [find\_element\_by\_css\_selector](https://selenium-python.readthedocs.io/locating-elements.html#locating-elements-by-css-selectors) and use a CSS selector that matches using a prefix
```
driver.find_element_by_css_selector("div[id^='start-ads-']")
```
|
28,198,893
|
I am trying to extract the SPY.Close column from the data frame SPY which is created by quantmod. However, I would like to generalize this so that whatever symbol I pass initially can be used to create the close vector.
```
library(quantmod)
library(wmtsa)
library(ggplot2)
library(tseries)
library(pracma)
s <- getSymbols("SPY")
s <- as.name(s)
field <- c(paste(s,".Close",sep=""))
close <- as.vector(s[,field])
```
If I were to just type in
```
close <- as.vector(SPY[,"SPY.Close"])
```
this is successful. However they are constants and would need to be changed with every new symbol.
Any help would be appreciated.
|
2015/01/28
|
[
"https://Stackoverflow.com/questions/28198893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504163/"
] |
Define a function to generate invoice number.
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
invoice_int = int(invoice_no.split('MAG')[-1])
new_invoice_int = invoice_int + 1
new_invoice_no = 'MAG' + str(new_invoice_int)
return new_invoice_no
```
Now use this function as default value in your model filed.
```
invoice_no = models.CharField(max_length=500, default=increment_invoice_number, null=True, blank=True)
```
This is just an idea. Modify the function to match your preferred invoice number format.
|
```
def invoiceIncrement():
get_last_invoice_number
incremente_last_invoice_number
return next_invoice_number
class Invoice:
invoice_no = models.CharField(max_length=500, null=True, blank=True,
validators=[RegexValidator(regex='^[a-zA-Z0-9]*$',
message='Invoice must be Alphanumeric',code='invalid_invoice number'),],
default=invoiceIncrement)
```
Try this: there are some obvious issues:
1. if more than one person adds an invoice at the same time, could have collision
2. will need to make an extra db call each time you create a new invoice.
Also: you may want to just consider using either an auto\_increment or UUID.
|
28,198,893
|
I am trying to extract the SPY.Close column from the data frame SPY which is created by quantmod. However, I would like to generalize this so that whatever symbol I pass initially can be used to create the close vector.
```
library(quantmod)
library(wmtsa)
library(ggplot2)
library(tseries)
library(pracma)
s <- getSymbols("SPY")
s <- as.name(s)
field <- c(paste(s,".Close",sep=""))
close <- as.vector(s[,field])
```
If I were to just type in
```
close <- as.vector(SPY[,"SPY.Close"])
```
this is successful. However they are constants and would need to be changed with every new symbol.
Any help would be appreciated.
|
2015/01/28
|
[
"https://Stackoverflow.com/questions/28198893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504163/"
] |
```
def invoiceIncrement():
get_last_invoice_number
incremente_last_invoice_number
return next_invoice_number
class Invoice:
invoice_no = models.CharField(max_length=500, null=True, blank=True,
validators=[RegexValidator(regex='^[a-zA-Z0-9]*$',
message='Invoice must be Alphanumeric',code='invalid_invoice number'),],
default=invoiceIncrement)
```
Try this: there are some obvious issues:
1. if more than one person adds an invoice at the same time, could have collision
2. will need to make an extra db call each time you create a new invoice.
Also: you may want to just consider using either an auto\_increment or UUID.
|
Maybe this code can help
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
new_invoice_no = str(int(invoice_no[4:]) + 1)
new_invoice_no = invoice_no[0:-(len(new_invoice_no))] + new_invoice_no
return new_invoice_no
```
|
28,198,893
|
I am trying to extract the SPY.Close column from the data frame SPY which is created by quantmod. However, I would like to generalize this so that whatever symbol I pass initially can be used to create the close vector.
```
library(quantmod)
library(wmtsa)
library(ggplot2)
library(tseries)
library(pracma)
s <- getSymbols("SPY")
s <- as.name(s)
field <- c(paste(s,".Close",sep=""))
close <- as.vector(s[,field])
```
If I were to just type in
```
close <- as.vector(SPY[,"SPY.Close"])
```
this is successful. However they are constants and would need to be changed with every new symbol.
Any help would be appreciated.
|
2015/01/28
|
[
"https://Stackoverflow.com/questions/28198893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504163/"
] |
```
def invoiceIncrement():
get_last_invoice_number
incremente_last_invoice_number
return next_invoice_number
class Invoice:
invoice_no = models.CharField(max_length=500, null=True, blank=True,
validators=[RegexValidator(regex='^[a-zA-Z0-9]*$',
message='Invoice must be Alphanumeric',code='invalid_invoice number'),],
default=invoiceIncrement)
```
Try this: there are some obvious issues:
1. if more than one person adds an invoice at the same time, could have collision
2. will need to make an extra db call each time you create a new invoice.
Also: you may want to just consider using either an auto\_increment or UUID.
|
```
def invoice_number_gen():
last_invoice = Invoice.objects.all().order_by('id').last()
last_invoice_number = last_invoice.invoice_no
#invoice number format is 'customer_name_short + number' eg: CS003
last_invoice_digits =int(last_invoice_number[2:])
#comment: slicing CS003 to get the number 003 and converting to int.
last_invoice_initials = last_invoice_number[:2]
new_invoice_digits = last_invoice_digits + 1
new_invoice_number = last_invoice_initials + str(new_invoice_digits)
return (new_invoice_number)
```
|
28,198,893
|
I am trying to extract the SPY.Close column from the data frame SPY which is created by quantmod. However, I would like to generalize this so that whatever symbol I pass initially can be used to create the close vector.
```
library(quantmod)
library(wmtsa)
library(ggplot2)
library(tseries)
library(pracma)
s <- getSymbols("SPY")
s <- as.name(s)
field <- c(paste(s,".Close",sep=""))
close <- as.vector(s[,field])
```
If I were to just type in
```
close <- as.vector(SPY[,"SPY.Close"])
```
this is successful. However they are constants and would need to be changed with every new symbol.
Any help would be appreciated.
|
2015/01/28
|
[
"https://Stackoverflow.com/questions/28198893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504163/"
] |
Define a function to generate invoice number.
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
invoice_int = int(invoice_no.split('MAG')[-1])
new_invoice_int = invoice_int + 1
new_invoice_no = 'MAG' + str(new_invoice_int)
return new_invoice_no
```
Now use this function as default value in your model filed.
```
invoice_no = models.CharField(max_length=500, default=increment_invoice_number, null=True, blank=True)
```
This is just an idea. Modify the function to match your preferred invoice number format.
|
In above arulmr answer just edit char field
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
invoice_int = int(invoice_no.split('MAG')[-1])
width = 4
new_invoice_int = invoice_int + 1
formatted = (width - len(str(new_invoice_int))) * "0" + str(new_invoice_int)
new_invoice_no = 'MAG' + str(formatted)
return new_invoice_no
class Invoice(models.Model):
invoice_no = models.CharField(max_length = 500, default = increment_invoice_number, null = True, blank = True)
```
This will work fine.
|
28,198,893
|
I am trying to extract the SPY.Close column from the data frame SPY which is created by quantmod. However, I would like to generalize this so that whatever symbol I pass initially can be used to create the close vector.
```
library(quantmod)
library(wmtsa)
library(ggplot2)
library(tseries)
library(pracma)
s <- getSymbols("SPY")
s <- as.name(s)
field <- c(paste(s,".Close",sep=""))
close <- as.vector(s[,field])
```
If I were to just type in
```
close <- as.vector(SPY[,"SPY.Close"])
```
this is successful. However they are constants and would need to be changed with every new symbol.
Any help would be appreciated.
|
2015/01/28
|
[
"https://Stackoverflow.com/questions/28198893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504163/"
] |
Define a function to generate invoice number.
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
invoice_int = int(invoice_no.split('MAG')[-1])
new_invoice_int = invoice_int + 1
new_invoice_no = 'MAG' + str(new_invoice_int)
return new_invoice_no
```
Now use this function as default value in your model filed.
```
invoice_no = models.CharField(max_length=500, default=increment_invoice_number, null=True, blank=True)
```
This is just an idea. Modify the function to match your preferred invoice number format.
|
Maybe this code can help
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
new_invoice_no = str(int(invoice_no[4:]) + 1)
new_invoice_no = invoice_no[0:-(len(new_invoice_no))] + new_invoice_no
return new_invoice_no
```
|
28,198,893
|
I am trying to extract the SPY.Close column from the data frame SPY which is created by quantmod. However, I would like to generalize this so that whatever symbol I pass initially can be used to create the close vector.
```
library(quantmod)
library(wmtsa)
library(ggplot2)
library(tseries)
library(pracma)
s <- getSymbols("SPY")
s <- as.name(s)
field <- c(paste(s,".Close",sep=""))
close <- as.vector(s[,field])
```
If I were to just type in
```
close <- as.vector(SPY[,"SPY.Close"])
```
this is successful. However they are constants and would need to be changed with every new symbol.
Any help would be appreciated.
|
2015/01/28
|
[
"https://Stackoverflow.com/questions/28198893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504163/"
] |
Define a function to generate invoice number.
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
invoice_int = int(invoice_no.split('MAG')[-1])
new_invoice_int = invoice_int + 1
new_invoice_no = 'MAG' + str(new_invoice_int)
return new_invoice_no
```
Now use this function as default value in your model filed.
```
invoice_no = models.CharField(max_length=500, default=increment_invoice_number, null=True, blank=True)
```
This is just an idea. Modify the function to match your preferred invoice number format.
|
```
def invoice_number_gen():
last_invoice = Invoice.objects.all().order_by('id').last()
last_invoice_number = last_invoice.invoice_no
#invoice number format is 'customer_name_short + number' eg: CS003
last_invoice_digits =int(last_invoice_number[2:])
#comment: slicing CS003 to get the number 003 and converting to int.
last_invoice_initials = last_invoice_number[:2]
new_invoice_digits = last_invoice_digits + 1
new_invoice_number = last_invoice_initials + str(new_invoice_digits)
return (new_invoice_number)
```
|
28,198,893
|
I am trying to extract the SPY.Close column from the data frame SPY which is created by quantmod. However, I would like to generalize this so that whatever symbol I pass initially can be used to create the close vector.
```
library(quantmod)
library(wmtsa)
library(ggplot2)
library(tseries)
library(pracma)
s <- getSymbols("SPY")
s <- as.name(s)
field <- c(paste(s,".Close",sep=""))
close <- as.vector(s[,field])
```
If I were to just type in
```
close <- as.vector(SPY[,"SPY.Close"])
```
this is successful. However they are constants and would need to be changed with every new symbol.
Any help would be appreciated.
|
2015/01/28
|
[
"https://Stackoverflow.com/questions/28198893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504163/"
] |
In above arulmr answer just edit char field
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
invoice_int = int(invoice_no.split('MAG')[-1])
width = 4
new_invoice_int = invoice_int + 1
formatted = (width - len(str(new_invoice_int))) * "0" + str(new_invoice_int)
new_invoice_no = 'MAG' + str(formatted)
return new_invoice_no
class Invoice(models.Model):
invoice_no = models.CharField(max_length = 500, default = increment_invoice_number, null = True, blank = True)
```
This will work fine.
|
Maybe this code can help
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
new_invoice_no = str(int(invoice_no[4:]) + 1)
new_invoice_no = invoice_no[0:-(len(new_invoice_no))] + new_invoice_no
return new_invoice_no
```
|
28,198,893
|
I am trying to extract the SPY.Close column from the data frame SPY which is created by quantmod. However, I would like to generalize this so that whatever symbol I pass initially can be used to create the close vector.
```
library(quantmod)
library(wmtsa)
library(ggplot2)
library(tseries)
library(pracma)
s <- getSymbols("SPY")
s <- as.name(s)
field <- c(paste(s,".Close",sep=""))
close <- as.vector(s[,field])
```
If I were to just type in
```
close <- as.vector(SPY[,"SPY.Close"])
```
this is successful. However they are constants and would need to be changed with every new symbol.
Any help would be appreciated.
|
2015/01/28
|
[
"https://Stackoverflow.com/questions/28198893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504163/"
] |
In above arulmr answer just edit char field
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
invoice_int = int(invoice_no.split('MAG')[-1])
width = 4
new_invoice_int = invoice_int + 1
formatted = (width - len(str(new_invoice_int))) * "0" + str(new_invoice_int)
new_invoice_no = 'MAG' + str(formatted)
return new_invoice_no
class Invoice(models.Model):
invoice_no = models.CharField(max_length = 500, default = increment_invoice_number, null = True, blank = True)
```
This will work fine.
|
```
def invoice_number_gen():
last_invoice = Invoice.objects.all().order_by('id').last()
last_invoice_number = last_invoice.invoice_no
#invoice number format is 'customer_name_short + number' eg: CS003
last_invoice_digits =int(last_invoice_number[2:])
#comment: slicing CS003 to get the number 003 and converting to int.
last_invoice_initials = last_invoice_number[:2]
new_invoice_digits = last_invoice_digits + 1
new_invoice_number = last_invoice_initials + str(new_invoice_digits)
return (new_invoice_number)
```
|
28,198,893
|
I am trying to extract the SPY.Close column from the data frame SPY which is created by quantmod. However, I would like to generalize this so that whatever symbol I pass initially can be used to create the close vector.
```
library(quantmod)
library(wmtsa)
library(ggplot2)
library(tseries)
library(pracma)
s <- getSymbols("SPY")
s <- as.name(s)
field <- c(paste(s,".Close",sep=""))
close <- as.vector(s[,field])
```
If I were to just type in
```
close <- as.vector(SPY[,"SPY.Close"])
```
this is successful. However they are constants and would need to be changed with every new symbol.
Any help would be appreciated.
|
2015/01/28
|
[
"https://Stackoverflow.com/questions/28198893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4504163/"
] |
Maybe this code can help
```
def increment_invoice_number():
last_invoice = Invoice.objects.all().order_by('id').last()
if not last_invoice:
return 'MAG0001'
invoice_no = last_invoice.invoice_no
new_invoice_no = str(int(invoice_no[4:]) + 1)
new_invoice_no = invoice_no[0:-(len(new_invoice_no))] + new_invoice_no
return new_invoice_no
```
|
```
def invoice_number_gen():
last_invoice = Invoice.objects.all().order_by('id').last()
last_invoice_number = last_invoice.invoice_no
#invoice number format is 'customer_name_short + number' eg: CS003
last_invoice_digits =int(last_invoice_number[2:])
#comment: slicing CS003 to get the number 003 and converting to int.
last_invoice_initials = last_invoice_number[:2]
new_invoice_digits = last_invoice_digits + 1
new_invoice_number = last_invoice_initials + str(new_invoice_digits)
return (new_invoice_number)
```
|
14,292,750
|
What's the best way to programmatically determine if the current machine is running Ubuntu, what architecture it has, and what version of Ubuntu it is running?
One way would be to scan the output of `uname -a` to check for the right kernel version and architecture.
Another way would be to scan `/etc/apt/sources.list` for the Ubuntu distribution keyword (eq `precise`, `quantal`, etc)
Is there a better way?
|
2013/01/12
|
[
"https://Stackoverflow.com/questions/14292750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1131467/"
] |
>
> One way would be to scan the output of uname -a to check for the right kernel version and architecture.
>
>
>
But one does not generally want to parse the output of such tools, because it's not elegant (it's considered a hack, so to say).
However, you can use the `uname()` function/syscall:
```
#include <sys/utsname.h>
struct utsname sysinfo;
if (uname(&sysinfo) < 0) {
printf("Cannot determine OS\n");
exit(-1);
}
printf("Operating system name: %s\n", sysinfo.sysname);
```
|
Afaik most Linux distributions also use `/etc/issue`. The text in it can ofcourse have been changed by the admin to show a different login message.
Sample from fedora:
```
Fedora release 17 (Beefy Miracle)
Kernel \r on an \m (\l)
```
Sample from ubuntu:
```
Ubuntu 11.04 \n \l
```
|
14,292,750
|
What's the best way to programmatically determine if the current machine is running Ubuntu, what architecture it has, and what version of Ubuntu it is running?
One way would be to scan the output of `uname -a` to check for the right kernel version and architecture.
Another way would be to scan `/etc/apt/sources.list` for the Ubuntu distribution keyword (eq `precise`, `quantal`, etc)
Is there a better way?
|
2013/01/12
|
[
"https://Stackoverflow.com/questions/14292750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1131467/"
] |
Apart from `uname -a`, There are several way to get information about the current distribution.
1. The best way is to parse the release files. They usually ended with `-release` or `_release` and located in `/etc`. Following command will find them all.
```
ls /etc/*{-,_}release
```
* Ubuntu uses `lsb_release`
* Redhat/Fedora uses `redhat-release`
* Slackware uses `slackware-release`
* Gentoo uses `gentoo-release`
Debian's corresponding file is `/etc/debian_version`. This file will also (somewhat misleadingly, but for a good reason) be present on Ubuntu systems, though.
1. Another file is `/etc/issue` which is used for machine identification and pre-login prompt can be used to determine current distribution information.
2. System information can be found in `/proc/version` too.
```
cat /proc/version
```
|
Afaik most Linux distributions also use `/etc/issue`. The text in it can ofcourse have been changed by the admin to show a different login message.
Sample from fedora:
```
Fedora release 17 (Beefy Miracle)
Kernel \r on an \m (\l)
```
Sample from ubuntu:
```
Ubuntu 11.04 \n \l
```
|
14,292,750
|
What's the best way to programmatically determine if the current machine is running Ubuntu, what architecture it has, and what version of Ubuntu it is running?
One way would be to scan the output of `uname -a` to check for the right kernel version and architecture.
Another way would be to scan `/etc/apt/sources.list` for the Ubuntu distribution keyword (eq `precise`, `quantal`, etc)
Is there a better way?
|
2013/01/12
|
[
"https://Stackoverflow.com/questions/14292750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1131467/"
] |
You can use a library as a neutral to the operating system. A solution is [lsb](http://www.linuxfoundation.org/collaborate/workgroups/lsb/lsb-41-release-notes)and your question became close to [using lsb question](https://stackoverflow.com/questions/1337329/determine-linux-version-from-java).
|
Afaik most Linux distributions also use `/etc/issue`. The text in it can ofcourse have been changed by the admin to show a different login message.
Sample from fedora:
```
Fedora release 17 (Beefy Miracle)
Kernel \r on an \m (\l)
```
Sample from ubuntu:
```
Ubuntu 11.04 \n \l
```
|
33,935,373
|
I `WPF/C#` desktop application, how to get the country where the user currently is running the application ?
I quess the following just returns the value based on whatever is selected in regional and language options of the Control Panel, therefore making it unusable here.
```
string countryName = RegionInfo.CurrentRegion.DisplayName;
```
Found this site for utilizing IP address:
<http://www.hostip.info/use.html>
but this is a corporate application and wondering if used in a corporate VPN therefore possible returning an incorrect country (I want the country where the user is currently sitting physically).
What would be the preferred (most reliable) way to get the country in this setting ?
|
2015/11/26
|
[
"https://Stackoverflow.com/questions/33935373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2143213/"
] |
Your problem is probably that you model class is not a clean JavaBean. At the moment Spark has no code to deal with properties that have a setter but no getter method. You can simply try something like this to inspect how Spark understands your class:
```
PropertyDescriptor[] props = Introspector.getBeanInfo(YourClass.class).getPropertyDescriptors();
for(PropertyDescriptor prop:props) {
System.out.println(prop.getDisplayName());
System.out.println("\t"+prop.getReadMethod());
System.out.println("\t"+prop.getWriteMethod());
}
```
The introspector also recognizes fields that only have a setter as preoperties, which throws the NullPointerException in Spark.
|
Here is what I tried and it worked: -
Here is POJO which stores String, Long and Int Values: -
```
import java.io.*;
public class TestingSQLPerson implements Serializable {
// Here is Data in a comma Separated file: -
// Sumit,20,123455
// Ramit,40,12345
private String name;
private int age;
private Long testL;
public Long getTestL() {
return testL;
}
public void setTestL(Long testL) {
this.testL = testL;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
And here is the Spark SQL Code in Java: -
```
import org.apache.spark.*;
import org.apache.spark.sql.*;
import org.apache.spark.api.java.*;
import org.apache.spark.api.java.function.Function;
public class TestingLongSQLTypes {
public static void main(String[] args) {
SparkConf javaConf = new SparkConf();
javaConf.setAppName("Test Long TTyypes");
JavaSparkContext javaCtx = new JavaSparkContext(javaConf);
SQLContext sqlContext = new org.apache.spark.sql.SQLContext(javaCtx);
String dataFile = "file:///home/ec2-user/softwares/crime-data/testfile.txt";
JavaRDD<TestingSQLPerson> people = javaCtx.textFile(dataFile).map(
new Function<String, TestingSQLPerson>() {
public TestingSQLPerson call(String line) throws Exception {
String[] parts = line.split(",");
TestingSQLPerson person = new TestingSQLPerson();
person.setName(parts[0]);
person.setAge(Integer.parseInt(parts[1].trim()));
person.setTestL(Long.parseLong(parts[2].trim()));
return person;
}
});
// Apply a schema to an RDD of JavaBeans and register it as a table.
DataFrame schemaPeople = sqlContext.createDataFrame(people, TestingSQLPerson.class);
schemaPeople.registerTempTable("TestingSQLPerson");
schemaPeople.printSchema();
schemaPeople.show();
}
}
```
All of the Above work and finally on the driver console i could see the results without any errors of Exception.
@Yukti - In your case, It should work too, provided you follow the same steps as defined in the above examples. In case, there is any deviation, then let me know, I can try helping you.
|
12,720,559
|
```
String text = "select ename from emp";
```
I want to know the space index after the word **from**. How to do it?
|
2012/10/04
|
[
"https://Stackoverflow.com/questions/12720559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659254/"
] |
If you're specifically looking for the index of the first space after the word "from", you can use:
```
text.substring(text.indexOf("from")).indexOf(' ');
```
If you're trying to do something more general, than you'll need to give a bit more information. But the indexOf() method will probably be very useful to you.
Edit: This should actually be
```
text.indexOf(' ', text.indexOf("from"));
```
The first version returns the index relative to "from", whereas the second returns the index relative to the original string. (thanks @jpm)
This loop will find all space characters in the given string:
```
int index = text.indexOf(' ');
while (index >= 0) {
System.out.println(index);
index = text.indexOf(' ', index + 1);
}
```
|
The very basic answer might look something like...
```
String text = "select ename from emp";
text = text.toLowerCase();
if (text.contains("from ")) {
int index = text.indexOf("from ") + "from".length();
System.out.println("Found space @ " + index);
System.out.println(text.substring(index));
} else {
System.out.println(text + " does not contain `from `");
}
```
Or you could use some regular expression (this is a rather poor example, but hay)
```
Pattern pattern = Pattern.compile("from ");
Matcher matcher = pattern.matcher(text);
String match = null;
int endIndex = -1;
if (matcher.find()) {
endIndex = matcher.end();
}
if (endIndex > -1) {
endIndex--;
System.out.println("Found space @ " + endIndex);
System.out.println(text.substring(endIndex));
} else {
System.out.println(text + " does not contain `from `");
}
```
To find the index of each space you could do something like...
```
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(text);
String match = null;
while (matcher.find()) {
System.out.println(matcher.start());
}
```
Which will output
```
6
12
17
```
|
12,720,559
|
```
String text = "select ename from emp";
```
I want to know the space index after the word **from**. How to do it?
|
2012/10/04
|
[
"https://Stackoverflow.com/questions/12720559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659254/"
] |
If you're specifically looking for the index of the first space after the word "from", you can use:
```
text.substring(text.indexOf("from")).indexOf(' ');
```
If you're trying to do something more general, than you'll need to give a bit more information. But the indexOf() method will probably be very useful to you.
Edit: This should actually be
```
text.indexOf(' ', text.indexOf("from"));
```
The first version returns the index relative to "from", whereas the second returns the index relative to the original string. (thanks @jpm)
This loop will find all space characters in the given string:
```
int index = text.indexOf(' ');
while (index >= 0) {
System.out.println(index);
index = text.indexOf(' ', index + 1);
}
```
|
use indexOf() method. Hope u got the answer
|
12,720,559
|
```
String text = "select ename from emp";
```
I want to know the space index after the word **from**. How to do it?
|
2012/10/04
|
[
"https://Stackoverflow.com/questions/12720559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659254/"
] |
The very basic answer might look something like...
```
String text = "select ename from emp";
text = text.toLowerCase();
if (text.contains("from ")) {
int index = text.indexOf("from ") + "from".length();
System.out.println("Found space @ " + index);
System.out.println(text.substring(index));
} else {
System.out.println(text + " does not contain `from `");
}
```
Or you could use some regular expression (this is a rather poor example, but hay)
```
Pattern pattern = Pattern.compile("from ");
Matcher matcher = pattern.matcher(text);
String match = null;
int endIndex = -1;
if (matcher.find()) {
endIndex = matcher.end();
}
if (endIndex > -1) {
endIndex--;
System.out.println("Found space @ " + endIndex);
System.out.println(text.substring(endIndex));
} else {
System.out.println(text + " does not contain `from `");
}
```
To find the index of each space you could do something like...
```
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(text);
String match = null;
while (matcher.find()) {
System.out.println(matcher.start());
}
```
Which will output
```
6
12
17
```
|
use indexOf() method. Hope u got the answer
|
31,251,171
|
I am new to html/css but was assigned to get a html webpage done. When I specified a `font-size` for my webpage and was surprised to find that it was adjusted by my browser (Google Chrome), but I'm not sure why. I specified the `font-size` at `14px` and it was adjusted to be `14.3999996185303px` by the browser, which makes my webpage a little ugly. I would like to understand when the browser will change the value I specify and how I can force the browser to use the value I specify. It would be great if someone can refer me to some material so I can have a good understanding of it.
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31251171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3398461/"
] |
Without `FlexibleContexts` all typeclass constraints on function definitions must have type variables. For example:
```
add :: Num a => a -> a -> a
add = (+)
```
Where `a` is the type variable. With `FlexibleContexts` enabled you can have any type inside a typeclass.
```
intAdd :: Num Int => Int -> Int -> Int
intAdd = (+)
```
This example is pretty contrived but it is the simplest I can think of. `FlexibleContexts` is usually only used with `MultiParamTypeClasses`. Here is an example:
```
class Shower a b where
myShow :: a -> b
doSomething :: Shower a String => a -> String
doSomething = myShow
```
Here you can see we say that we only want a `Shower a String`. Without `FlexibleContexts` `String` would have to be a type variable instead of a concrete type.
|
Commonly it's used with the `MultiParamTypeClasses` extension, for example when using the `mtl` library you might write
```
doSomethingWithState :: MonadState MyState m => m ()
doSomethingWithState = do
current <- get
let something1 = computeSomething1 current
something2 = computeSomething2 current something1
put something2
```
And similarly with `MonadReader` and `MonadWriter`, along with other similar typeclasses. Without `FlexibleContexts` you can't use this constraint.
(Note that this answer was based on [@DiegoNolan's](https://stackoverflow.com/a/31252435/839246) but rewritten to use an existing library that should make sense to LYAH readers).
|
31,251,171
|
I am new to html/css but was assigned to get a html webpage done. When I specified a `font-size` for my webpage and was surprised to find that it was adjusted by my browser (Google Chrome), but I'm not sure why. I specified the `font-size` at `14px` and it was adjusted to be `14.3999996185303px` by the browser, which makes my webpage a little ugly. I would like to understand when the browser will change the value I specify and how I can force the browser to use the value I specify. It would be great if someone can refer me to some material so I can have a good understanding of it.
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31251171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3398461/"
] |
Without `FlexibleContexts` all typeclass constraints on function definitions must have type variables. For example:
```
add :: Num a => a -> a -> a
add = (+)
```
Where `a` is the type variable. With `FlexibleContexts` enabled you can have any type inside a typeclass.
```
intAdd :: Num Int => Int -> Int -> Int
intAdd = (+)
```
This example is pretty contrived but it is the simplest I can think of. `FlexibleContexts` is usually only used with `MultiParamTypeClasses`. Here is an example:
```
class Shower a b where
myShow :: a -> b
doSomething :: Shower a String => a -> String
doSomething = myShow
```
Here you can see we say that we only want a `Shower a String`. Without `FlexibleContexts` `String` would have to be a type variable instead of a concrete type.
|
I've discovered a use for it apart from those mentioned: it results in clearer error messages from GHC. E.g. normally,
```
Prelude> max (1, 2) 3
<interactive>:1:1: error:
• Non type-variable argument in the constraint: Num (a, b)
(Use FlexibleContexts to permit this)
• When checking the inferred type
it :: forall a b.
(Num (a, b), Num b, Num a, Ord b, Ord a) =>
(a, b)
```
And with FlexibleContexts enabled:
```
Prelude> max (1, 2) 3
<interactive>:1:1: error:
• No instance for (Num (Integer, Integer))
arising from a use of ‘it’
• In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it
```
Here's [a discussion](https://www.reddit.com/r/haskellquestions/comments/9c98hk/help_understanding_the_error_message_for_max_1_2_3/).
|
31,251,171
|
I am new to html/css but was assigned to get a html webpage done. When I specified a `font-size` for my webpage and was surprised to find that it was adjusted by my browser (Google Chrome), but I'm not sure why. I specified the `font-size` at `14px` and it was adjusted to be `14.3999996185303px` by the browser, which makes my webpage a little ugly. I would like to understand when the browser will change the value I specify and how I can force the browser to use the value I specify. It would be great if someone can refer me to some material so I can have a good understanding of it.
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31251171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3398461/"
] |
Without `FlexibleContexts` all typeclass constraints on function definitions must have type variables. For example:
```
add :: Num a => a -> a -> a
add = (+)
```
Where `a` is the type variable. With `FlexibleContexts` enabled you can have any type inside a typeclass.
```
intAdd :: Num Int => Int -> Int -> Int
intAdd = (+)
```
This example is pretty contrived but it is the simplest I can think of. `FlexibleContexts` is usually only used with `MultiParamTypeClasses`. Here is an example:
```
class Shower a b where
myShow :: a -> b
doSomething :: Shower a String => a -> String
doSomething = myShow
```
Here you can see we say that we only want a `Shower a String`. Without `FlexibleContexts` `String` would have to be a type variable instead of a concrete type.
|
`FlexibleContexts` is often used with type families. For example, when using `GHC.Generics`, it's common to see signatures like
```
foo :: (Generic a, GFoo (Rep a)) => Int -> a -> a
```
This can be seen as a variation of the `MultiParamTypeClasses` usage:
```
class (Generic a, rep ~ Rep a) => MPGeneric rep a
instance (Generic a, rep ~ Rep a) => MPGeneric rep a
mpFoo :: (MPGeneric rep a, GFoo rep) => Int -> a -> a
```
As [AJFarmar pointed out](https://stackoverflow.com/questions/31251163/what-is-the-flexiblecontexts-extension-good-for-could-you-please-explain-it-usi#comment50507992_31252435), `FlexibleContexts` is also useful with neither MPTCs nor type families. Here's a simple example:
```
newtype Ap f a = Ap (f a)
deriving instance Show (f a) => Show (Ap f a)
```
The alternative approach using `Show1` is significantly more awkward.
A more involved example is provided by AJFarmar's comment:
```
data Free f a = Pure a | Free (f (Free f a))
deriving instance (Show a, Show (f (Free f a))) => Show (Free f a)
```
This brings in `UndecidableInstances` as well, since it's recursive, but it does a good job of explaining just what it needs to be able to show `Free f a`. In bleeding-edge GHC Haskell, an alternative would be to use `QuantifiedConstraints`:
```
deriving instance (Show a, forall x. Show x => Show (f x)) => Show (Free f a)
```
but this is overkill because we only need to show `f` applied to `Free f a`.
|
31,251,171
|
I am new to html/css but was assigned to get a html webpage done. When I specified a `font-size` for my webpage and was surprised to find that it was adjusted by my browser (Google Chrome), but I'm not sure why. I specified the `font-size` at `14px` and it was adjusted to be `14.3999996185303px` by the browser, which makes my webpage a little ugly. I would like to understand when the browser will change the value I specify and how I can force the browser to use the value I specify. It would be great if someone can refer me to some material so I can have a good understanding of it.
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31251171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3398461/"
] |
Commonly it's used with the `MultiParamTypeClasses` extension, for example when using the `mtl` library you might write
```
doSomethingWithState :: MonadState MyState m => m ()
doSomethingWithState = do
current <- get
let something1 = computeSomething1 current
something2 = computeSomething2 current something1
put something2
```
And similarly with `MonadReader` and `MonadWriter`, along with other similar typeclasses. Without `FlexibleContexts` you can't use this constraint.
(Note that this answer was based on [@DiegoNolan's](https://stackoverflow.com/a/31252435/839246) but rewritten to use an existing library that should make sense to LYAH readers).
|
`FlexibleContexts` is often used with type families. For example, when using `GHC.Generics`, it's common to see signatures like
```
foo :: (Generic a, GFoo (Rep a)) => Int -> a -> a
```
This can be seen as a variation of the `MultiParamTypeClasses` usage:
```
class (Generic a, rep ~ Rep a) => MPGeneric rep a
instance (Generic a, rep ~ Rep a) => MPGeneric rep a
mpFoo :: (MPGeneric rep a, GFoo rep) => Int -> a -> a
```
As [AJFarmar pointed out](https://stackoverflow.com/questions/31251163/what-is-the-flexiblecontexts-extension-good-for-could-you-please-explain-it-usi#comment50507992_31252435), `FlexibleContexts` is also useful with neither MPTCs nor type families. Here's a simple example:
```
newtype Ap f a = Ap (f a)
deriving instance Show (f a) => Show (Ap f a)
```
The alternative approach using `Show1` is significantly more awkward.
A more involved example is provided by AJFarmar's comment:
```
data Free f a = Pure a | Free (f (Free f a))
deriving instance (Show a, Show (f (Free f a))) => Show (Free f a)
```
This brings in `UndecidableInstances` as well, since it's recursive, but it does a good job of explaining just what it needs to be able to show `Free f a`. In bleeding-edge GHC Haskell, an alternative would be to use `QuantifiedConstraints`:
```
deriving instance (Show a, forall x. Show x => Show (f x)) => Show (Free f a)
```
but this is overkill because we only need to show `f` applied to `Free f a`.
|
31,251,171
|
I am new to html/css but was assigned to get a html webpage done. When I specified a `font-size` for my webpage and was surprised to find that it was adjusted by my browser (Google Chrome), but I'm not sure why. I specified the `font-size` at `14px` and it was adjusted to be `14.3999996185303px` by the browser, which makes my webpage a little ugly. I would like to understand when the browser will change the value I specify and how I can force the browser to use the value I specify. It would be great if someone can refer me to some material so I can have a good understanding of it.
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31251171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3398461/"
] |
I've discovered a use for it apart from those mentioned: it results in clearer error messages from GHC. E.g. normally,
```
Prelude> max (1, 2) 3
<interactive>:1:1: error:
• Non type-variable argument in the constraint: Num (a, b)
(Use FlexibleContexts to permit this)
• When checking the inferred type
it :: forall a b.
(Num (a, b), Num b, Num a, Ord b, Ord a) =>
(a, b)
```
And with FlexibleContexts enabled:
```
Prelude> max (1, 2) 3
<interactive>:1:1: error:
• No instance for (Num (Integer, Integer))
arising from a use of ‘it’
• In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it
```
Here's [a discussion](https://www.reddit.com/r/haskellquestions/comments/9c98hk/help_understanding_the_error_message_for_max_1_2_3/).
|
`FlexibleContexts` is often used with type families. For example, when using `GHC.Generics`, it's common to see signatures like
```
foo :: (Generic a, GFoo (Rep a)) => Int -> a -> a
```
This can be seen as a variation of the `MultiParamTypeClasses` usage:
```
class (Generic a, rep ~ Rep a) => MPGeneric rep a
instance (Generic a, rep ~ Rep a) => MPGeneric rep a
mpFoo :: (MPGeneric rep a, GFoo rep) => Int -> a -> a
```
As [AJFarmar pointed out](https://stackoverflow.com/questions/31251163/what-is-the-flexiblecontexts-extension-good-for-could-you-please-explain-it-usi#comment50507992_31252435), `FlexibleContexts` is also useful with neither MPTCs nor type families. Here's a simple example:
```
newtype Ap f a = Ap (f a)
deriving instance Show (f a) => Show (Ap f a)
```
The alternative approach using `Show1` is significantly more awkward.
A more involved example is provided by AJFarmar's comment:
```
data Free f a = Pure a | Free (f (Free f a))
deriving instance (Show a, Show (f (Free f a))) => Show (Free f a)
```
This brings in `UndecidableInstances` as well, since it's recursive, but it does a good job of explaining just what it needs to be able to show `Free f a`. In bleeding-edge GHC Haskell, an alternative would be to use `QuantifiedConstraints`:
```
deriving instance (Show a, forall x. Show x => Show (f x)) => Show (Free f a)
```
but this is overkill because we only need to show `f` applied to `Free f a`.
|
9,520,148
|
I am designing a theme layout for my web app.
Let's say if I have two controllers,A and B. I want A view to display div A and B view will display div B.
I know how to set this inside the controller by utilizing `if($this->router->fetch_class() == 'A')
{
//display div A
}`
But, how to achieve this in view?
|
2012/03/01
|
[
"https://Stackoverflow.com/questions/9520148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/992972/"
] |
For several of your cross-classifications you have missing covariates:
```
with(masterData, table(sample, substrate, r1mis = is.na(r1) ) )
#
snipped the nonmissing reports
, , r1mis = TRUE
substrate
sample 1 2 3 4 5 6 7 8
3 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0
5 0 0 0 0 0 0 0 0
6 0 0 0 0 0 0 0 0
7 0 0 0 0 0 0 3 3
8 0 0 0 0 0 0 0 3
9 0 0 0 0 0 0 0 3
10 0 0 0 0 0 0 0 3
11 0 0 0 0 0 0 0 3
12 0 0 0 0 0 0 0 3
13 0 0 0 0 0 0 0 3
14 0 0 0 0 0 0 0 3
```
This would let you skip over the subsets with insufficient data in this particular data:
```
meanSlope <- function(df) { if ( sum(!is.na(df$el1)) < 2 ) { return(NA) } else {
lm1 <- lm(df$F1 ~ df$el1, na.action=na.omit) #changing to na.exclude doesn't help
slope1 <- lm1$coefficients[2]
meanSlope <- mean(c(slope1)) }
}
```
Although it depends on the missingness being in one particular covariate. A more robust solution would be to use `try` to capture errors and convert to NA's.
```
?try
```
|
As per my comment:
```
my.func <- function(df) {
data.frame(el1=all(is.na(df$el1)), F1=all(is.na(df$F1)))
}
ddply(workingData, .(sample, substrate), my.func)
```
Shows that you have many sub sets where both F1 and el1 are NA. (in fact every time one is all na, the other is as well!)
|
34,675,357
|
i have a multiple array.. the output looks like this:
```
Array
(
[0] => Array
(
[0] => AdsBot
[1] => 7
)
[1] => Array
(
[0] => SurveyBot
[1] => 1
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => bot
[1] => 27
)
```
what i need now is to sort arrays by there number.. so it should look exactly like this:
```
Array
(
[0] => Array
(
[0] => bot
[1] => 27
)
[1] => Array
(
[0] => AdsBot
[1] => 7
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => SurveyBot
[1] => 1
)
```
i need to sort it by the numbers array key.. but i really dont know how- well, i'm new to php
the multi. array code :
```
$bot_array = [
['name' => 'bingbot', 'number' => $bingbot],
['name' => 'googlebot', 'number' => $googlebot],
['name' => 'robots.txt', 'number' => $robots_txt],
['name' => 'exabot', 'number' => $exabot],
['name' => 'bot', 'number' => $bot],
['name' => 'robot', 'number' => $robot],
['name' => 'BaiDuSpider', 'number' => $BaiDuSpider],
['name' => 'Yahoo Slurp', 'number' => $yahoo_slurp],
['name' => 'AdsBot', 'number' => $adsbot],
['name' => 'SurveyBot', 'number' => $surveybot],
['name' => 'scanner', 'number' => $scanner],
['name' => 'checker', 'number' => $checker],
];
```
or maybe there is a more smarter way to do this?
i need this for a top ten :) on the left should be written all the names and at the right the quantity
thanks for any help :)
EDIT:
```
$tmp = Array();
foreach($bot_array as &$ba)
$tmp[] = &$ba["number"];
array_multisort($tmp, $bot_array);
foreach($bot_array as &$ba)
echo $ba["number"]."<br/>";
```
i did this but it still doesnt sort it like i want it..
```
0
0
0
1
10
12
27
3
3
5
7
9
```
this is what it gives me now :o
|
2016/01/08
|
[
"https://Stackoverflow.com/questions/34675357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5658705/"
] |
you can use this function
```
function sortAscending($accounts, $key)
{
$ascending = function($accountA, $accountB) use ($key) {
if ($accountA[$key] == $accountB[$key]) {
return 0;
}
return ($accountA[$key] < $accountB[$key]) ? -1 : 1;
};
usort($accounts, $ascending);
return $accounts;
}
```
|
Try [`usort()`](http://php.net/manual/en/function.usort.php). It allows you to define a callback to sort on a custom expression. In your case you want to reverse sort by the second indexed element in each sub-array:
```
<?php
$bots = [
[
'name' => 'AdsBot',
'number' => 7,
],
[
'name' => 'SurveyBot',
'number' => 1,
],
[
'name' => 'bingbot',
'number' => 3,
],
[
'name' => 'bot',
'number' => 27,
],
];
usort($bots, function($a, $b) {
return $a['number'] <= $b['number'];
});
print_r($bots);
```
Yields:
```
Array
(
[0] => Array
(
[name] => bot
[number] => 27
)
[1] => Array
(
[name] => AdsBot
[number] => 7
)
[2] => Array
(
[name] => bingbot
[number] => 3
)
[3] => Array
(
[name] => SurveyBot
[number] => 1
)
)
```
Hope this helps :)
|
34,675,357
|
i have a multiple array.. the output looks like this:
```
Array
(
[0] => Array
(
[0] => AdsBot
[1] => 7
)
[1] => Array
(
[0] => SurveyBot
[1] => 1
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => bot
[1] => 27
)
```
what i need now is to sort arrays by there number.. so it should look exactly like this:
```
Array
(
[0] => Array
(
[0] => bot
[1] => 27
)
[1] => Array
(
[0] => AdsBot
[1] => 7
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => SurveyBot
[1] => 1
)
```
i need to sort it by the numbers array key.. but i really dont know how- well, i'm new to php
the multi. array code :
```
$bot_array = [
['name' => 'bingbot', 'number' => $bingbot],
['name' => 'googlebot', 'number' => $googlebot],
['name' => 'robots.txt', 'number' => $robots_txt],
['name' => 'exabot', 'number' => $exabot],
['name' => 'bot', 'number' => $bot],
['name' => 'robot', 'number' => $robot],
['name' => 'BaiDuSpider', 'number' => $BaiDuSpider],
['name' => 'Yahoo Slurp', 'number' => $yahoo_slurp],
['name' => 'AdsBot', 'number' => $adsbot],
['name' => 'SurveyBot', 'number' => $surveybot],
['name' => 'scanner', 'number' => $scanner],
['name' => 'checker', 'number' => $checker],
];
```
or maybe there is a more smarter way to do this?
i need this for a top ten :) on the left should be written all the names and at the right the quantity
thanks for any help :)
EDIT:
```
$tmp = Array();
foreach($bot_array as &$ba)
$tmp[] = &$ba["number"];
array_multisort($tmp, $bot_array);
foreach($bot_array as &$ba)
echo $ba["number"]."<br/>";
```
i did this but it still doesnt sort it like i want it..
```
0
0
0
1
10
12
27
3
3
5
7
9
```
this is what it gives me now :o
|
2016/01/08
|
[
"https://Stackoverflow.com/questions/34675357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5658705/"
] |
you can use this function
```
function sortAscending($accounts, $key)
{
$ascending = function($accountA, $accountB) use ($key) {
if ($accountA[$key] == $accountB[$key]) {
return 0;
}
return ($accountA[$key] < $accountB[$key]) ? -1 : 1;
};
usort($accounts, $ascending);
return $accounts;
}
```
|
Please, see bellow code.
```
$arr = array(
0 => array(
'0' => 'AdsBot',
'1' => 7
),
1 => array(
'0' => 'SurveyBot',
'1' => 1
),
2 => array(
'0' => 'bingbot',
'1' => 3
),
3 => array(
'0' => 'bot',
'1' => 27
)
);
echo '<pre>';
print_r(sortDescOrder($arr,'1'));
echo '</pre>';
function sortDescOrder($accounts, $key)
{
$ascending = function($accountA, $accountB) use ($key) {
if ($accountA[$key] == $accountB[$key]) {
return 0;
}
return ($accountA[$key] > $accountB[$key]) ? -1 : 1;
};
usort($accounts, $ascending);
return $accounts;
}
```
Or see another code
```
$bot_array = [
['name' => 'bingbot', 'number' => 5],
['name' => 'googlebot', 'number' => 8],
['name' => 'robots.txt', 'number' => 3],
['name' => 'exabot', 'number' => 7],
['name' => 'bot', 'number' => 7],
['name' => 'robot', 'number' => 12],
['name' => 'BaiDuSpider', 'number' => 45],
['name' => 'Yahoo Slurp', 'number' => 18],
['name' => 'AdsBot', 'number' => 78],
['name' => 'SurveyBot', 'number' => 96],
['name' => 'scanner', 'number' => 41],
['name' => 'checker', 'number' => 10]
];
usort($bot_array, function($x, $y) {
return $x['number'] <= $y['number'];
});
echo '<pre>';
print_r($bot_array);
echo '</pre>';
```
|
34,675,357
|
i have a multiple array.. the output looks like this:
```
Array
(
[0] => Array
(
[0] => AdsBot
[1] => 7
)
[1] => Array
(
[0] => SurveyBot
[1] => 1
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => bot
[1] => 27
)
```
what i need now is to sort arrays by there number.. so it should look exactly like this:
```
Array
(
[0] => Array
(
[0] => bot
[1] => 27
)
[1] => Array
(
[0] => AdsBot
[1] => 7
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => SurveyBot
[1] => 1
)
```
i need to sort it by the numbers array key.. but i really dont know how- well, i'm new to php
the multi. array code :
```
$bot_array = [
['name' => 'bingbot', 'number' => $bingbot],
['name' => 'googlebot', 'number' => $googlebot],
['name' => 'robots.txt', 'number' => $robots_txt],
['name' => 'exabot', 'number' => $exabot],
['name' => 'bot', 'number' => $bot],
['name' => 'robot', 'number' => $robot],
['name' => 'BaiDuSpider', 'number' => $BaiDuSpider],
['name' => 'Yahoo Slurp', 'number' => $yahoo_slurp],
['name' => 'AdsBot', 'number' => $adsbot],
['name' => 'SurveyBot', 'number' => $surveybot],
['name' => 'scanner', 'number' => $scanner],
['name' => 'checker', 'number' => $checker],
];
```
or maybe there is a more smarter way to do this?
i need this for a top ten :) on the left should be written all the names and at the right the quantity
thanks for any help :)
EDIT:
```
$tmp = Array();
foreach($bot_array as &$ba)
$tmp[] = &$ba["number"];
array_multisort($tmp, $bot_array);
foreach($bot_array as &$ba)
echo $ba["number"]."<br/>";
```
i did this but it still doesnt sort it like i want it..
```
0
0
0
1
10
12
27
3
3
5
7
9
```
this is what it gives me now :o
|
2016/01/08
|
[
"https://Stackoverflow.com/questions/34675357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5658705/"
] |
you can use this function
```
function sortAscending($accounts, $key)
{
$ascending = function($accountA, $accountB) use ($key) {
if ($accountA[$key] == $accountB[$key]) {
return 0;
}
return ($accountA[$key] < $accountB[$key]) ? -1 : 1;
};
usort($accounts, $ascending);
return $accounts;
}
```
|
Use this way to sort your array
```
$arry = array( array('AdsBot','7'),
array('SurveyBot','1'),
array('bingbot','3'),
array('bot','27')
);
echo "<pre>"; print_r($arry); echo "</pre>";
function sortByOrder($a, $b) {
return $a['1'] - $b['1'];
}
usort($arry, 'sortByOrder');
echo "<pre>"; print_r($arry); echo "</pre>";
```
|
34,675,357
|
i have a multiple array.. the output looks like this:
```
Array
(
[0] => Array
(
[0] => AdsBot
[1] => 7
)
[1] => Array
(
[0] => SurveyBot
[1] => 1
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => bot
[1] => 27
)
```
what i need now is to sort arrays by there number.. so it should look exactly like this:
```
Array
(
[0] => Array
(
[0] => bot
[1] => 27
)
[1] => Array
(
[0] => AdsBot
[1] => 7
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => SurveyBot
[1] => 1
)
```
i need to sort it by the numbers array key.. but i really dont know how- well, i'm new to php
the multi. array code :
```
$bot_array = [
['name' => 'bingbot', 'number' => $bingbot],
['name' => 'googlebot', 'number' => $googlebot],
['name' => 'robots.txt', 'number' => $robots_txt],
['name' => 'exabot', 'number' => $exabot],
['name' => 'bot', 'number' => $bot],
['name' => 'robot', 'number' => $robot],
['name' => 'BaiDuSpider', 'number' => $BaiDuSpider],
['name' => 'Yahoo Slurp', 'number' => $yahoo_slurp],
['name' => 'AdsBot', 'number' => $adsbot],
['name' => 'SurveyBot', 'number' => $surveybot],
['name' => 'scanner', 'number' => $scanner],
['name' => 'checker', 'number' => $checker],
];
```
or maybe there is a more smarter way to do this?
i need this for a top ten :) on the left should be written all the names and at the right the quantity
thanks for any help :)
EDIT:
```
$tmp = Array();
foreach($bot_array as &$ba)
$tmp[] = &$ba["number"];
array_multisort($tmp, $bot_array);
foreach($bot_array as &$ba)
echo $ba["number"]."<br/>";
```
i did this but it still doesnt sort it like i want it..
```
0
0
0
1
10
12
27
3
3
5
7
9
```
this is what it gives me now :o
|
2016/01/08
|
[
"https://Stackoverflow.com/questions/34675357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5658705/"
] |
You can use [usort](http://php.net/manual/en/function.usort.php)
```
<?php
$data = array(
array('AdsBot', 7),
array('SurveyBot', 1),
array('bingbot', 3),
array('bot', 27)
);
usort($data, 'botSort');
function botSort($val1, $val2) {
if (is_array($val1) && is_array($val2)) {
if ($val1[1] <= $val2[1]) {
return 1;
}
}
return -1;
}
var_dump($data);
```
**Output**
```
array(4) {
[0] =>
array(2) {
[0] =>
string(3) "bot"
[1] =>
int(27)
}
[1] =>
array(2) {
[0] =>
string(6) "AdsBot"
[1] =>
int(7)
}
[2] =>
array(2) {
[0] =>
string(7) "bingbot"
[1] =>
int(3)
}
[3] =>
array(2) {
[0] =>
string(9) "SurveyBot"
[1] =>
int(1)
}
}
```
According to your updated question, it should be.
```
<?php
usort($bot_array, 'botSort');
function botSort($val1, $val2) {
if (is_array($val1) && is_array($val2)) {
if ($val1['number'] <= $val2['number']) {
return 1;
}
}
return -1;
}
print_r($data);
```
|
Try [`usort()`](http://php.net/manual/en/function.usort.php). It allows you to define a callback to sort on a custom expression. In your case you want to reverse sort by the second indexed element in each sub-array:
```
<?php
$bots = [
[
'name' => 'AdsBot',
'number' => 7,
],
[
'name' => 'SurveyBot',
'number' => 1,
],
[
'name' => 'bingbot',
'number' => 3,
],
[
'name' => 'bot',
'number' => 27,
],
];
usort($bots, function($a, $b) {
return $a['number'] <= $b['number'];
});
print_r($bots);
```
Yields:
```
Array
(
[0] => Array
(
[name] => bot
[number] => 27
)
[1] => Array
(
[name] => AdsBot
[number] => 7
)
[2] => Array
(
[name] => bingbot
[number] => 3
)
[3] => Array
(
[name] => SurveyBot
[number] => 1
)
)
```
Hope this helps :)
|
34,675,357
|
i have a multiple array.. the output looks like this:
```
Array
(
[0] => Array
(
[0] => AdsBot
[1] => 7
)
[1] => Array
(
[0] => SurveyBot
[1] => 1
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => bot
[1] => 27
)
```
what i need now is to sort arrays by there number.. so it should look exactly like this:
```
Array
(
[0] => Array
(
[0] => bot
[1] => 27
)
[1] => Array
(
[0] => AdsBot
[1] => 7
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => SurveyBot
[1] => 1
)
```
i need to sort it by the numbers array key.. but i really dont know how- well, i'm new to php
the multi. array code :
```
$bot_array = [
['name' => 'bingbot', 'number' => $bingbot],
['name' => 'googlebot', 'number' => $googlebot],
['name' => 'robots.txt', 'number' => $robots_txt],
['name' => 'exabot', 'number' => $exabot],
['name' => 'bot', 'number' => $bot],
['name' => 'robot', 'number' => $robot],
['name' => 'BaiDuSpider', 'number' => $BaiDuSpider],
['name' => 'Yahoo Slurp', 'number' => $yahoo_slurp],
['name' => 'AdsBot', 'number' => $adsbot],
['name' => 'SurveyBot', 'number' => $surveybot],
['name' => 'scanner', 'number' => $scanner],
['name' => 'checker', 'number' => $checker],
];
```
or maybe there is a more smarter way to do this?
i need this for a top ten :) on the left should be written all the names and at the right the quantity
thanks for any help :)
EDIT:
```
$tmp = Array();
foreach($bot_array as &$ba)
$tmp[] = &$ba["number"];
array_multisort($tmp, $bot_array);
foreach($bot_array as &$ba)
echo $ba["number"]."<br/>";
```
i did this but it still doesnt sort it like i want it..
```
0
0
0
1
10
12
27
3
3
5
7
9
```
this is what it gives me now :o
|
2016/01/08
|
[
"https://Stackoverflow.com/questions/34675357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5658705/"
] |
You can use [usort](http://php.net/manual/en/function.usort.php)
```
<?php
$data = array(
array('AdsBot', 7),
array('SurveyBot', 1),
array('bingbot', 3),
array('bot', 27)
);
usort($data, 'botSort');
function botSort($val1, $val2) {
if (is_array($val1) && is_array($val2)) {
if ($val1[1] <= $val2[1]) {
return 1;
}
}
return -1;
}
var_dump($data);
```
**Output**
```
array(4) {
[0] =>
array(2) {
[0] =>
string(3) "bot"
[1] =>
int(27)
}
[1] =>
array(2) {
[0] =>
string(6) "AdsBot"
[1] =>
int(7)
}
[2] =>
array(2) {
[0] =>
string(7) "bingbot"
[1] =>
int(3)
}
[3] =>
array(2) {
[0] =>
string(9) "SurveyBot"
[1] =>
int(1)
}
}
```
According to your updated question, it should be.
```
<?php
usort($bot_array, 'botSort');
function botSort($val1, $val2) {
if (is_array($val1) && is_array($val2)) {
if ($val1['number'] <= $val2['number']) {
return 1;
}
}
return -1;
}
print_r($data);
```
|
Please, see bellow code.
```
$arr = array(
0 => array(
'0' => 'AdsBot',
'1' => 7
),
1 => array(
'0' => 'SurveyBot',
'1' => 1
),
2 => array(
'0' => 'bingbot',
'1' => 3
),
3 => array(
'0' => 'bot',
'1' => 27
)
);
echo '<pre>';
print_r(sortDescOrder($arr,'1'));
echo '</pre>';
function sortDescOrder($accounts, $key)
{
$ascending = function($accountA, $accountB) use ($key) {
if ($accountA[$key] == $accountB[$key]) {
return 0;
}
return ($accountA[$key] > $accountB[$key]) ? -1 : 1;
};
usort($accounts, $ascending);
return $accounts;
}
```
Or see another code
```
$bot_array = [
['name' => 'bingbot', 'number' => 5],
['name' => 'googlebot', 'number' => 8],
['name' => 'robots.txt', 'number' => 3],
['name' => 'exabot', 'number' => 7],
['name' => 'bot', 'number' => 7],
['name' => 'robot', 'number' => 12],
['name' => 'BaiDuSpider', 'number' => 45],
['name' => 'Yahoo Slurp', 'number' => 18],
['name' => 'AdsBot', 'number' => 78],
['name' => 'SurveyBot', 'number' => 96],
['name' => 'scanner', 'number' => 41],
['name' => 'checker', 'number' => 10]
];
usort($bot_array, function($x, $y) {
return $x['number'] <= $y['number'];
});
echo '<pre>';
print_r($bot_array);
echo '</pre>';
```
|
34,675,357
|
i have a multiple array.. the output looks like this:
```
Array
(
[0] => Array
(
[0] => AdsBot
[1] => 7
)
[1] => Array
(
[0] => SurveyBot
[1] => 1
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => bot
[1] => 27
)
```
what i need now is to sort arrays by there number.. so it should look exactly like this:
```
Array
(
[0] => Array
(
[0] => bot
[1] => 27
)
[1] => Array
(
[0] => AdsBot
[1] => 7
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => SurveyBot
[1] => 1
)
```
i need to sort it by the numbers array key.. but i really dont know how- well, i'm new to php
the multi. array code :
```
$bot_array = [
['name' => 'bingbot', 'number' => $bingbot],
['name' => 'googlebot', 'number' => $googlebot],
['name' => 'robots.txt', 'number' => $robots_txt],
['name' => 'exabot', 'number' => $exabot],
['name' => 'bot', 'number' => $bot],
['name' => 'robot', 'number' => $robot],
['name' => 'BaiDuSpider', 'number' => $BaiDuSpider],
['name' => 'Yahoo Slurp', 'number' => $yahoo_slurp],
['name' => 'AdsBot', 'number' => $adsbot],
['name' => 'SurveyBot', 'number' => $surveybot],
['name' => 'scanner', 'number' => $scanner],
['name' => 'checker', 'number' => $checker],
];
```
or maybe there is a more smarter way to do this?
i need this for a top ten :) on the left should be written all the names and at the right the quantity
thanks for any help :)
EDIT:
```
$tmp = Array();
foreach($bot_array as &$ba)
$tmp[] = &$ba["number"];
array_multisort($tmp, $bot_array);
foreach($bot_array as &$ba)
echo $ba["number"]."<br/>";
```
i did this but it still doesnt sort it like i want it..
```
0
0
0
1
10
12
27
3
3
5
7
9
```
this is what it gives me now :o
|
2016/01/08
|
[
"https://Stackoverflow.com/questions/34675357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5658705/"
] |
You can use [usort](http://php.net/manual/en/function.usort.php)
```
<?php
$data = array(
array('AdsBot', 7),
array('SurveyBot', 1),
array('bingbot', 3),
array('bot', 27)
);
usort($data, 'botSort');
function botSort($val1, $val2) {
if (is_array($val1) && is_array($val2)) {
if ($val1[1] <= $val2[1]) {
return 1;
}
}
return -1;
}
var_dump($data);
```
**Output**
```
array(4) {
[0] =>
array(2) {
[0] =>
string(3) "bot"
[1] =>
int(27)
}
[1] =>
array(2) {
[0] =>
string(6) "AdsBot"
[1] =>
int(7)
}
[2] =>
array(2) {
[0] =>
string(7) "bingbot"
[1] =>
int(3)
}
[3] =>
array(2) {
[0] =>
string(9) "SurveyBot"
[1] =>
int(1)
}
}
```
According to your updated question, it should be.
```
<?php
usort($bot_array, 'botSort');
function botSort($val1, $val2) {
if (is_array($val1) && is_array($val2)) {
if ($val1['number'] <= $val2['number']) {
return 1;
}
}
return -1;
}
print_r($data);
```
|
Use this way to sort your array
```
$arry = array( array('AdsBot','7'),
array('SurveyBot','1'),
array('bingbot','3'),
array('bot','27')
);
echo "<pre>"; print_r($arry); echo "</pre>";
function sortByOrder($a, $b) {
return $a['1'] - $b['1'];
}
usort($arry, 'sortByOrder');
echo "<pre>"; print_r($arry); echo "</pre>";
```
|
7,050,957
|
OK. I'm starting out on Backbone.js, and trying to do some very simple things. Here's a very simple Model and Collection.
```
// my model
Friend = Backbone.Model.extend({});
// my collection
Friends = Backbone.Collection.extend({});
// instantiate friends and add some friends objects!
var friends = new Friends();
friends.add([
{name: "James"},
{name: "Michael"}
]);
console.log(friends.length) // prints out 2! which is correct!
```
Above example is fine. But now I want to initialize my collection from server, which returns the exact same JSON object.
```
// my model
Friend = Backbone.Model.extend({});
// my collection
Friends = Backbone.Collection.extend({
url: 'http://localhost/myapp/get_users'
});
// instantiate friends and add some friends objects!
var friends = new Friends();
friends.fetch();
console.log(friends.length) // prints out 0! WHY???
```
I've been looking at my Chrome inspection panel for both of them and regardless, I have no idea why one from the server is not working?
FYI, on the server side, I have CodeIgniter 2.02, using Phil Stuegeon's REST API to return a JSON data.
I've also tried a simple function on my PHP side, like
```
function get_users() {
echo '{name:"James"}, {name:"Michael"}';
}
```
But without any success.
What am I doing wrong here?
|
2011/08/13
|
[
"https://Stackoverflow.com/questions/7050957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181557/"
] |
Have you forgot the [] to make it an array?
```
echo '[{name:"James"}, {name:"Michael"}]';
```
Also you check the length in the onsuccess method you can pass to fetch. At the moment you check the length directly after fetching, so your not sure if the result is still loaded.
```
friends.fetch(
{success:function(){
console.log(friends.length)
}}
);
```
|
I think the JSON you're passing to `.add()` is invalid. You've got:
```
[
{name: "James"},
{name: "Michael"}
]
```
But you need to quote the keys too:
```
[
{"name": "James"},
{"name": "Michael"}
]
```
|
7,050,957
|
OK. I'm starting out on Backbone.js, and trying to do some very simple things. Here's a very simple Model and Collection.
```
// my model
Friend = Backbone.Model.extend({});
// my collection
Friends = Backbone.Collection.extend({});
// instantiate friends and add some friends objects!
var friends = new Friends();
friends.add([
{name: "James"},
{name: "Michael"}
]);
console.log(friends.length) // prints out 2! which is correct!
```
Above example is fine. But now I want to initialize my collection from server, which returns the exact same JSON object.
```
// my model
Friend = Backbone.Model.extend({});
// my collection
Friends = Backbone.Collection.extend({
url: 'http://localhost/myapp/get_users'
});
// instantiate friends and add some friends objects!
var friends = new Friends();
friends.fetch();
console.log(friends.length) // prints out 0! WHY???
```
I've been looking at my Chrome inspection panel for both of them and regardless, I have no idea why one from the server is not working?
FYI, on the server side, I have CodeIgniter 2.02, using Phil Stuegeon's REST API to return a JSON data.
I've also tried a simple function on my PHP side, like
```
function get_users() {
echo '{name:"James"}, {name:"Michael"}';
}
```
But without any success.
What am I doing wrong here?
|
2011/08/13
|
[
"https://Stackoverflow.com/questions/7050957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181557/"
] |
Have you forgot the [] to make it an array?
```
echo '[{name:"James"}, {name:"Michael"}]';
```
Also you check the length in the onsuccess method you can pass to fetch. At the moment you check the length directly after fetching, so your not sure if the result is still loaded.
```
friends.fetch(
{success:function(){
console.log(friends.length)
}}
);
```
|
fetch() is an asynchronous call, so you'll be printing to the console before the fetch() has returned to populate your collection
To verify, put a breakpoint on the console.log(friends.length) line. The breakpoint will give the fetch() time to happen
|
7,050,957
|
OK. I'm starting out on Backbone.js, and trying to do some very simple things. Here's a very simple Model and Collection.
```
// my model
Friend = Backbone.Model.extend({});
// my collection
Friends = Backbone.Collection.extend({});
// instantiate friends and add some friends objects!
var friends = new Friends();
friends.add([
{name: "James"},
{name: "Michael"}
]);
console.log(friends.length) // prints out 2! which is correct!
```
Above example is fine. But now I want to initialize my collection from server, which returns the exact same JSON object.
```
// my model
Friend = Backbone.Model.extend({});
// my collection
Friends = Backbone.Collection.extend({
url: 'http://localhost/myapp/get_users'
});
// instantiate friends and add some friends objects!
var friends = new Friends();
friends.fetch();
console.log(friends.length) // prints out 0! WHY???
```
I've been looking at my Chrome inspection panel for both of them and regardless, I have no idea why one from the server is not working?
FYI, on the server side, I have CodeIgniter 2.02, using Phil Stuegeon's REST API to return a JSON data.
I've also tried a simple function on my PHP side, like
```
function get_users() {
echo '{name:"James"}, {name:"Michael"}';
}
```
But without any success.
What am I doing wrong here?
|
2011/08/13
|
[
"https://Stackoverflow.com/questions/7050957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181557/"
] |
fetch() is an asynchronous call, so you'll be printing to the console before the fetch() has returned to populate your collection
To verify, put a breakpoint on the console.log(friends.length) line. The breakpoint will give the fetch() time to happen
|
I think the JSON you're passing to `.add()` is invalid. You've got:
```
[
{name: "James"},
{name: "Michael"}
]
```
But you need to quote the keys too:
```
[
{"name": "James"},
{"name": "Michael"}
]
```
|
17,085,030
|
I'm trying to find the most simplistic way of adding a delay on this bootstrap dropdown...<http://www.bootply.com/64074> I have tried various methods and scripts but I cant seem to do it. I've added a css line to allow auto dropdown on mouseover.
```
<!-- Top Nav -->
<div class="navbar hidden-phone well well-small">
<div class="navbar-inner header-drop-nav">
<!-- 1st dropdown -->
<ul class="nav nav-tabs">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Browse by Destination <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- 1st Top Nav links -->
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="nav-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<!-- 2nd dropdown -->
<ul class="nav nav-tabs pull-middle">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Browse by Activity <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- 2nd Top Nav links -->
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="nav-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<!-- 3rd dropdown -->
<ul class="nav nav-tabs">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Browse by Interest <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- 3rd Top Nav links -->
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="nav-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<!-- 4th dropdown -->
<ul class="nav nav-tabs">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Special Offers <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- 4th Top Nav links -->
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="nav-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<form class="navbar-form pull-right hidden-tablet">
<input class="span3" type="text" placeholder="Search">
<button type="submit" class="btn btn-primary">GoSeeDo</button>
</form>
</div>
</div>
```
|
2013/06/13
|
[
"https://Stackoverflow.com/questions/17085030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2402389/"
] |
This JQuery did the trick! <http://www.bootply.com/64081>
```
jQuery('ul.nav li.dropdown').hover(function() {
jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn();
}, function() {
jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});
```
|
For those that come across this thread later.. check out this great plugin that is Bootstrap 3 compatible and works with nav menus, buttons, button groups etc:
<https://github.com/CWSpear/bootstrap-hover-dropdown>
|
17,085,030
|
I'm trying to find the most simplistic way of adding a delay on this bootstrap dropdown...<http://www.bootply.com/64074> I have tried various methods and scripts but I cant seem to do it. I've added a css line to allow auto dropdown on mouseover.
```
<!-- Top Nav -->
<div class="navbar hidden-phone well well-small">
<div class="navbar-inner header-drop-nav">
<!-- 1st dropdown -->
<ul class="nav nav-tabs">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Browse by Destination <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- 1st Top Nav links -->
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="nav-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<!-- 2nd dropdown -->
<ul class="nav nav-tabs pull-middle">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Browse by Activity <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- 2nd Top Nav links -->
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="nav-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<!-- 3rd dropdown -->
<ul class="nav nav-tabs">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Browse by Interest <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- 3rd Top Nav links -->
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="nav-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<!-- 4th dropdown -->
<ul class="nav nav-tabs">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Special Offers <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- 4th Top Nav links -->
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="nav-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<form class="navbar-form pull-right hidden-tablet">
<input class="span3" type="text" placeholder="Search">
<button type="submit" class="btn btn-primary">GoSeeDo</button>
</form>
</div>
</div>
```
|
2013/06/13
|
[
"https://Stackoverflow.com/questions/17085030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2402389/"
] |
This JQuery did the trick! <http://www.bootply.com/64081>
```
jQuery('ul.nav li.dropdown').hover(function() {
jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn();
}, function() {
jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});
```
|
If you are using submenus, need to add .first() after .find():
```
$('div.dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(100).fadeIn(100);
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(200).fadeOut(300);
});
```
|
27,640,567
|
Quite embarrassing, but I can't find the python source code on my Mac (Yosemite). Going through the Django tutorial and stuck on the step below.
Now create a directory called admin inside templates, and copy the template admin/base\_site.html from within the default Django admin template directory in the source code of Django itself (django/contrib/admin/templates) into that directory.
```
import sys
>>> sys.path = sys.path[1:]
>>> import django
>>> print(django.__path__)
['/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django']
```
I don't see a "Frameworks" folder in my Library folder (although I can 'cd' my way there in the terminal. The finder doesn't reveal anything when searching. I read somewhere it might by in a "System" folder, but I can't find that either. I also might be able to complete this step without accessing the folder?
I also believe I've found two different locations using terminal?
```
$ ls /Library/Frameworks/Python.framework/Versions/
3.4
$cd /System/Library/Frameworks/Python.framework/Versions
Versions $ ls
2.3 2.5 2.6 2.7 Current
```
|
2014/12/24
|
[
"https://Stackoverflow.com/questions/27640567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3905394/"
] |
Without virtualenv: **path/to/your/python/X.X/site-packages/django** . In my case **/Library/Python/2.7/site-packages/django**
using virtualenv: **/Users/ME/.virtualenvs/my\_virtual\_env/lib/python2.7/site-packages/django**
Good luck
|
In your finder window if you show the **Devices** on the left sidebar you can search within your **Macintosh HD** for the **Library** folder which should contain your **Frameworks** folder. At least that's what worked for me.
|
916,312
|
I want to prove that $I,A,A^2\:$matrices $\in M\_{2\times 2}$ are $\textit {linearly independent}$.
I consider the following matrices and their "corresponding" vectors:
$I=\begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}\to (1,0,0,1)$
$A=\begin{pmatrix} a & b \\ c & d \end{pmatrix}\to (a,b,c,d)$
$A^2=\begin{pmatrix} a^2+ b c & ab+db \\ ac+dc & d^2+bc\end{pmatrix}\to (a^2+bc, ab+db, ac+dc,d^2+bc)$
What I am trying to do, is to prove that these vectors are $\textit{linearly independent}$.
For that direction, I want to prove that (at least) one $3\times 3$ determinant is $\neq 0$.
It seems that all $3\times 3$ determinants $\left( e.g. \begin{vmatrix} 1 & 0 & 0\\ a & b & c\\ a^2+bc & ab+db & ac+dc\end{vmatrix} \right)$ are equal to zero! What am I really missing?
|
2014/09/01
|
[
"https://math.stackexchange.com/questions/916312",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/124031/"
] |
The thing you're trying to prove is not true. Consider the case $A = I$.
More generally, if $A$ is any $2 \times 2$ matrix, then you can compute its characteristic polynomial, $c(x)$, the determinant of $A - xI$. That will be some quadratic polynomial in $x$, like
$$
3x^2 - 22 x^1 + 8x^0.
$$
It turns out that if you plug in $A$ for $x$ , and treat the $A^0$ as $I$, you'll get a $2 \times 2$ matrix...that's the zero matrix! That's called the Cayley-Hamilton theorem.
As an example:
$$
A = \begin{bmatrix}1 & 3 \\ -1 & 1 \end{bmatrix} \\
A- xI = \begin{bmatrix}1-x & 3 \\ -1 & 1-x \end{bmatrix} \\
c(x) = det(A - xI) = (1-x)^2 + 3 = x^2 -2x + 4
$$
Now plug $A$ into $c$ to get
$$
c(A) = A^2 - 2A + 4I \\
= \begin{bmatrix} -2 & 6 \\ -2 & -2 \end{bmatrix} - \begin{bmatrix}2 & 6 \\ -2 & 2 \end{bmatrix} + \begin{bmatrix}4 & 0 \\ 0 & 4 \end{bmatrix} \\
= \begin{bmatrix}0 & 0 \\ 0 & 0 \end{bmatrix}
$$
|
First of all your matrix is a root of its [characteristic polynomial](http://en.wikipedia.org/wiki/Characteristic_polynomial#Formal_definition) . The bad news is that its square is linear dependant from its lower order terms. The good news is that the algebra generated by this matrix (if its characteristic polynomial is irreducible which it's mostly is) is the splitting field of its roots.
|
2,305,990
|
Using VB.Net
I want to get a all datagrid cell values, then insert into table1.
Code
```
cmd = New SqlCommand("insert into table1 values('" & DataGrid.Rows(0).Cells(0).Value & "', '" & DataGrid.Rows(0).Cells(1).Value & "', '" & DataGrid.Rows(0).Cells(2).Value & "', '" & DataGrid.Rows(0).Cells(3).Value & "')", con)
cmd.ExecuteNonQuery()
```
The above code is inserting first row of datagrid cell value, but i want to insert all the datagrid cell values
How to modify my code for getting all the datagrid cell value.
|
2010/02/21
|
[
"https://Stackoverflow.com/questions/2305990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128071/"
] |
Sticking to your existing code, despite its flaws (definatly look up: [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection))
You could do somthing like this:
```
For Each row As DataGridViewRow in dataGrid.Rows
cmd = New SqlCommand("insert into table1 values('" & row.Cells(0).Value & "', '" & row.Cells(1).Value & "', '" & row.Cells(2).Value & "', '" & row.Cells(3).Value & "')", con)
cmd.ExecuteNonQuery()
Next
```
There's numerous improvements that could be made but this answers your question:
|
First of all: avoid SQL Injection by using Parameters
Then: Loop over all rows and insert them
Pseudocode:
```
foreach(var row in DataGid.Rows)
{
insert();
}
```
|
68,790,977
|
I make mini app to find factorial. When i click button and get number in `js` it is not showing any thing.
This is my `script.js`
```
function factorial() {
let number = document.getElementById("number")
console.log(number);
for (let i = number - 1; i >= 1; i++) {
number = i * number
console.log(number);
}
console.log(number);
return number;
}
```
this is my `index.html`
```
<input type="text" name="number" class="number" id="number">
<button onclick="factorial()" class="btn btn-primary " style="padding-right: 160px;padding-left: 160px">Find</button>
```
|
2021/08/15
|
[
"https://Stackoverflow.com/questions/68790977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16221393/"
] |
Like this for example:
```js
function factorial() {
let number = document.getElementById("number").value
console.log(number);
for (let i = number - 1; i >= 1; i--) {
number = i * number
}
document.getElementById("result").innerHTML = number
}
```
```html
<input type="text" name="number" class="number" id="number">
<button onclick="factorial()" class="btn btn-primary " style="padding-right: 160px;padding-left: 160px">Find</button>
<h3 id="result"></h3>
```
|
There is a property called [.value](https://www.w3schools.com/jsref/prop_text_value.asp). This will return the inner value of inputs (You can try it). After you achieved the value of the input, then you can run your statement.
>
> Read about **.textContent** [here](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent).
>
>
>
>
> Read about **.querySelector()** [here](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector).
>
>
>
**Tip**: Don't ever use *onclick()*. No one uses it anymore, use [.addEventListener()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) instead.
```js
function factorial() {
// Edited here
let number = document.getElementById("number").value;
console.log(number);
for (let i = number - 1; i >= 1; i++) {
number = i * number
console.log(number);
}
// As you wanted to put the result in the html file
document.querySelector('h1').textContent += number;
}
```
```html
<input type="text" name="number" class="number" id="number">
<button onclick="factorial()" class="btn btn-primary " style="padding-right: 160px;padding-left: 160px">Find</button>
<h1>Result: </h1>
```
|
43,378,060
|
I have accepted and merged a pull request on GitHub, and now I cannot pull my commits any more.
The message is:
```
! [remote rejected] master -> master (push declined due to email privacy restrictions)
error: failed to push some refs to 'git@github.com:FranckFreiburger/vue-resize-sensor.git'
git did not exit cleanly (exit code 1) (3838 ms @ 12/04/2017 21:23:11)
```
What should I do now?
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138579/"
] |
There is 3 options you can use:
**1**. You could uncheck your `Keep my email addresses private` in your [GitHub E-mail Settings](https://github.com/settings/emails).
**2**. If you want hide e-mail your repositories, GitHub provide a noreply e-mail address in GitHub e-mail settings
>
> Because you have email privacy enabled,
> will be used for account-related notifications as well as password resets.
>
>
>
>
> 34661293+aslancan32@users.noreply.github.com will be used for
> web-based Git operations, e.g., edits and merges.
>
>
>
```
git config --global user.email "<your-noreply-github-email>"
```
**3-** Or you can use your public email or business email for your repositories. Like `m****@business.com`
```
git config --global user.email "<your-public-email>"
```
After apply to your setting I recommend run reset header code :
```
git reset --soft HEAD~1
```
Try again to `push` your repository
|
Using Github Desktop fixed my issue.
|
43,378,060
|
I have accepted and merged a pull request on GitHub, and now I cannot pull my commits any more.
The message is:
```
! [remote rejected] master -> master (push declined due to email privacy restrictions)
error: failed to push some refs to 'git@github.com:FranckFreiburger/vue-resize-sensor.git'
git did not exit cleanly (exit code 1) (3838 ms @ 12/04/2017 21:23:11)
```
What should I do now?
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138579/"
] |
1. Open `Emails` section of github.com. Visit <https://github.com/settings/emails>.
2. Go to `Keep my email addresses private` section and note down your `donotreply` email id.
3. Open `git terminal` and set your `donotreply` email id as your email id using following command:
```
git config --global user.email "<your_donotreply_email_id"
```
4. Revert your recent local commits (with your private email) which are getting failed to be pushed into repository.
```
git reset --soft HEAD~1
```
5. Stage and push those commits
```
git add .
git commit –m "<commit_message>"
git push
```
|
1. Just go to github.com and click on your profile
2. Go to settings
3. Now click on the 'Email' on the left navigation panel
4. And search for the field 'Keep my email addresses private'
5. Please uncheck this option
6. Now please check again and I think your problem is solved now.
|
43,378,060
|
I have accepted and merged a pull request on GitHub, and now I cannot pull my commits any more.
The message is:
```
! [remote rejected] master -> master (push declined due to email privacy restrictions)
error: failed to push some refs to 'git@github.com:FranckFreiburger/vue-resize-sensor.git'
git did not exit cleanly (exit code 1) (3838 ms @ 12/04/2017 21:23:11)
```
What should I do now?
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138579/"
] |
There is 3 options you can use:
**1**. You could uncheck your `Keep my email addresses private` in your [GitHub E-mail Settings](https://github.com/settings/emails).
**2**. If you want hide e-mail your repositories, GitHub provide a noreply e-mail address in GitHub e-mail settings
>
> Because you have email privacy enabled,
> will be used for account-related notifications as well as password resets.
>
>
>
>
> 34661293+aslancan32@users.noreply.github.com will be used for
> web-based Git operations, e.g., edits and merges.
>
>
>
```
git config --global user.email "<your-noreply-github-email>"
```
**3-** Or you can use your public email or business email for your repositories. Like `m****@business.com`
```
git config --global user.email "<your-public-email>"
```
After apply to your setting I recommend run reset header code :
```
git reset --soft HEAD~1
```
Try again to `push` your repository
|
I solved the errors by:
`git config --global user.email ""`
This just sets my email to blank (an empty string). I now set my email in individual projects with:
`git config user.email "myemail@domain.com"`
|
43,378,060
|
I have accepted and merged a pull request on GitHub, and now I cannot pull my commits any more.
The message is:
```
! [remote rejected] master -> master (push declined due to email privacy restrictions)
error: failed to push some refs to 'git@github.com:FranckFreiburger/vue-resize-sensor.git'
git did not exit cleanly (exit code 1) (3838 ms @ 12/04/2017 21:23:11)
```
What should I do now?
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138579/"
] |
1. Open `Emails` section of github.com. Visit <https://github.com/settings/emails>.
2. Go to `Keep my email addresses private` section and note down your `donotreply` email id.
3. Open `git terminal` and set your `donotreply` email id as your email id using following command:
```
git config --global user.email "<your_donotreply_email_id"
```
4. Revert your recent local commits (with your private email) which are getting failed to be pushed into repository.
```
git reset --soft HEAD~1
```
5. Stage and push those commits
```
git add .
git commit –m "<commit_message>"
git push
```
|
Using Github Desktop fixed my issue.
|
43,378,060
|
I have accepted and merged a pull request on GitHub, and now I cannot pull my commits any more.
The message is:
```
! [remote rejected] master -> master (push declined due to email privacy restrictions)
error: failed to push some refs to 'git@github.com:FranckFreiburger/vue-resize-sensor.git'
git did not exit cleanly (exit code 1) (3838 ms @ 12/04/2017 21:23:11)
```
What should I do now?
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138579/"
] |
1. Just go to github.com and click on your profile
2. Go to settings
3. Now click on the 'Email' on the left navigation panel
4. And search for the field 'Keep my email addresses private'
5. Please uncheck this option
6. Now please check again and I think your problem is solved now.
|
Using Github Desktop fixed my issue.
|
43,378,060
|
I have accepted and merged a pull request on GitHub, and now I cannot pull my commits any more.
The message is:
```
! [remote rejected] master -> master (push declined due to email privacy restrictions)
error: failed to push some refs to 'git@github.com:FranckFreiburger/vue-resize-sensor.git'
git did not exit cleanly (exit code 1) (3838 ms @ 12/04/2017 21:23:11)
```
What should I do now?
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138579/"
] |
This is likely caused by a [new GitHub setting](https://github.com/blog/2346-private-emails-now-more-private) that blocks command line pushes that expose your email address.
Try unchecking the "Block command line pushes that expose my email" box in your [email settings](https://github.com/settings/emails) and then pushing again.
|
I solved the errors by:
`git config --global user.email ""`
This just sets my email to blank (an empty string). I now set my email in individual projects with:
`git config user.email "myemail@domain.com"`
|
43,378,060
|
I have accepted and merged a pull request on GitHub, and now I cannot pull my commits any more.
The message is:
```
! [remote rejected] master -> master (push declined due to email privacy restrictions)
error: failed to push some refs to 'git@github.com:FranckFreiburger/vue-resize-sensor.git'
git did not exit cleanly (exit code 1) (3838 ms @ 12/04/2017 21:23:11)
```
What should I do now?
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138579/"
] |
I solved the errors by:
`git config --global user.email ""`
This just sets my email to blank (an empty string). I now set my email in individual projects with:
`git config user.email "myemail@domain.com"`
|
Using Github Desktop fixed my issue.
|
43,378,060
|
I have accepted and merged a pull request on GitHub, and now I cannot pull my commits any more.
The message is:
```
! [remote rejected] master -> master (push declined due to email privacy restrictions)
error: failed to push some refs to 'git@github.com:FranckFreiburger/vue-resize-sensor.git'
git did not exit cleanly (exit code 1) (3838 ms @ 12/04/2017 21:23:11)
```
What should I do now?
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138579/"
] |
The remote repository has been configured to disallow you pushing a commit that would reveal your personal e-mail address. For example in GitHub you have checked the [*Block command line pushes that expose my email*](https://github.com/settings/emails) checkbox to [enable this](https://github.com/blog/2346-private-emails-now-more-private).
[](https://i.stack.imgur.com/qUWWQ.png)
While you can of course uncheck that setting, it will expose your private e-mail address to everyone in the world, as author information is readable by anyone with access to your repository.
Instead, do this:
1. You can see your personal e-mail address, which is used by default for your commits in Git:
```sh
git config --global user.email
```
2. Find your [GitHub noreply address](https://help.github.com/articles/setting-your-email-in-git/) in your GitHub's [Personal Settings → Emails](https://github.com/settings/emails). It's mentioned in the description of the *Keep my email address private* checkbox. Usually, it starts with a unique identifier, plus your username:
```sh
{ID}+{username}@users.noreply.github.com
```
[](https://i.stack.imgur.com/pFiwC.png)
3. Change the global user e-mail address setting to be your GitHub noreply address:
```sh
git config --global user.email {ID}+{username}@users.noreply.github.com
```
4. Reset the author information on your last commit:
```sh
git commit --amend --reset-author
```
If you have multiple commits with your private e-mail address, see [this answer](https://stackoverflow.com/a/25815116/146622).
5. Now you can push the commit with the noreply e-mail address, and future commits will have the noreply e-mail address as well.
```sh
git push
```
|
This is likely caused by a [new GitHub setting](https://github.com/blog/2346-private-emails-now-more-private) that blocks command line pushes that expose your email address.
Try unchecking the "Block command line pushes that expose my email" box in your [email settings](https://github.com/settings/emails) and then pushing again.
|
43,378,060
|
I have accepted and merged a pull request on GitHub, and now I cannot pull my commits any more.
The message is:
```
! [remote rejected] master -> master (push declined due to email privacy restrictions)
error: failed to push some refs to 'git@github.com:FranckFreiburger/vue-resize-sensor.git'
git did not exit cleanly (exit code 1) (3838 ms @ 12/04/2017 21:23:11)
```
What should I do now?
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138579/"
] |
This is likely caused by a [new GitHub setting](https://github.com/blog/2346-private-emails-now-more-private) that blocks command line pushes that expose your email address.
Try unchecking the "Block command line pushes that expose my email" box in your [email settings](https://github.com/settings/emails) and then pushing again.
|
There is 3 options you can use:
**1**. You could uncheck your `Keep my email addresses private` in your [GitHub E-mail Settings](https://github.com/settings/emails).
**2**. If you want hide e-mail your repositories, GitHub provide a noreply e-mail address in GitHub e-mail settings
>
> Because you have email privacy enabled,
> will be used for account-related notifications as well as password resets.
>
>
>
>
> 34661293+aslancan32@users.noreply.github.com will be used for
> web-based Git operations, e.g., edits and merges.
>
>
>
```
git config --global user.email "<your-noreply-github-email>"
```
**3-** Or you can use your public email or business email for your repositories. Like `m****@business.com`
```
git config --global user.email "<your-public-email>"
```
After apply to your setting I recommend run reset header code :
```
git reset --soft HEAD~1
```
Try again to `push` your repository
|
43,378,060
|
I have accepted and merged a pull request on GitHub, and now I cannot pull my commits any more.
The message is:
```
! [remote rejected] master -> master (push declined due to email privacy restrictions)
error: failed to push some refs to 'git@github.com:FranckFreiburger/vue-resize-sensor.git'
git did not exit cleanly (exit code 1) (3838 ms @ 12/04/2017 21:23:11)
```
What should I do now?
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138579/"
] |
This is likely caused by a [new GitHub setting](https://github.com/blog/2346-private-emails-now-more-private) that blocks command line pushes that expose your email address.
Try unchecking the "Block command line pushes that expose my email" box in your [email settings](https://github.com/settings/emails) and then pushing again.
|
1. Just go to github.com and click on your profile
2. Go to settings
3. Now click on the 'Email' on the left navigation panel
4. And search for the field 'Keep my email addresses private'
5. Please uncheck this option
6. Now please check again and I think your problem is solved now.
|
51,538,453
|
I need to create a new table, based on two existing.
<http://sqlfiddle.com/#!9/74e49>
It must contain number of instances of every particular value from table1 in table2. Like:
* Name - koatuu1 - koatuu2 - koatuu3 - koatuu\_N ... koatuu\_350
* Johnson - 5 - 12 - 76 - 9 - 321 - 4
It must be something like this for every lastname:
```
select table1.koatuu, count(table2.*)
from table2
where lastname = "Johnson"
inner join table1 on table1.postcode = table2.postcode
```
[I need a red circled table](https://i.stack.imgur.com/1rw8q.png)
Can I do it within MySQL query, without writing a script in Php?
|
2018/07/26
|
[
"https://Stackoverflow.com/questions/51538453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5896632/"
] |
As per the answer given by google this is intended behaviour.
<https://issuetracker.google.com/issues/111819103>
They gave 3 options
1. Use android.view.ViewOutlineProvider (as per example here <https://github.com/googlesamples/android-ClippingBasic>).
2. Replace the ImageView with a BitmapShader, which is fast (each pixel is drawn once) and more portable way as BitmapShader is supported in API level 1.
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.spiderman);
Shader shader = new BitmapShader(bm, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(shader);
Path corners = new Path();
corners.addRoundRect(bounds, radii, Path.Direction.CW);
canvas.drawPath(corners, paint);
3. Draw an inverse path with SRC\_OVER on top of the ImageView. This works if background is solid color and it is slower, because some pixels are drawn twice.
Of these the first can't be used to render convex complex path as is answered in <https://issuetracker.google.com/issues/37064491>
Trying the other two options and post the results here.
|
Yep, I have encountered the same problem.
Maybe Android-Pie does not seem to support drawerDuff.Mode on drawPath ...
But, you still can be use drawBitmap to cut layers.
E.g:
```
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (clipPathBitmap != null) {
canvas.drawBitmap(clipPathBitmap, 0, 0, paint);
}
}
private void makeClipPathBitmap() {
clipPathBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(mShapeBitmap);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(Color.BLACK);
clipPath.draw(c, p);
}
```
|
29,558
|
We sell buttons (for the plug). Each of the buttons will cost 2,- Euro. A defined set of 3 buttons will cost 5,- EUR. All individual buttons are created as simple products. So far so good.
I have already tried a lot. The problems are:
* Grouped: The customer can define the number but the number is set).
* Bundle: compilation, the user can choose (but he should not) and the price is not unique.
|
2014/07/21
|
[
"https://magento.stackexchange.com/questions/29558",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/12395/"
] |
If you want to offer this defined set with its own product page, bundle products are the perfect fit.
To address your problems:
* When you create a bundle, you can choose to give it a fixed price instead of dynamic price, this means the price will not depend on the simple products.
* If you make the bundle options required and only add one selection per option, the user won't get to choose anything:
+ **Option 1**: Type "Checkbox", Required
- Selection: Button 1
+ **Option 2**: Type "Checkbox", Required
- Selection: Button 2
+ **Option 3**: Type "Checkbox", Required
- Selection: Button 3
|
If all the products are the same you can use tiered prices. If not, you can set promotions/discount rules to match a certain criteria.
Most of what you need might be [here.](http://www.magentocommerce.com/wiki/welcome_to_the_magento_user_s_guide/chapter_5)
|
66,525,073
|
Consider a simple array that contains a set of values.
```
var arr = ['ab', 'cd', 'ef'];
```
I'd like to convert the above array into,
```
[
{ name: 'ab' },
{ name: 'cd' },
{ name: 'ef' }
];
```
What I've tried:
```
arr.reduce((a, c) => ((a[c] = c), a), {});
```
|
2021/03/08
|
[
"https://Stackoverflow.com/questions/66525073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475148/"
] |
You can do this using `Array.map`, which allows you to specify a function that returns a new item to replace in the array.
```js
arr.map(o => ({ name: o }))
```
Here's one without fancy arrow function shorthand, just in case you are confused.
```js
arr.map(function(o) {
return {
name: o,
}
})
```
|
You can use forEach() and create a new array of objects pushing each new object.
```
var arr = ['ab', 'cd', 'ef'];
const newObjArr = [];
arr.forEach((str) => newObjArr.push({ name: str }))
console.log(newObjArr); //[ { name: 'ab' }, { name: 'cd' }, { name: 'ef' } ]
```
|
66,525,073
|
Consider a simple array that contains a set of values.
```
var arr = ['ab', 'cd', 'ef'];
```
I'd like to convert the above array into,
```
[
{ name: 'ab' },
{ name: 'cd' },
{ name: 'ef' }
];
```
What I've tried:
```
arr.reduce((a, c) => ((a[c] = c), a), {});
```
|
2021/03/08
|
[
"https://Stackoverflow.com/questions/66525073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475148/"
] |
You can do this using `Array.map`, which allows you to specify a function that returns a new item to replace in the array.
```js
arr.map(o => ({ name: o }))
```
Here's one without fancy arrow function shorthand, just in case you are confused.
```js
arr.map(function(o) {
return {
name: o,
}
})
```
|
>
> You've tried: `arr.reduce((a, c) => ((a[c] = c), a), {});`
>
>
>
Your code there are 2 problems:
1. `{}`: The initialValue should be the `Array` instead.
2. `(a[c] = c`: You want to define the specific `name` instead of each `c` value
[**The `.reduce` syntax**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#syntax)
>
> arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[,
> initialValue])
>
>
>
The finish solution `.reduce` should be like this:
```js
const arr = ['ab', 'cd', 'ef'];
const result = arr.reduce((acc, currItem) => {
acc.push({name: currItem});
return acc;
}, []);
console.log(result);
```
Or just `.map()` like this.
```js
const arr = ['ab', 'cd', 'ef'];
const result = arr.map(item => ({name: item}));
console.log(result);
```
|
66,525,073
|
Consider a simple array that contains a set of values.
```
var arr = ['ab', 'cd', 'ef'];
```
I'd like to convert the above array into,
```
[
{ name: 'ab' },
{ name: 'cd' },
{ name: 'ef' }
];
```
What I've tried:
```
arr.reduce((a, c) => ((a[c] = c), a), {});
```
|
2021/03/08
|
[
"https://Stackoverflow.com/questions/66525073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475148/"
] |
You can do this using `Array.map`, which allows you to specify a function that returns a new item to replace in the array.
```js
arr.map(o => ({ name: o }))
```
Here's one without fancy arrow function shorthand, just in case you are confused.
```js
arr.map(function(o) {
return {
name: o,
}
})
```
|
Another way using [`With Object.fromEntries, you can convert from Array to Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries)
```js
const arr = ['ab', 'cd', 'ef'];
const result = arr.map(item => Object.fromEntries([["name",item]]));
console.log(result);
```
|
12,088,519
|
Well, here is the code I've tried so far.
```
public class CustomDateEditorRegistrar implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy hh:mm a"), true))
registry.registerCustomEditor(Date.class, new StructuredDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true))
}
}
```
I am using a calendar jQuery plugin and a regular grails DatePicker, if I just use the first one, I always get an error with the regular grails Date Picker. If I use both, I don't get an error anymore.. However, the calendar saves just the date and not the time? Anyway to fix this? :(
|
2012/08/23
|
[
"https://Stackoverflow.com/questions/12088519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1619251/"
] |
You may want to take a look at this:
[Grails Date unmarshalling](https://stackoverflow.com/questions/963922/grails-date-unmarshalling)
and this
[Binding a Grails date from params in a controller](https://stackoverflow.com/questions/2871977/binding-a-grails-date-from-params-in-a-controller)
|
I don't think you can register multiple editors for the same type, so I would instead write my own `MultiDateEditor` subclass of `CustomDateEditor` (or implement `PropertyEditorSupport` directly) which tries to bind a date using multiple formats. Then you only need to register `MultiDateEditor`:
```
public class CustomDateEditorRegistrar implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new MultiDateEditor(
["MM/dd/yyyy hh:mm a", "MM/dd/yyyy"]))
}
}
```
|
261,602
|
Here is my code for overriding vendor module template. when the page corresponding to this layout loads, it is fetching template file from vendor.after the refresh it is fetching from my custom module.Please help.
```
<referenceBlock name="items">
<action method="setTemplate">
<argument name="template" translate="true" xsi:type="string">My_Sales::order/create/items.phtml</argument>
</action>
</referenceBlock>
```
|
2019/02/13
|
[
"https://magento.stackexchange.com/questions/261602",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/76593/"
] |
Below layouts are to be overrided.
* sales\_order\_create\_index.xml
* sales\_order\_create\_load\_block\_items.xml
* sales\_order\_create\_load\_block\_data.xml
|
You should put this in module.xml
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="My_Sales" setup_version="0.0.1">
<sequence>
<module name="Magento_Checkout" />
</sequence>
</module>
</config>
```
Its depends which module you trying rewrite file
|
42,997,363
|
Below is datasource.jsp for adding dynamic dropdown into my customComponent dialog, I'm using this datasource in my customComponent as below mentioned field.
Here my requirement is need to get url values to dropdown when my customComponent used in any page(this page having urls). So here i need that currentPage url where i have used my customComponent.
Please help me to get that page url where i have used my customComponent to this datasource.
```
<%
request.setAttribute(DataSource.class.getName(), EmptyDataSource.instance());
ResourceResolver resolver = resource.getResourceResolver();
//Create an ArrayList to hold data
List<Resource> fakeResourceList = new ArrayList<Resource>();
ValueMap vm = null;
Resource childResource = resourceResolver.getResource(currentPage.getPath()+"/jcr:content/node/path");
if(childResource!=null){
Node childNode = childResource.adaptTo(Node.class);
Node childLinks = childNode.getNode("childnode");
if(childLinks!=null){
NodeIterator childrenNodes = childLinks.getNodes();
while(childrenNodes.hasNext()) {
vm = new ValueMapDecorator(new HashMap<String, Object>());
Node next = childrenNodes.nextNode();
String label = next.getProperty("label").getValue().getString();
String path = next.getProperty("url").getValue().getString();
vm.put("text",label);
vm.put("value",path.substring(1));
fakeResourceList.add(new ValueMapResource(resolver, new ResourceMetadata(), "nt:unstructured", vm));
}
}
} else {
vm = new ValueMapDecorator(new HashMap<String, Object>());
vm.put("text","NoValue");
vm.put("value","");
fakeResourceList.add(new ValueMapResource(resolver, new ResourceMetadata(), "nt:unstructured", vm));
}
DataSource ds = new SimpleDataSource(fakeResourceList.iterator());
request.setAttribute(DataSource.class.getName(), ds);
%>
```
In my customComponent dialog content.xml which is using above datasource as it's sling:resourceType.
```
<dataSourceTest
jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/foundation/form/select"
fieldDescription="Provide ID"
fieldLabel="Anchor"
name="./datasourceTest">
<datasource
jcr:primaryType="nt:unstructured"
sling:resourceType="/apps/mysite/components/page/datasource"/>
</dataSourceTest>
```
|
2017/03/24
|
[
"https://Stackoverflow.com/questions/42997363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4895053/"
] |
You can achieve this using:
jQuery:
```
$('.desktop-button.tiny').attr('name', 'login_button');
```
Or Javascript:
```
document.querySelector(".desktop-button.tiny").setAttribute("name", "login_button");
```
```js
var addNameAttr = function () {
$('.desktop-button.tiny').attr('name', 'login_button');
console.log($('.desktop-button.tiny').attr('name'));
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" class="desktop-button tiny" onclick="addNameAttr()">LOGIN</button>
```
|
You can select the button using its classes, `.desktop-button .tiny`.
Together with setting the name attribute, this would result in:
jQuery:
```
$(".desktop-button.tiny").attr("name", "login_button");
```
Pure JavaScript:
```
document.querySelector(".desktop-button.tiny").setAttribute("name", "login_button");
```
|
42,997,363
|
Below is datasource.jsp for adding dynamic dropdown into my customComponent dialog, I'm using this datasource in my customComponent as below mentioned field.
Here my requirement is need to get url values to dropdown when my customComponent used in any page(this page having urls). So here i need that currentPage url where i have used my customComponent.
Please help me to get that page url where i have used my customComponent to this datasource.
```
<%
request.setAttribute(DataSource.class.getName(), EmptyDataSource.instance());
ResourceResolver resolver = resource.getResourceResolver();
//Create an ArrayList to hold data
List<Resource> fakeResourceList = new ArrayList<Resource>();
ValueMap vm = null;
Resource childResource = resourceResolver.getResource(currentPage.getPath()+"/jcr:content/node/path");
if(childResource!=null){
Node childNode = childResource.adaptTo(Node.class);
Node childLinks = childNode.getNode("childnode");
if(childLinks!=null){
NodeIterator childrenNodes = childLinks.getNodes();
while(childrenNodes.hasNext()) {
vm = new ValueMapDecorator(new HashMap<String, Object>());
Node next = childrenNodes.nextNode();
String label = next.getProperty("label").getValue().getString();
String path = next.getProperty("url").getValue().getString();
vm.put("text",label);
vm.put("value",path.substring(1));
fakeResourceList.add(new ValueMapResource(resolver, new ResourceMetadata(), "nt:unstructured", vm));
}
}
} else {
vm = new ValueMapDecorator(new HashMap<String, Object>());
vm.put("text","NoValue");
vm.put("value","");
fakeResourceList.add(new ValueMapResource(resolver, new ResourceMetadata(), "nt:unstructured", vm));
}
DataSource ds = new SimpleDataSource(fakeResourceList.iterator());
request.setAttribute(DataSource.class.getName(), ds);
%>
```
In my customComponent dialog content.xml which is using above datasource as it's sling:resourceType.
```
<dataSourceTest
jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/foundation/form/select"
fieldDescription="Provide ID"
fieldLabel="Anchor"
name="./datasourceTest">
<datasource
jcr:primaryType="nt:unstructured"
sling:resourceType="/apps/mysite/components/page/datasource"/>
</dataSourceTest>
```
|
2017/03/24
|
[
"https://Stackoverflow.com/questions/42997363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4895053/"
] |
You can achieve this using:
jQuery:
```
$('.desktop-button.tiny').attr('name', 'login_button');
```
Or Javascript:
```
document.querySelector(".desktop-button.tiny").setAttribute("name", "login_button");
```
```js
var addNameAttr = function () {
$('.desktop-button.tiny').attr('name', 'login_button');
console.log($('.desktop-button.tiny').attr('name'));
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" class="desktop-button tiny" onclick="addNameAttr()">LOGIN</button>
```
|
You first need to obtain the element and then set the name attribute.
Without jquery this would be:
```
<button id='my-button' type="submit" class="desktop-button tiny" onclick="document.stacks_in_3151032_page6.formAction.value = 1'login';">LOGIN</button>
document.getElementById('my-button').setAttribute('name', 'login_button');
```
With jquery, you would be able to find the element without adding an id as such:
```
$('button.desktop-button.tiny').attr('name', 'login_button');
```
Hope this helps.
|
779,033
|
I tried using the Monte Carlo Method to approximate the sum $\sum\_{1}^{10000}e^{\frac{k}{10000}}$. First I genarating 100 random numbers in (1, 10000). Then by the strong law of large numbers:
$$\sum\_{i=1}^{100}\frac{f(U\_i)}{k} \to E[f(U)] = \theta$$
where:
$$\theta = \int\_{1}^{10000}e^{\frac{x}{10000}}dx$$
The exercise says to use only 100 random numbers. So dont know if that thought is right, because this method requires k→∞
|
2014/05/03
|
[
"https://math.stackexchange.com/questions/779033",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/147464/"
] |
You are confusing a few different concepts:
* You write $\frac{1}{k}\sum\_{i=1}^{100}f(U\_i)\to\mathbb{E}[f(U)]$ when you clearly mean $\frac{1}{100}\sum\_{i=1}^{100}f(U\_i)\approx\mathbb{E}[f(U)]$.
* You talk about random numbers in $\{1,\dots,10000\}$ (implying that you choose them uniformly). This is therefore a discrete random variable. To evaluate its expectation, you then integrate between 1 and 10000 as if it were continuous (and you don't even normalize the density).
Let us go back to the basics. You know that for any continuous function $f$ on $[0,1]$,
$$\frac{1}{N}\sum\_{k=0}^Nf\left(\frac{k}{N}\right)\xrightarrow[N\to+\infty]{}\int\_0^1f(x)\,\mathrm{d}x.$$
By identification, do you see what function $f$ you should choose to approximate $\sum\_{k=1}^{10000}e^{k/1000}$?
Let us assume that you have found such an $f$, and $\sum\_{k=1}^{10000}e^{k/1000}\approx\int\_0^1f(x)\,\mathrm{d}x$. You may write
$$\int\_0^1f(x)\,\mathrm{d}x=\mathbb{E}[f(U)],$$
where $U$ is a uniform random variable on $[0,1]$. Then, do you see how to approximate $\mathbb{E}[f(U)]$ by using the Monte Carlo techniques you mention in your post?
|
This looks slightly messy to me, in that we are mixing to different approximations: an integral that is (numerically) approximated by a sum, and a integral (or a sum) that is (probabilistically) approximated by a Montecarlo extraction.
There is no need to convert the integral to a (approximate) sum to evaluate it via Montecarlo - and might be confusing to suggest that.
Let's say we want to evaluate
$$I=\int\_0^1 e^x dx $$
On one hand, this can be approximated by a finite sum:
$$I= \frac{1}{10000}\int\_0^{10000} e^{t/10000}dt\approx \frac{1}{10000} \sum\_k e^{k/10000}$$
On the other (rather unrelated) hand, the integral can be evaluated via Montecarlo. Let $Y$ be a random variable uniform in $[0,1]$ Then , letting $u(y)=e^{y}$
$$E[u(Y)]=\int\_{0}^1 f\_Y(y)\, u(Y) dY = I$$
Then, we can evaluate the integral as an expectation, and so we can throw a large number (say $N=100$) of values of $Y$ and approximate
$$I =E(u(Y)) \approx \frac{1}{N}\sum\_{i=1}^N u(Y\_i) $$
Notice that this $N$ has no relation with the $10000$ above. To evaluate if this $N$ is big enough, we could try to compute the variance. Anyway, informally, if the variable is not "tricky" (if the densitiy does not varies wildly in the support), 100 (even sometimes 30) is considered a reasonable number for using the law of large numbers.
|
70,442,285
|
I want a code to be highlighted like this
jmp **label** ;comments
I want only **label** to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case **jmp** is brightmagenta also.
How can I implement this? I want only **label** to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.
[](https://i.stack.imgur.com/OyK0T.jpg)
Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file[](https://i.stack.imgur.com/1cfxR.jpg)
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70442285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17735779/"
] |
You could use transmute, e.g.
```r
library(dplyr)
df <- data.frame(
A_1 = c(NA, NA, 3, 4, 5),
A_2 = c(1, 2, NA, NA, NA),
B_1 = c(NA, NA, 13, 14, 15),
B_2 = c(11, 12, NA, NA, NA)
)
df %>%
transmute(A = coalesce(A_1, A_2),
B = coalesce(B_1, B_2))
#> A B
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
#> 5 5 15
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
Another option, if you have lots of "A\_\*" and "B\_\*" columns (source: [Romain François](https://github.com/tidyverse/funs/issues/54#issuecomment-613882658), user: [@Romain Francois](https://stackoverflow.com/users/499163/romain-francois)):
```r
library(dplyr)
df <- data.frame(
A_1 = c(NA, NA, 3, 4, 5),
A_2 = c(1, 2, NA, NA, NA),
B_1 = c(NA, NA, 13, 14, 15),
B_2 = c(11, 12, NA, NA, NA)
)
coacross <- function(...) {
coalesce(!!!across(...))
}
df %>%
transmute(A = coacross(starts_with("A_")),
B = coacross(starts_with("B_")))
#> A B
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
#> 5 5 15
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
Edit
----
Based on your updated question, you don't have lots of "A\_\*" or "B\_\*" columns, but instead lots of "\*\_1", "\*\_2", and "\*\_3" columns. I think this is the most straightforward solution for your use-case:
```r
library(dplyr)
df <- data.frame(Al_TAC4.25.275 = c(1, 1, 1, NA, NA, NA),
Al_TAC4.25.276 = c(NA, NA, 2, 2, 2, NA),
Al_TAC4.25.277 = c(NA, NA, 3, NA, NA, 3),
Au_TAC4.25.275 = c(1, 1, 1, NA, NA, NA),
Au_TAC4.25.276 = c(NA, NA, 2, 2, 2, NA),
Au_TAC4.25.277 = c(NA, NA, 3, NA, NA, NA),
Ar_TAC4.25.275 = c(1, 1, 1, NA, NA, 1),
Ar_TAC4.25.276 = c(NA, NA, 2, 2, 2, 2),
Ar_TAC4.25.277 = c(NA, NA, 3, NA, NA, 3))
df
#> Al_TAC4.25.275 Al_TAC4.25.276 Al_TAC4.25.277 Au_TAC4.25.275 Au_TAC4.25.276
#> 1 1 NA NA 1 NA
#> 2 1 NA NA 1 NA
#> 3 1 2 3 1 2
#> 4 NA 2 NA NA 2
#> 5 NA 2 NA NA 2
#> 6 NA NA 3 NA NA
#> Au_TAC4.25.277 Ar_TAC4.25.275 Ar_TAC4.25.276 Ar_TAC4.25.277
#> 1 NA 1 NA NA
#> 2 NA 1 NA NA
#> 3 3 1 2 3
#> 4 NA NA 2 NA
#> 5 NA NA 2 NA
#> 6 NA 1 2 3
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(1,2,3)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 1 1 1
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 1 NA
# change the order of the list to change the 'priority'
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(3,2,1)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 3 3 3
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 3 NA
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(2,1,3)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 2 2 2
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 2 NA
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
|
Edit: I believe this solution continues to work even after your edit. It works regardless of the number of elements or the number of cores per element. You just need to make sure things are named consistently, in the form `"{element}_{core}"`.
```
library(tidyverse)
df %>%
mutate(id = 1:n()) %>%
pivot_longer(-id) %>%
filter(!is.na(value)) %>%
mutate(variable = str_extract(name, "^[^_]+")) %>%
group_by(id, variable) %>%
# Arrange by name (e.g. A_1) so that we could select the first non-NA
arrange(name) %>%
summarise(value = value[1]) %>%
pivot_wider(names_from = "variable")
```
Output
```
# A tibble: 5 x 3
id A B
<int> <dbl> <dbl>
1 1 1 11
2 2 2 12
3 3 3 13
4 4 4 14
5 5 5 15
```
|
70,442,285
|
I want a code to be highlighted like this
jmp **label** ;comments
I want only **label** to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case **jmp** is brightmagenta also.
How can I implement this? I want only **label** to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.
[](https://i.stack.imgur.com/OyK0T.jpg)
Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file[](https://i.stack.imgur.com/1cfxR.jpg)
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70442285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17735779/"
] |
You could use transmute, e.g.
```r
library(dplyr)
df <- data.frame(
A_1 = c(NA, NA, 3, 4, 5),
A_2 = c(1, 2, NA, NA, NA),
B_1 = c(NA, NA, 13, 14, 15),
B_2 = c(11, 12, NA, NA, NA)
)
df %>%
transmute(A = coalesce(A_1, A_2),
B = coalesce(B_1, B_2))
#> A B
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
#> 5 5 15
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
Another option, if you have lots of "A\_\*" and "B\_\*" columns (source: [Romain François](https://github.com/tidyverse/funs/issues/54#issuecomment-613882658), user: [@Romain Francois](https://stackoverflow.com/users/499163/romain-francois)):
```r
library(dplyr)
df <- data.frame(
A_1 = c(NA, NA, 3, 4, 5),
A_2 = c(1, 2, NA, NA, NA),
B_1 = c(NA, NA, 13, 14, 15),
B_2 = c(11, 12, NA, NA, NA)
)
coacross <- function(...) {
coalesce(!!!across(...))
}
df %>%
transmute(A = coacross(starts_with("A_")),
B = coacross(starts_with("B_")))
#> A B
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
#> 5 5 15
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
Edit
----
Based on your updated question, you don't have lots of "A\_\*" or "B\_\*" columns, but instead lots of "\*\_1", "\*\_2", and "\*\_3" columns. I think this is the most straightforward solution for your use-case:
```r
library(dplyr)
df <- data.frame(Al_TAC4.25.275 = c(1, 1, 1, NA, NA, NA),
Al_TAC4.25.276 = c(NA, NA, 2, 2, 2, NA),
Al_TAC4.25.277 = c(NA, NA, 3, NA, NA, 3),
Au_TAC4.25.275 = c(1, 1, 1, NA, NA, NA),
Au_TAC4.25.276 = c(NA, NA, 2, 2, 2, NA),
Au_TAC4.25.277 = c(NA, NA, 3, NA, NA, NA),
Ar_TAC4.25.275 = c(1, 1, 1, NA, NA, 1),
Ar_TAC4.25.276 = c(NA, NA, 2, 2, 2, 2),
Ar_TAC4.25.277 = c(NA, NA, 3, NA, NA, 3))
df
#> Al_TAC4.25.275 Al_TAC4.25.276 Al_TAC4.25.277 Au_TAC4.25.275 Au_TAC4.25.276
#> 1 1 NA NA 1 NA
#> 2 1 NA NA 1 NA
#> 3 1 2 3 1 2
#> 4 NA 2 NA NA 2
#> 5 NA 2 NA NA 2
#> 6 NA NA 3 NA NA
#> Au_TAC4.25.277 Ar_TAC4.25.275 Ar_TAC4.25.276 Ar_TAC4.25.277
#> 1 NA 1 NA NA
#> 2 NA 1 NA NA
#> 3 3 1 2 3
#> 4 NA NA 2 NA
#> 5 NA NA 2 NA
#> 6 NA 1 2 3
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(1,2,3)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 1 1 1
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 1 NA
# change the order of the list to change the 'priority'
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(3,2,1)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 3 3 3
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 3 NA
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(2,1,3)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 2 2 2
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 2 NA
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
|
Here is another more concise solution, comparing to my other one. I think the use of `cur_data()` function is very helpful but you could also use `across(everything())` in its place:
```
library(dplyr)
library(purrr)
unique(sub("(\\D)_\\d+", "\\1", names(df))) %>%
map_dfc(~ df %>%
select(starts_with(.x)) %>%
summarise(!!.x := do.call(coalesce, cur_data())))
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
Here is another solution for as many pairs as possible. Just note that I used `bang bang` operator (`!!!`) in order to collapse elements of a data frame into standalone single arguments so that I could apply `coalesce` on them:
```
library(dplyr)
library(rlang)
as.data.frame(do.call(cbind, lapply(split.default(df, sub("(\\D)_\\d+", "\\1", names(df))), function(x) {
coalesce(!!!x)
})))
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
|
70,442,285
|
I want a code to be highlighted like this
jmp **label** ;comments
I want only **label** to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case **jmp** is brightmagenta also.
How can I implement this? I want only **label** to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.
[](https://i.stack.imgur.com/OyK0T.jpg)
Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file[](https://i.stack.imgur.com/1cfxR.jpg)
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70442285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17735779/"
] |
Here is another more concise solution, comparing to my other one. I think the use of `cur_data()` function is very helpful but you could also use `across(everything())` in its place:
```
library(dplyr)
library(purrr)
unique(sub("(\\D)_\\d+", "\\1", names(df))) %>%
map_dfc(~ df %>%
select(starts_with(.x)) %>%
summarise(!!.x := do.call(coalesce, cur_data())))
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
Here is another solution for as many pairs as possible. Just note that I used `bang bang` operator (`!!!`) in order to collapse elements of a data frame into standalone single arguments so that I could apply `coalesce` on them:
```
library(dplyr)
library(rlang)
as.data.frame(do.call(cbind, lapply(split.default(df, sub("(\\D)_\\d+", "\\1", names(df))), function(x) {
coalesce(!!!x)
})))
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
|
Here is an alternative with pivoting:
```
library(dplyr)
library(tidyr)
df %>%
pivot_longer(
everything()
) %>%
mutate(name = substr(name, 1, 1)) %>%
na.omit %>%
pivot_wider(
names_from = name,
values_from = value,
values_fn = list
) %>%
unnest(cols = c(A, B))
```
```
A B
<dbl> <dbl>
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
|
70,442,285
|
I want a code to be highlighted like this
jmp **label** ;comments
I want only **label** to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case **jmp** is brightmagenta also.
How can I implement this? I want only **label** to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.
[](https://i.stack.imgur.com/OyK0T.jpg)
Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file[](https://i.stack.imgur.com/1cfxR.jpg)
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70442285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17735779/"
] |
A base R option
```
list2DF(
lapply(
split.default(df, gsub("_.*", "", names(df))),
rowSums,
na.rm = TRUE
)
)
```
gives
```
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
|
I have asked for it here: <https://github.com/tidyverse/dplyr/issues/6109> where there are some possible solutions. For example
```r
library(dplyr)
library(purrr)
df %>%
transmute(map2_dfc(.x = across(ends_with("_1"), .names = '{sub("_1","",.col)}'),
.y = across(ends_with("_2")),
.f = coalesce))
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
Or also using the function
```r
coalesce_prefix <- function(prefix) {
exprs <- map(prefix, function(p) {
expr(coalesce(
!!sym(paste0(p, ".x")),
!!sym(paste0(p, ".y"))
))
})
names(exprs) <- prefix
exprs
}
```
|
70,442,285
|
I want a code to be highlighted like this
jmp **label** ;comments
I want only **label** to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case **jmp** is brightmagenta also.
How can I implement this? I want only **label** to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.
[](https://i.stack.imgur.com/OyK0T.jpg)
Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file[](https://i.stack.imgur.com/1cfxR.jpg)
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70442285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17735779/"
] |
You could use transmute, e.g.
```r
library(dplyr)
df <- data.frame(
A_1 = c(NA, NA, 3, 4, 5),
A_2 = c(1, 2, NA, NA, NA),
B_1 = c(NA, NA, 13, 14, 15),
B_2 = c(11, 12, NA, NA, NA)
)
df %>%
transmute(A = coalesce(A_1, A_2),
B = coalesce(B_1, B_2))
#> A B
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
#> 5 5 15
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
Another option, if you have lots of "A\_\*" and "B\_\*" columns (source: [Romain François](https://github.com/tidyverse/funs/issues/54#issuecomment-613882658), user: [@Romain Francois](https://stackoverflow.com/users/499163/romain-francois)):
```r
library(dplyr)
df <- data.frame(
A_1 = c(NA, NA, 3, 4, 5),
A_2 = c(1, 2, NA, NA, NA),
B_1 = c(NA, NA, 13, 14, 15),
B_2 = c(11, 12, NA, NA, NA)
)
coacross <- function(...) {
coalesce(!!!across(...))
}
df %>%
transmute(A = coacross(starts_with("A_")),
B = coacross(starts_with("B_")))
#> A B
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
#> 5 5 15
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
Edit
----
Based on your updated question, you don't have lots of "A\_\*" or "B\_\*" columns, but instead lots of "\*\_1", "\*\_2", and "\*\_3" columns. I think this is the most straightforward solution for your use-case:
```r
library(dplyr)
df <- data.frame(Al_TAC4.25.275 = c(1, 1, 1, NA, NA, NA),
Al_TAC4.25.276 = c(NA, NA, 2, 2, 2, NA),
Al_TAC4.25.277 = c(NA, NA, 3, NA, NA, 3),
Au_TAC4.25.275 = c(1, 1, 1, NA, NA, NA),
Au_TAC4.25.276 = c(NA, NA, 2, 2, 2, NA),
Au_TAC4.25.277 = c(NA, NA, 3, NA, NA, NA),
Ar_TAC4.25.275 = c(1, 1, 1, NA, NA, 1),
Ar_TAC4.25.276 = c(NA, NA, 2, 2, 2, 2),
Ar_TAC4.25.277 = c(NA, NA, 3, NA, NA, 3))
df
#> Al_TAC4.25.275 Al_TAC4.25.276 Al_TAC4.25.277 Au_TAC4.25.275 Au_TAC4.25.276
#> 1 1 NA NA 1 NA
#> 2 1 NA NA 1 NA
#> 3 1 2 3 1 2
#> 4 NA 2 NA NA 2
#> 5 NA 2 NA NA 2
#> 6 NA NA 3 NA NA
#> Au_TAC4.25.277 Ar_TAC4.25.275 Ar_TAC4.25.276 Ar_TAC4.25.277
#> 1 NA 1 NA NA
#> 2 NA 1 NA NA
#> 3 3 1 2 3
#> 4 NA NA 2 NA
#> 5 NA NA 2 NA
#> 6 NA 1 2 3
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(1,2,3)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 1 1 1
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 1 NA
# change the order of the list to change the 'priority'
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(3,2,1)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 3 3 3
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 3 NA
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(2,1,3)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 2 2 2
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 2 NA
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
|
Here is an alternative with pivoting:
```
library(dplyr)
library(tidyr)
df %>%
pivot_longer(
everything()
) %>%
mutate(name = substr(name, 1, 1)) %>%
na.omit %>%
pivot_wider(
names_from = name,
values_from = value,
values_fn = list
) %>%
unnest(cols = c(A, B))
```
```
A B
<dbl> <dbl>
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
|
70,442,285
|
I want a code to be highlighted like this
jmp **label** ;comments
I want only **label** to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case **jmp** is brightmagenta also.
How can I implement this? I want only **label** to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.
[](https://i.stack.imgur.com/OyK0T.jpg)
Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file[](https://i.stack.imgur.com/1cfxR.jpg)
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70442285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17735779/"
] |
A base R option
```
list2DF(
lapply(
split.default(df, gsub("_.*", "", names(df))),
rowSums,
na.rm = TRUE
)
)
```
gives
```
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
|
Edit: I believe this solution continues to work even after your edit. It works regardless of the number of elements or the number of cores per element. You just need to make sure things are named consistently, in the form `"{element}_{core}"`.
```
library(tidyverse)
df %>%
mutate(id = 1:n()) %>%
pivot_longer(-id) %>%
filter(!is.na(value)) %>%
mutate(variable = str_extract(name, "^[^_]+")) %>%
group_by(id, variable) %>%
# Arrange by name (e.g. A_1) so that we could select the first non-NA
arrange(name) %>%
summarise(value = value[1]) %>%
pivot_wider(names_from = "variable")
```
Output
```
# A tibble: 5 x 3
id A B
<int> <dbl> <dbl>
1 1 1 11
2 2 2 12
3 3 3 13
4 4 4 14
5 5 5 15
```
|
70,442,285
|
I want a code to be highlighted like this
jmp **label** ;comments
I want only **label** to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case **jmp** is brightmagenta also.
How can I implement this? I want only **label** to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.
[](https://i.stack.imgur.com/OyK0T.jpg)
Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file[](https://i.stack.imgur.com/1cfxR.jpg)
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70442285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17735779/"
] |
Here is another more concise solution, comparing to my other one. I think the use of `cur_data()` function is very helpful but you could also use `across(everything())` in its place:
```
library(dplyr)
library(purrr)
unique(sub("(\\D)_\\d+", "\\1", names(df))) %>%
map_dfc(~ df %>%
select(starts_with(.x)) %>%
summarise(!!.x := do.call(coalesce, cur_data())))
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
Here is another solution for as many pairs as possible. Just note that I used `bang bang` operator (`!!!`) in order to collapse elements of a data frame into standalone single arguments so that I could apply `coalesce` on them:
```
library(dplyr)
library(rlang)
as.data.frame(do.call(cbind, lapply(split.default(df, sub("(\\D)_\\d+", "\\1", names(df))), function(x) {
coalesce(!!!x)
})))
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
|
Edit: I believe this solution continues to work even after your edit. It works regardless of the number of elements or the number of cores per element. You just need to make sure things are named consistently, in the form `"{element}_{core}"`.
```
library(tidyverse)
df %>%
mutate(id = 1:n()) %>%
pivot_longer(-id) %>%
filter(!is.na(value)) %>%
mutate(variable = str_extract(name, "^[^_]+")) %>%
group_by(id, variable) %>%
# Arrange by name (e.g. A_1) so that we could select the first non-NA
arrange(name) %>%
summarise(value = value[1]) %>%
pivot_wider(names_from = "variable")
```
Output
```
# A tibble: 5 x 3
id A B
<int> <dbl> <dbl>
1 1 1 11
2 2 2 12
3 3 3 13
4 4 4 14
5 5 5 15
```
|
70,442,285
|
I want a code to be highlighted like this
jmp **label** ;comments
I want only **label** to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case **jmp** is brightmagenta also.
How can I implement this? I want only **label** to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.
[](https://i.stack.imgur.com/OyK0T.jpg)
Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file[](https://i.stack.imgur.com/1cfxR.jpg)
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70442285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17735779/"
] |
You could use transmute, e.g.
```r
library(dplyr)
df <- data.frame(
A_1 = c(NA, NA, 3, 4, 5),
A_2 = c(1, 2, NA, NA, NA),
B_1 = c(NA, NA, 13, 14, 15),
B_2 = c(11, 12, NA, NA, NA)
)
df %>%
transmute(A = coalesce(A_1, A_2),
B = coalesce(B_1, B_2))
#> A B
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
#> 5 5 15
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
Another option, if you have lots of "A\_\*" and "B\_\*" columns (source: [Romain François](https://github.com/tidyverse/funs/issues/54#issuecomment-613882658), user: [@Romain Francois](https://stackoverflow.com/users/499163/romain-francois)):
```r
library(dplyr)
df <- data.frame(
A_1 = c(NA, NA, 3, 4, 5),
A_2 = c(1, 2, NA, NA, NA),
B_1 = c(NA, NA, 13, 14, 15),
B_2 = c(11, 12, NA, NA, NA)
)
coacross <- function(...) {
coalesce(!!!across(...))
}
df %>%
transmute(A = coacross(starts_with("A_")),
B = coacross(starts_with("B_")))
#> A B
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
#> 5 5 15
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
Edit
----
Based on your updated question, you don't have lots of "A\_\*" or "B\_\*" columns, but instead lots of "\*\_1", "\*\_2", and "\*\_3" columns. I think this is the most straightforward solution for your use-case:
```r
library(dplyr)
df <- data.frame(Al_TAC4.25.275 = c(1, 1, 1, NA, NA, NA),
Al_TAC4.25.276 = c(NA, NA, 2, 2, 2, NA),
Al_TAC4.25.277 = c(NA, NA, 3, NA, NA, 3),
Au_TAC4.25.275 = c(1, 1, 1, NA, NA, NA),
Au_TAC4.25.276 = c(NA, NA, 2, 2, 2, NA),
Au_TAC4.25.277 = c(NA, NA, 3, NA, NA, NA),
Ar_TAC4.25.275 = c(1, 1, 1, NA, NA, 1),
Ar_TAC4.25.276 = c(NA, NA, 2, 2, 2, 2),
Ar_TAC4.25.277 = c(NA, NA, 3, NA, NA, 3))
df
#> Al_TAC4.25.275 Al_TAC4.25.276 Al_TAC4.25.277 Au_TAC4.25.275 Au_TAC4.25.276
#> 1 1 NA NA 1 NA
#> 2 1 NA NA 1 NA
#> 3 1 2 3 1 2
#> 4 NA 2 NA NA 2
#> 5 NA 2 NA NA 2
#> 6 NA NA 3 NA NA
#> Au_TAC4.25.277 Ar_TAC4.25.275 Ar_TAC4.25.276 Ar_TAC4.25.277
#> 1 NA 1 NA NA
#> 2 NA 1 NA NA
#> 3 3 1 2 3
#> 4 NA NA 2 NA
#> 5 NA NA 2 NA
#> 6 NA 1 2 3
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(1,2,3)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 1 1 1
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 1 NA
# change the order of the list to change the 'priority'
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(3,2,1)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 3 3 3
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 3 NA
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(2,1,3)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 2 2 2
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 2 NA
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
|
A base R option
```
list2DF(
lapply(
split.default(df, gsub("_.*", "", names(df))),
rowSums,
na.rm = TRUE
)
)
```
gives
```
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
|
70,442,285
|
I want a code to be highlighted like this
jmp **label** ;comments
I want only **label** to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case **jmp** is brightmagenta also.
How can I implement this? I want only **label** to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.
[](https://i.stack.imgur.com/OyK0T.jpg)
Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file[](https://i.stack.imgur.com/1cfxR.jpg)
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70442285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17735779/"
] |
You could use transmute, e.g.
```r
library(dplyr)
df <- data.frame(
A_1 = c(NA, NA, 3, 4, 5),
A_2 = c(1, 2, NA, NA, NA),
B_1 = c(NA, NA, 13, 14, 15),
B_2 = c(11, 12, NA, NA, NA)
)
df %>%
transmute(A = coalesce(A_1, A_2),
B = coalesce(B_1, B_2))
#> A B
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
#> 5 5 15
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
Another option, if you have lots of "A\_\*" and "B\_\*" columns (source: [Romain François](https://github.com/tidyverse/funs/issues/54#issuecomment-613882658), user: [@Romain Francois](https://stackoverflow.com/users/499163/romain-francois)):
```r
library(dplyr)
df <- data.frame(
A_1 = c(NA, NA, 3, 4, 5),
A_2 = c(1, 2, NA, NA, NA),
B_1 = c(NA, NA, 13, 14, 15),
B_2 = c(11, 12, NA, NA, NA)
)
coacross <- function(...) {
coalesce(!!!across(...))
}
df %>%
transmute(A = coacross(starts_with("A_")),
B = coacross(starts_with("B_")))
#> A B
#> 1 1 11
#> 2 2 12
#> 3 3 13
#> 4 4 14
#> 5 5 15
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
Edit
----
Based on your updated question, you don't have lots of "A\_\*" or "B\_\*" columns, but instead lots of "\*\_1", "\*\_2", and "\*\_3" columns. I think this is the most straightforward solution for your use-case:
```r
library(dplyr)
df <- data.frame(Al_TAC4.25.275 = c(1, 1, 1, NA, NA, NA),
Al_TAC4.25.276 = c(NA, NA, 2, 2, 2, NA),
Al_TAC4.25.277 = c(NA, NA, 3, NA, NA, 3),
Au_TAC4.25.275 = c(1, 1, 1, NA, NA, NA),
Au_TAC4.25.276 = c(NA, NA, 2, 2, 2, NA),
Au_TAC4.25.277 = c(NA, NA, 3, NA, NA, NA),
Ar_TAC4.25.275 = c(1, 1, 1, NA, NA, 1),
Ar_TAC4.25.276 = c(NA, NA, 2, 2, 2, 2),
Ar_TAC4.25.277 = c(NA, NA, 3, NA, NA, 3))
df
#> Al_TAC4.25.275 Al_TAC4.25.276 Al_TAC4.25.277 Au_TAC4.25.275 Au_TAC4.25.276
#> 1 1 NA NA 1 NA
#> 2 1 NA NA 1 NA
#> 3 1 2 3 1 2
#> 4 NA 2 NA NA 2
#> 5 NA 2 NA NA 2
#> 6 NA NA 3 NA NA
#> Au_TAC4.25.277 Ar_TAC4.25.275 Ar_TAC4.25.276 Ar_TAC4.25.277
#> 1 NA 1 NA NA
#> 2 NA 1 NA NA
#> 3 3 1 2 3
#> 4 NA NA 2 NA
#> 5 NA NA 2 NA
#> 6 NA 1 2 3
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(1,2,3)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 1 1 1
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 1 NA
# change the order of the list to change the 'priority'
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(3,2,1)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 3 3 3
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 3 NA
names(df) %>%
split(str_extract(., '[:alpha:]+')) %>%
map_dfc(~ coalesce(!!!df[.x][c(2,1,3)]))
#> # A tibble: 6 × 3
#> Al Ar Au
#> <dbl> <dbl> <dbl>
#> 1 1 1 1
#> 2 1 1 1
#> 3 2 2 2
#> 4 2 2 2
#> 5 2 2 2
#> 6 3 2 NA
```
Created on 2021-12-22 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
|
I have asked for it here: <https://github.com/tidyverse/dplyr/issues/6109> where there are some possible solutions. For example
```r
library(dplyr)
library(purrr)
df %>%
transmute(map2_dfc(.x = across(ends_with("_1"), .names = '{sub("_1","",.col)}'),
.y = across(ends_with("_2")),
.f = coalesce))
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
Or also using the function
```r
coalesce_prefix <- function(prefix) {
exprs <- map(prefix, function(p) {
expr(coalesce(
!!sym(paste0(p, ".x")),
!!sym(paste0(p, ".y"))
))
})
names(exprs) <- prefix
exprs
}
```
|
70,442,285
|
I want a code to be highlighted like this
jmp **label** ;comments
I want only **label** to be highlighted. I've tried something like this
context exclusive jmp\t \n brightmagenta
But in this case ";comments" turned brightmagenta as well which is not what I want. For the comments there is another exclusive context. I've tried also
keyword jmp\t\[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@\] brightmagenta
But in this case **jmp** is brightmagenta also.
How can I implement this? I want only **label** to be affected by highlighting while comments are highlighted in the same manner everywhere(in the attached picture comments for jnz is brightmagenta and in the line after brown) and all the jumps are not affected by highlighting, hence I don't need to add them (and all other commands, variable, constants etc.) manually to the syntax file.
[](https://i.stack.imgur.com/OyK0T.jpg)
Closely related question, since every assembly programmer uses invoke macro is it possible to highlight just the function like in screenshot below? Function was written as keyword in syntax file however I don't want all the functions to the syntax file[](https://i.stack.imgur.com/1cfxR.jpg)
|
2021/12/21
|
[
"https://Stackoverflow.com/questions/70442285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17735779/"
] |
A base R option
```
list2DF(
lapply(
split.default(df, gsub("_.*", "", names(df))),
rowSums,
na.rm = TRUE
)
)
```
gives
```
A B
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
|
Here is an alternative with pivoting:
```
library(dplyr)
library(tidyr)
df %>%
pivot_longer(
everything()
) %>%
mutate(name = substr(name, 1, 1)) %>%
na.omit %>%
pivot_wider(
names_from = name,
values_from = value,
values_fn = list
) %>%
unnest(cols = c(A, B))
```
```
A B
<dbl> <dbl>
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
```
|
52,591,696
|
Suppose I have several dataframes: df1, df2, df3, etc. The label with each dataframes is A1, A2, A3 etc. I want to use this information as a whole, so that I can pass them. Three methods came into my mind:
### method 1
use a label list: `labels=["A1", "A2", "A3"...]` and a list of dataframes `dfs=[df1, df2, df3...]`.
### method 2
use a dictionary: `d={"A1": df1, "A2": df2, "A3": df3}`.
### method 3
use a pandas series: `s=pd.Series([df1, df2, df3], index=["A1", "A2", "A3"])`.
I will use the label and dataframes **sequentially**, therefore I think method1 and method3 should be my choice. However, using method 1 will need me to pass two items, while using method 3 I only need to keep one object. **Is it a common practice to put the dataframes in a series?** I seldom see people do this, is it against best practice? Is there any better suggestions?
|
2018/10/01
|
[
"https://Stackoverflow.com/questions/52591696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2794152/"
] |
An `OrderedDict` would probably be more conventional than using a series for this.
```
from collections import OrderedDict
d = OrderedDict([("A1", df1), ("A2", df2), ("A3", df3)])
```
This can easily be iterated over:
```
for label, df in d:
print(label, df)
```
That said I can't see any strong reason not to use a pandas series. A small advantage of using the series is that you can access the dataframes using dot notation `s.A1`, `s.A2` etc. as well as using the dictionary-like notation `s["A1"]`. Using a series, it would also be relatively easy to sort the dataframes, insert additional ones in the middle, or associate additional metadata with them later if needed.
(See [this question](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) on dictionary ordering in Python 3.6 and 3.7 - you may be able to use an ordinary dictionary instead of an `OrderedDict` if using Python 3.7 and you don't need to use other 'ordered' behaviours. In Python 3.6, the preservation of insertion order is an implementation detail and should not be relied upon.)
|
Method 2 also works. Since Python 3.6 it remembers the order it is created too.
|
727,766
|
I am trying to bind data from SQL to a repeater control. I have tried what I usually do for a Gridview and it doesn't work. I would like to see an example whether it be using an SQLAdapter or using ExecuteReader from a command. Thank you!
```
string sql = "SELECT [WallPost], [DatePosted] FROM [WallTable] WHERE [UserId] = '"
+ Request["friend"] + "'";
string strCon =
System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlDataAdapter daUserProfile = new SqlDataAdapter(sql, conn);
dsSocialSite.UserProfileDataTable tbUserProfile =
new dsSocialSite.UserProfileDataTable();
daUserProfile.Fill(tbUserProfile);
rpWall2.DataSource = tbUserProfile; //rpWall2 = repeater control
rpWall2.DataBind();
```
|
2009/04/07
|
[
"https://Stackoverflow.com/questions/727766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84786/"
] |
Using an example I had knocked up the other day
```
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true"CodeFile="Default.aspx.cs" Inherits="Default2"
Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
<div id="Questions" align="center" style="background-color: #C0C0C0">
<asp:Repeater ID="QuestionsRepeater" runat="server"
DataSourceID="SqlDataSourceQuestions">
<ItemTemplate>
<div align="left" style="text-indent: 15px">
<asp:Label ID="Label1"
runat="server" Text= '<%# Eval("QCategory") %>'
Font-Bold="True" Font-Size="Medium"></asp:Label>
</div>
<br />
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
DataSourceID="SqlDataSourceRatings" DataTextField="RatingsCategory"
DataValueField="RatingsCategory" RepeatDirection="Horizontal" >
</asp:RadioButtonList>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSourceQuestions" runat="server"
ConnectionString="<%$ ConnectionStrings:sandboxConnectionString %>"
SelectCommand="SELECT [QCategory] FROM [QuestionsCategory]">
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSourceRatings" runat="server"
ConnectionString="<%$ ConnectionStrings:sandboxConnectionString %>"
SelectCommand="SELECT [RatingsCategory], [RatingsId] FROM [Ratings]">
```
|
Doing it on the html (as in John Nolans answer) side is easier with the repeater since it uses templates.
If you want to do it in code behind, create a class that implements ITemplate then place it like so:
```
myRepeater.ItemTemplate = new MyTemplateClass();
```
|
3,955,820
|
On my site, I load jQuery UI script using the following code:
`wp_enqueue_script('nf-jquery-ui','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js')`
In my plugin I use the following code:
`wp_enqueue_script('wp_filebrowser-jqueryui','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js')`
The result is that both these lines are added to my header - and loading a script twice is not very good.
Yes, I know I can remove it from either my plugin or my site. But the point is that anyone can download my plugin, and they might already be loading the jQuery UI script.
How can I avoid having a script being added twice?
|
2010/10/17
|
[
"https://Stackoverflow.com/questions/3955820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91612/"
] |
You could deregister the first script by putting this line in your plugin...
```
wp_deregister_script( 'nf-jquery-ui');
```
before you call your 'enqueue script'
```
wp_enqueue_script('wp_filebrowser-jqueryui','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js')
```
This should remove the first jQuery call on all pages that use your plugin.
|
The [WP API states](http://codex.wordpress.org/Function_Reference/wp_enqueue_script) the first param is a handler. That one is probably used so a script is only inserted once (although I can not say for sure).
It also [defines handlers](http://codex.wordpress.org/Function_Reference/wp_enqueue_script#Default_scripts_included_with_WordPress) for jQuery and jQuery UI which you should probably use. Those handlers are for included scripts and jQuery as well as jQuery-ui is listed there. If you want to update consider passing the version to the wp\_-function or just replacing the jQuery script file that’s already in use / packaged with wp.
|
42,493,272
|
simple project, but a beginner at programming, so struggling. I am trying to set a couple of buttons to create a slider to change pictures. My problem is that when I set the position attribute to absolute in the div that contains the buttons, the div element that contains the buttons disappears.
So this is a screenshot of my page with position set to relative:
```
.buttons {
cursor: pointer;
position: relative;
}
```
[](https://i.stack.imgur.com/ccLCH.png)
and this is with it set to absolute:
```
.buttons {
cursor: pointer;
position: absolute;
}
```
[](https://i.stack.imgur.com/e8qsg.png)
And here is the code
html
```
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Photography</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="JavaScript2b.js"></script>
<script type="text/javascript" src="JavaScript2.js"></script>
</head>
<body>
<div id="header">
</div>
<div id="container">
<div id="imagewrap">
<img src="Images/01Folder/Image.jpg" height="500px" id="front" />
<div id="previous" class="buttons" onclick="change(-1);">
</div>
<div id="next" class="buttons" onclick="change(1);">
</div>
</div>
</div>
<div id="footer">
</div>
</body>
<script type="text/javascript" src="JavaScript2.js"></script>
</html>
```
css
```
html, body {
margin: 0px;
padding: 0px;
height: 100vh;
}
#header {
position: relative;
height: 10%;
width: 100%;
background-color: lightgray;
}
#footer {
position: relative;
height: 10%;
width: 100%;
background-color: lightgray;
display: block;
}
#container {
height: 80%;
width: 100vw;
background-color: white;
min-height: 580px;
text-align: center;
}
#imagewrap{
position: relative;
border: 1px solid #818181;
overflow: hidden;
z-index: 5;
display: inline-block;
top: 50%;
transform: translateY(-50%);
}
.buttons {
cursor: pointer;
position: relative;
}
#previous {
background-image: url(Images/carremoins.png);
background-repeat: no-repeat;
background-position: center center;
width: 20px;
height: 20px;
}
#next {
background-image: url(Images/carreplus.png);
background-repeat: no-repeat;
width: 20px;
height: 20px;
background-position: center center;
}
```
I would like the buttons to be on the picture, not below it, but can't understand why they disappear. Any help appreciated.
|
2017/02/27
|
[
"https://Stackoverflow.com/questions/42493272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5684416/"
] |
Try setting the z-index on the buttons to a value larger than that of the image (5).
```
.buttons {
cursor: pointer;
position: relative;
z-index: 10;
}
```
|
Your container, `#imagewrap`, has `overflow: hidden`. When you make its children `position: absolute`, you remove them from calculations determining the size of the parent element, so the parent is no longer large enough to display the children. That means they are overflow, which you have specified should be hidden.
You can solve this problem in several ways, depending on your needs. You can allow overflow, reposition the children so they are inside of the parent, and/or increase the size of the parent such that it encompasses its children. Any or all will make the children visible.
|
110,768
|
I have created a SharePoint 2013 Workflow in Visual Studio 2012. This workflow is activated when a list item is modified.
Once the list item modified, the workflow shows as the started. But on clicking "started" or "workflow name", it throws an error:
>
> The given key was not present in the dictionary.
>
>
> **Stack Trace**
>
>
> [KeyNotFoundException: The given key was not present in the dictionary.]
> System.Collections.Generic.Dictionary`2.get\_Item(TKey key) +14122715
> Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider.GetRetryMessage(WorkflowInstance instance) +936
> Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider.GetInstance(Guid instanceId) +463
> Microsoft.SharePoint.WorkflowServices.ApplicationPages.WrkStatPage.OnLoad(EventArgs e) +611
> System.Web.UI.Control.LoadRecursive() +71
> System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178
>
>
>
Edit:
Prior to the above error, an http 401 error (Token contains invalid signature) was thrown on workflow initiation. After following the steps mentioned [here](http://blogs.technet.com/b/projectsupport/archive/2014/01/13/sharepoint-2013-workflow-token-contains-invalid-signature.aspx), it started throwing the above error.
|
2014/08/05
|
[
"https://sharepoint.stackexchange.com/questions/110768",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/4399/"
] |
Yes it is possible.
It is a SharePoint limitation, each Workflow is associated with one Task list and one History list but we can overcome this by creating 2010 workflow and call that in 2013 workflow.
SharePoint designer workflow 2013 allows you to call 2010 site workflows or List workflows.
So, you can create two 2010 workflows and associate the respective task lists in that workflow and create tasks using that.
In your case:
In WF Stage:Escalate - Call a 2010 workflow which will create task in "Escalate Tasks" list.
In WF Stage:Exception - Call a 2010 workflow which will create task in "Exception Tasks" list.
Hope this is useful.
|
Yes it is possible.
You can use SharePoint Designer to create the workflow and create new items to any(or multiple) lists.
Regards
|
27,163,209
|
I am new at Symfony. My Symfony version is 2.5.7 I have generated a CRUD using "`generate:doctrine:crud`".
There is a delete button, in the view of each entry. I want to add css class inside button.
For this button, the generated code is -
```
{{ form(delete_form) }}
```
By inspection from the browser, I got -
```
<button type="submit" id="form_submit" name="form[submit]">Delete</button>
```
I have modified the generated twig code to -
```
{{ form_widget(delete_form, {'attr': {'class': 'btn btn-danger btn-lg'}}) }}
```
By inspection from the browser, I got -
```
<div id="form" class="btn btn-danger btn-lg">
<div>
<button type="submit" id="form_submit" name="form[submit]">Delete</button>
</div>
<input type="hidden" id="form__token" name="form[_token]" value="JrBKKEdf1F8hBDYIzu0TP9a4fauKvmlPMGg3rHwwA3w">
</div>
```
So, the button is look like, now -

But I want it like -

So, my generated code should be look like -
```
<div>
<button type="submit" id="form_submit" name="form[submit]" class="btn btn-danger btn-lg">Delete</button>
</div>
```
I have tried like, but it does not work - It is just showing normal delete button as, no class is included -
```
{{ form_widget(delete_form.submit, { 'label': 'Delete' }, { 'attr': {'class': 'btn btn-danger btn-lg', 'type': 'button'} }) }}
```
By the way, without the following twig code delete button does not delete the entry --
```
{{ form(delete_form) }}
```
How can I do it from with twig???
|
2014/11/27
|
[
"https://Stackoverflow.com/questions/27163209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/622896/"
] |
I have solved the problem.. :) but not from twig.. from controller.. I have added the css class to `createDeleteForm()` method...
```
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('book_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete',
'attr' => array('class' => 'btn btn-danger btn-lg')))
->getForm()
;
}
```
But i think, it is not the good practice.. :(
|
Expanding on [Zed's](https://stackoverflow.com/a/27165580/1069375) answer, but I also needed the label in another language, all without touching anything other than the TWIG template:
```
{{ form_widget(delete_form.submit, {'label': 'Usuń', 'attr': {'class': 'btn btn-danger btn-lg', 'type': 'button', 'title': 'DELETE'} }) }}
```
Later on the same page, changed the default Update button:
```
{{ form_widget(edit_form.submit, {'label': 'Zapisz', 'attr': {'class': 'btn btn-save btn-lg', 'type': 'button', 'title': 'UPDATE'} }) }}
```
|
27,163,209
|
I am new at Symfony. My Symfony version is 2.5.7 I have generated a CRUD using "`generate:doctrine:crud`".
There is a delete button, in the view of each entry. I want to add css class inside button.
For this button, the generated code is -
```
{{ form(delete_form) }}
```
By inspection from the browser, I got -
```
<button type="submit" id="form_submit" name="form[submit]">Delete</button>
```
I have modified the generated twig code to -
```
{{ form_widget(delete_form, {'attr': {'class': 'btn btn-danger btn-lg'}}) }}
```
By inspection from the browser, I got -
```
<div id="form" class="btn btn-danger btn-lg">
<div>
<button type="submit" id="form_submit" name="form[submit]">Delete</button>
</div>
<input type="hidden" id="form__token" name="form[_token]" value="JrBKKEdf1F8hBDYIzu0TP9a4fauKvmlPMGg3rHwwA3w">
</div>
```
So, the button is look like, now -

But I want it like -

So, my generated code should be look like -
```
<div>
<button type="submit" id="form_submit" name="form[submit]" class="btn btn-danger btn-lg">Delete</button>
</div>
```
I have tried like, but it does not work - It is just showing normal delete button as, no class is included -
```
{{ form_widget(delete_form.submit, { 'label': 'Delete' }, { 'attr': {'class': 'btn btn-danger btn-lg', 'type': 'button'} }) }}
```
By the way, without the following twig code delete button does not delete the entry --
```
{{ form(delete_form) }}
```
How can I do it from with twig???
|
2014/11/27
|
[
"https://Stackoverflow.com/questions/27163209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/622896/"
] |
I have solved the problem.. :) but not from twig.. from controller.. I have added the css class to `createDeleteForm()` method...
```
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('book_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete',
'attr' => array('class' => 'btn btn-danger btn-lg')))
->getForm()
;
}
```
But i think, it is not the good practice.. :(
|
All the answers here works to add the class to the submit button. However, if one just uses this line with delete\_form.submit the form won't work. The complete answer is:
```
{{ form_start(delete_form) }}
{{ form_widget(delete_form.submit, { 'attr': {'class': 'btn btn-danger', 'type': 'button'} }) }}
{{ form_end(delete_form) }}
```
As it is explained on the doc, form\_widget doesn't render the form start and end tags:
```
{# renders all fields #}
{{ form_widget(form) }}
{# renders all fields *and* the form start and end tags #}
{{ form(form) }}
```
|
27,163,209
|
I am new at Symfony. My Symfony version is 2.5.7 I have generated a CRUD using "`generate:doctrine:crud`".
There is a delete button, in the view of each entry. I want to add css class inside button.
For this button, the generated code is -
```
{{ form(delete_form) }}
```
By inspection from the browser, I got -
```
<button type="submit" id="form_submit" name="form[submit]">Delete</button>
```
I have modified the generated twig code to -
```
{{ form_widget(delete_form, {'attr': {'class': 'btn btn-danger btn-lg'}}) }}
```
By inspection from the browser, I got -
```
<div id="form" class="btn btn-danger btn-lg">
<div>
<button type="submit" id="form_submit" name="form[submit]">Delete</button>
</div>
<input type="hidden" id="form__token" name="form[_token]" value="JrBKKEdf1F8hBDYIzu0TP9a4fauKvmlPMGg3rHwwA3w">
</div>
```
So, the button is look like, now -

But I want it like -

So, my generated code should be look like -
```
<div>
<button type="submit" id="form_submit" name="form[submit]" class="btn btn-danger btn-lg">Delete</button>
</div>
```
I have tried like, but it does not work - It is just showing normal delete button as, no class is included -
```
{{ form_widget(delete_form.submit, { 'label': 'Delete' }, { 'attr': {'class': 'btn btn-danger btn-lg', 'type': 'button'} }) }}
```
By the way, without the following twig code delete button does not delete the entry --
```
{{ form(delete_form) }}
```
How can I do it from with twig???
|
2014/11/27
|
[
"https://Stackoverflow.com/questions/27163209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/622896/"
] |
Remove `{ 'label': 'Delete' }` and it should work. Here is an example:
```
{{ form_widget(delete_form.submit, { 'attr': {'class': 'btn btn-danger btn-lg', 'type': 'button'} }) }}
```
|
Expanding on [Zed's](https://stackoverflow.com/a/27165580/1069375) answer, but I also needed the label in another language, all without touching anything other than the TWIG template:
```
{{ form_widget(delete_form.submit, {'label': 'Usuń', 'attr': {'class': 'btn btn-danger btn-lg', 'type': 'button', 'title': 'DELETE'} }) }}
```
Later on the same page, changed the default Update button:
```
{{ form_widget(edit_form.submit, {'label': 'Zapisz', 'attr': {'class': 'btn btn-save btn-lg', 'type': 'button', 'title': 'UPDATE'} }) }}
```
|
27,163,209
|
I am new at Symfony. My Symfony version is 2.5.7 I have generated a CRUD using "`generate:doctrine:crud`".
There is a delete button, in the view of each entry. I want to add css class inside button.
For this button, the generated code is -
```
{{ form(delete_form) }}
```
By inspection from the browser, I got -
```
<button type="submit" id="form_submit" name="form[submit]">Delete</button>
```
I have modified the generated twig code to -
```
{{ form_widget(delete_form, {'attr': {'class': 'btn btn-danger btn-lg'}}) }}
```
By inspection from the browser, I got -
```
<div id="form" class="btn btn-danger btn-lg">
<div>
<button type="submit" id="form_submit" name="form[submit]">Delete</button>
</div>
<input type="hidden" id="form__token" name="form[_token]" value="JrBKKEdf1F8hBDYIzu0TP9a4fauKvmlPMGg3rHwwA3w">
</div>
```
So, the button is look like, now -

But I want it like -

So, my generated code should be look like -
```
<div>
<button type="submit" id="form_submit" name="form[submit]" class="btn btn-danger btn-lg">Delete</button>
</div>
```
I have tried like, but it does not work - It is just showing normal delete button as, no class is included -
```
{{ form_widget(delete_form.submit, { 'label': 'Delete' }, { 'attr': {'class': 'btn btn-danger btn-lg', 'type': 'button'} }) }}
```
By the way, without the following twig code delete button does not delete the entry --
```
{{ form(delete_form) }}
```
How can I do it from with twig???
|
2014/11/27
|
[
"https://Stackoverflow.com/questions/27163209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/622896/"
] |
Remove `{ 'label': 'Delete' }` and it should work. Here is an example:
```
{{ form_widget(delete_form.submit, { 'attr': {'class': 'btn btn-danger btn-lg', 'type': 'button'} }) }}
```
|
All the answers here works to add the class to the submit button. However, if one just uses this line with delete\_form.submit the form won't work. The complete answer is:
```
{{ form_start(delete_form) }}
{{ form_widget(delete_form.submit, { 'attr': {'class': 'btn btn-danger', 'type': 'button'} }) }}
{{ form_end(delete_form) }}
```
As it is explained on the doc, form\_widget doesn't render the form start and end tags:
```
{# renders all fields #}
{{ form_widget(form) }}
{# renders all fields *and* the form start and end tags #}
{{ form(form) }}
```
|
22,527,216
|
For good understanding I will take a simple abstraction of DHCP lease as example: The lease contains the IP and MAC address, the time it was granted at and can be renewed with a given time span. Once expired an event will be invoked. Again, this is just serving as the most minimal example I could come up with:
```
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Timers;
namespace Example
{
public class Lease
{
public IPAddress IP
{
get;
private set;
}
public PhysicalAddress MAC
{
get;
private set;
}
public DateTime Granted
{
get;
private set;
}
public event EventHandler Expired;
private readonly Timer timer;
public Lease(IPAddress ip, PhysicalAddress mac, TimeSpan available)
{
IP = ip;
MAC = mac;
timer = new Timer();
timer.AutoReset = false;
timer.Elapsed += timerElapsed;
Renew(available);
}
public void timerElapsed(object sender, EventArgs e)
{
var handle = Expired;
if (handle != null)
{
handle(this, EventArgs.Empty);
}
}
public void Renew(TimeSpan available)
{
Granted = DateTime.Now;
timer.Interval = available.TotalMilliseconds;
timer.Enabled = true;
}
}
}
```
Is there anything to consider when creating - for example - "a few thousand" instances of such a class? I am mostly concerned about the timers. **Should I consider another design pattern for such a task** (like a manager for all the leases,or not use timers at all?) **or is there nothing to worry about when creating a lot of timers, and this is the appropriate way?** At least I always try to be cautious when it comes to timers and events.
|
2014/03/20
|
[
"https://Stackoverflow.com/questions/22527216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333312/"
] |
Rather than creating thousands of timers, you could just store the expiration time of each `Lease` object, then in a single thread query for the expired ones periodically.
An off the top of my head code example:
```
var leases = new List<Lease>();
var running = true;
var expiredChecker = Task.Factory.StartNew(() =>
{
while (running)
{
var expired = leases.All(l => l.ExpirationDate < DateTime.Now);
// do something with the expired lease objects
}
});
```
Assuming you have an `IEnumerable<Lease>`, a `DateTime` property called `ExpirationDate` on your `Lease` object, you can then cancel this by setting running to false when you want to stop.
|
According to the [`System.Timers.Timer` MSDN page](http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.110%29.aspx):
>
> The server-based Timer is designed for use with worker threads in a
> multithreaded environment. Server timers can move among threads to
> handle the raised Elapsed event, resulting in more accuracy than
> Windows timers in raising the event on time.
>
>
>
Which means it is not very likely to be causing issues when you are running a couple thousand timers at the same time.
That doesn't mean it is a good approach, you should probably be looking for a more centralized solution to this problem.
|
22,527,216
|
For good understanding I will take a simple abstraction of DHCP lease as example: The lease contains the IP and MAC address, the time it was granted at and can be renewed with a given time span. Once expired an event will be invoked. Again, this is just serving as the most minimal example I could come up with:
```
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Timers;
namespace Example
{
public class Lease
{
public IPAddress IP
{
get;
private set;
}
public PhysicalAddress MAC
{
get;
private set;
}
public DateTime Granted
{
get;
private set;
}
public event EventHandler Expired;
private readonly Timer timer;
public Lease(IPAddress ip, PhysicalAddress mac, TimeSpan available)
{
IP = ip;
MAC = mac;
timer = new Timer();
timer.AutoReset = false;
timer.Elapsed += timerElapsed;
Renew(available);
}
public void timerElapsed(object sender, EventArgs e)
{
var handle = Expired;
if (handle != null)
{
handle(this, EventArgs.Empty);
}
}
public void Renew(TimeSpan available)
{
Granted = DateTime.Now;
timer.Interval = available.TotalMilliseconds;
timer.Enabled = true;
}
}
}
```
Is there anything to consider when creating - for example - "a few thousand" instances of such a class? I am mostly concerned about the timers. **Should I consider another design pattern for such a task** (like a manager for all the leases,or not use timers at all?) **or is there nothing to worry about when creating a lot of timers, and this is the appropriate way?** At least I always try to be cautious when it comes to timers and events.
|
2014/03/20
|
[
"https://Stackoverflow.com/questions/22527216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333312/"
] |
I would suppose this depends partly on what resources you have available on your server, and what kind of accuracy and performance you need.
An alternative approach might be to store something as simple as a time stamp in each instance, and checking that value regularly, comparing it to current time, and updating it appropriately. I have a hunch that this *might* be easier on performance - but you should try to benchmark it somehow to be sure.
Of course, if you have a large number of instances, iterating over all of them might also take some time, so perhaps pooling these into groups, where each group is handled in a separate thread on regular (adjustable?) intervals might be an option.
It's a bit hard to give a great answer here without some info about performance, so you should probably just create a proof of concept, and test a couple of strategies that you think might work, and try to benchmark them to see which fits best.
|
According to the [`System.Timers.Timer` MSDN page](http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.110%29.aspx):
>
> The server-based Timer is designed for use with worker threads in a
> multithreaded environment. Server timers can move among threads to
> handle the raised Elapsed event, resulting in more accuracy than
> Windows timers in raising the event on time.
>
>
>
Which means it is not very likely to be causing issues when you are running a couple thousand timers at the same time.
That doesn't mean it is a good approach, you should probably be looking for a more centralized solution to this problem.
|
22,527,216
|
For good understanding I will take a simple abstraction of DHCP lease as example: The lease contains the IP and MAC address, the time it was granted at and can be renewed with a given time span. Once expired an event will be invoked. Again, this is just serving as the most minimal example I could come up with:
```
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Timers;
namespace Example
{
public class Lease
{
public IPAddress IP
{
get;
private set;
}
public PhysicalAddress MAC
{
get;
private set;
}
public DateTime Granted
{
get;
private set;
}
public event EventHandler Expired;
private readonly Timer timer;
public Lease(IPAddress ip, PhysicalAddress mac, TimeSpan available)
{
IP = ip;
MAC = mac;
timer = new Timer();
timer.AutoReset = false;
timer.Elapsed += timerElapsed;
Renew(available);
}
public void timerElapsed(object sender, EventArgs e)
{
var handle = Expired;
if (handle != null)
{
handle(this, EventArgs.Empty);
}
}
public void Renew(TimeSpan available)
{
Granted = DateTime.Now;
timer.Interval = available.TotalMilliseconds;
timer.Enabled = true;
}
}
}
```
Is there anything to consider when creating - for example - "a few thousand" instances of such a class? I am mostly concerned about the timers. **Should I consider another design pattern for such a task** (like a manager for all the leases,or not use timers at all?) **or is there nothing to worry about when creating a lot of timers, and this is the appropriate way?** At least I always try to be cautious when it comes to timers and events.
|
2014/03/20
|
[
"https://Stackoverflow.com/questions/22527216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333312/"
] |
Rather than creating thousands of timers, you could just store the expiration time of each `Lease` object, then in a single thread query for the expired ones periodically.
An off the top of my head code example:
```
var leases = new List<Lease>();
var running = true;
var expiredChecker = Task.Factory.StartNew(() =>
{
while (running)
{
var expired = leases.All(l => l.ExpirationDate < DateTime.Now);
// do something with the expired lease objects
}
});
```
Assuming you have an `IEnumerable<Lease>`, a `DateTime` property called `ExpirationDate` on your `Lease` object, you can then cancel this by setting running to false when you want to stop.
|
I recommend use a `System.Threading.Timer` instead of the `System.Timers.Timer`. The second one is wrapper about the first one to be visible in the design time and it is not necessary if you really don't need design time support. **Timer internally calls ThreadPool.QueueUseWorkItem**, than threadpool is responsible for maintaining thread on timer tick. **Thread pool uses only one thread to maintain all the timers** object and this thread decide when each timer queue new thread on timer tick.
Than I cant see **any** overhead unless your timers will tick so quick than you are not able do all on tick job and you simply queue too much work in thread pool.
|
22,527,216
|
For good understanding I will take a simple abstraction of DHCP lease as example: The lease contains the IP and MAC address, the time it was granted at and can be renewed with a given time span. Once expired an event will be invoked. Again, this is just serving as the most minimal example I could come up with:
```
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Timers;
namespace Example
{
public class Lease
{
public IPAddress IP
{
get;
private set;
}
public PhysicalAddress MAC
{
get;
private set;
}
public DateTime Granted
{
get;
private set;
}
public event EventHandler Expired;
private readonly Timer timer;
public Lease(IPAddress ip, PhysicalAddress mac, TimeSpan available)
{
IP = ip;
MAC = mac;
timer = new Timer();
timer.AutoReset = false;
timer.Elapsed += timerElapsed;
Renew(available);
}
public void timerElapsed(object sender, EventArgs e)
{
var handle = Expired;
if (handle != null)
{
handle(this, EventArgs.Empty);
}
}
public void Renew(TimeSpan available)
{
Granted = DateTime.Now;
timer.Interval = available.TotalMilliseconds;
timer.Enabled = true;
}
}
}
```
Is there anything to consider when creating - for example - "a few thousand" instances of such a class? I am mostly concerned about the timers. **Should I consider another design pattern for such a task** (like a manager for all the leases,or not use timers at all?) **or is there nothing to worry about when creating a lot of timers, and this is the appropriate way?** At least I always try to be cautious when it comes to timers and events.
|
2014/03/20
|
[
"https://Stackoverflow.com/questions/22527216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333312/"
] |
I would suppose this depends partly on what resources you have available on your server, and what kind of accuracy and performance you need.
An alternative approach might be to store something as simple as a time stamp in each instance, and checking that value regularly, comparing it to current time, and updating it appropriately. I have a hunch that this *might* be easier on performance - but you should try to benchmark it somehow to be sure.
Of course, if you have a large number of instances, iterating over all of them might also take some time, so perhaps pooling these into groups, where each group is handled in a separate thread on regular (adjustable?) intervals might be an option.
It's a bit hard to give a great answer here without some info about performance, so you should probably just create a proof of concept, and test a couple of strategies that you think might work, and try to benchmark them to see which fits best.
|
I recommend use a `System.Threading.Timer` instead of the `System.Timers.Timer`. The second one is wrapper about the first one to be visible in the design time and it is not necessary if you really don't need design time support. **Timer internally calls ThreadPool.QueueUseWorkItem**, than threadpool is responsible for maintaining thread on timer tick. **Thread pool uses only one thread to maintain all the timers** object and this thread decide when each timer queue new thread on timer tick.
Than I cant see **any** overhead unless your timers will tick so quick than you are not able do all on tick job and you simply queue too much work in thread pool.
|
48,166,675
|
I have 3 tables (T\_BONUS\_TAB, T\_COND, T\_BONUS\_COND\_LINK).
One of them connects (T\_BONUS\_COND\_LINK) two other tables.
This table has 3 columns: bonus\_id, cond\_id (references to parent tables) and another column with additional value (priority).
```
create table T_BONUS_COND_LINK
(
cond_id NUMBER(9) not null,
bonus_id NUMBER(9) not null,
priority NUMBER(1)
)
alter table T_BONUS_COND_LINK
add constraint T_BONUS_COND_B_FK foreign key (BONUS_ID)
references T_BONUS_TAB (ROW_ID);
alter table T_BONUS_COND_LINK
add constraint T_BONUS_COND_M_FK foreign key (COND_ID)
references T_COND (ROW_ID);
```
The question is how get value of priority column?
```
@Entity(name = ENTITY_NAME)
@Table(name = "T_BONUS_TAB")
@Customizer(EclipseLinkIssuesFixer.class)
public class BonusApplication extends AbstractIdentifiableByLongEntity {
...
@OneToMany(fetch = EAGER)
@JoinTable(
name="T_BONUS_COND_LINK",
joinColumns = @JoinColumn( name="BONUS_ID"),
inverseJoinColumns = @JoinColumn( name="COND_ID")
)
private List<Condition> conds;
....
}
@Entity(name = ENTITY_NAME)
@Table(name = "T_COND")
@Customizer(EclipseLinkIssuesFixer.class)
public class CONDITION extends AbstractIdentifiableByLongEntity {
@Id
@Column(name = "ROW_ID", nullable = false, updatable = false)
private Long id;
@Column(name = "NAME", insertable = false, updatable = false)
private String name;
@Column(name = "DESCX", updatable = false)
private String desc;
}
```
|
2018/01/09
|
[
"https://Stackoverflow.com/questions/48166675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7913988/"
] |
The big difference is that with the `else`, the second condition will not be checked *at all* if the first condition was true. Without the `else`, the second condition will be checked.
Ramifications of that:
* If the conditions are not mutually-exclusive, without the `else` both could match and both `if` bodies could be executed.
* If the conditions involve *side effects*, without the `else` the second evaluation will trigger the side-effect a second time.
* As [dasblinkenlight](https://stackoverflow.com/users/335858/dasblinkenlight) pointed out in a now-deleted [comment](https://stackoverflow.com/questions/48166660/whats-the-difference-between-using-an-else-if-statement-and-just-creating-a-new/48166689?noredirect=1#comment83312646_48166689) below (and now in [his answer](https://stackoverflow.com/a/48166967/157247)), if `x` is a volatile field and its value is changed by another thread after the first check and before the second, without the `else` both conditions could match and both `if` bodies could be executed.
To see what I mean about evaluation, let's make `x` a function call with a side effect instead of just a variable (Java and JavaScript are **very different**, but in this case, we can use JavaScript to demonstrate the concept):
```js
function x() {
console.log("x called");
return 42;
}
console.log("With else:");
if (x() > 1) {
console.log("> 1");
} else if (x() < 1) {
console.log("< 1");
}
console.log("Without else:");
if (x() > 1) {
console.log("> 1");
}
if (x() < 1) {
console.log("< 1");
}
```
```css
.as-console-wrapper {
max-height: 100% !important;
}
```
Note that `x` is called *twice* without the `else`, but only once with the `else`.
|
**In your example it makes no difference** but now if you have something a little bit **different** like this:
```
if (x >= 1) {
System.out.println("Hello!");
}
if (x <= 1) {
System.out.println("Bye!");
}
```
It will print the two string (if x equal 1) as the conditions are both `true`
|
48,166,675
|
I have 3 tables (T\_BONUS\_TAB, T\_COND, T\_BONUS\_COND\_LINK).
One of them connects (T\_BONUS\_COND\_LINK) two other tables.
This table has 3 columns: bonus\_id, cond\_id (references to parent tables) and another column with additional value (priority).
```
create table T_BONUS_COND_LINK
(
cond_id NUMBER(9) not null,
bonus_id NUMBER(9) not null,
priority NUMBER(1)
)
alter table T_BONUS_COND_LINK
add constraint T_BONUS_COND_B_FK foreign key (BONUS_ID)
references T_BONUS_TAB (ROW_ID);
alter table T_BONUS_COND_LINK
add constraint T_BONUS_COND_M_FK foreign key (COND_ID)
references T_COND (ROW_ID);
```
The question is how get value of priority column?
```
@Entity(name = ENTITY_NAME)
@Table(name = "T_BONUS_TAB")
@Customizer(EclipseLinkIssuesFixer.class)
public class BonusApplication extends AbstractIdentifiableByLongEntity {
...
@OneToMany(fetch = EAGER)
@JoinTable(
name="T_BONUS_COND_LINK",
joinColumns = @JoinColumn( name="BONUS_ID"),
inverseJoinColumns = @JoinColumn( name="COND_ID")
)
private List<Condition> conds;
....
}
@Entity(name = ENTITY_NAME)
@Table(name = "T_COND")
@Customizer(EclipseLinkIssuesFixer.class)
public class CONDITION extends AbstractIdentifiableByLongEntity {
@Id
@Column(name = "ROW_ID", nullable = false, updatable = false)
private Long id;
@Column(name = "NAME", insertable = false, updatable = false)
private String name;
@Column(name = "DESCX", updatable = false)
private String desc;
}
```
|
2018/01/09
|
[
"https://Stackoverflow.com/questions/48166675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7913988/"
] |
**In your example it makes no difference** but now if you have something a little bit **different** like this:
```
if (x >= 1) {
System.out.println("Hello!");
}
if (x <= 1) {
System.out.println("Bye!");
}
```
It will print the two string (if x equal 1) as the conditions are both `true`
|
The difference is on the runtime. In the if...else if... case if the case of if it is correct the else if will not be examined. In if.. and then another if.. both the cases of if's will be examined, so on the runtime you have one more comparison. In such a small programm will not make the difference, but consider a huge program with thousands of if cases.
Hope I covered you!
|
48,166,675
|
I have 3 tables (T\_BONUS\_TAB, T\_COND, T\_BONUS\_COND\_LINK).
One of them connects (T\_BONUS\_COND\_LINK) two other tables.
This table has 3 columns: bonus\_id, cond\_id (references to parent tables) and another column with additional value (priority).
```
create table T_BONUS_COND_LINK
(
cond_id NUMBER(9) not null,
bonus_id NUMBER(9) not null,
priority NUMBER(1)
)
alter table T_BONUS_COND_LINK
add constraint T_BONUS_COND_B_FK foreign key (BONUS_ID)
references T_BONUS_TAB (ROW_ID);
alter table T_BONUS_COND_LINK
add constraint T_BONUS_COND_M_FK foreign key (COND_ID)
references T_COND (ROW_ID);
```
The question is how get value of priority column?
```
@Entity(name = ENTITY_NAME)
@Table(name = "T_BONUS_TAB")
@Customizer(EclipseLinkIssuesFixer.class)
public class BonusApplication extends AbstractIdentifiableByLongEntity {
...
@OneToMany(fetch = EAGER)
@JoinTable(
name="T_BONUS_COND_LINK",
joinColumns = @JoinColumn( name="BONUS_ID"),
inverseJoinColumns = @JoinColumn( name="COND_ID")
)
private List<Condition> conds;
....
}
@Entity(name = ENTITY_NAME)
@Table(name = "T_COND")
@Customizer(EclipseLinkIssuesFixer.class)
public class CONDITION extends AbstractIdentifiableByLongEntity {
@Id
@Column(name = "ROW_ID", nullable = false, updatable = false)
private Long id;
@Column(name = "NAME", insertable = false, updatable = false)
private String name;
@Column(name = "DESCX", updatable = false)
private String desc;
}
```
|
2018/01/09
|
[
"https://Stackoverflow.com/questions/48166675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7913988/"
] |
The big difference is that with the `else`, the second condition will not be checked *at all* if the first condition was true. Without the `else`, the second condition will be checked.
Ramifications of that:
* If the conditions are not mutually-exclusive, without the `else` both could match and both `if` bodies could be executed.
* If the conditions involve *side effects*, without the `else` the second evaluation will trigger the side-effect a second time.
* As [dasblinkenlight](https://stackoverflow.com/users/335858/dasblinkenlight) pointed out in a now-deleted [comment](https://stackoverflow.com/questions/48166660/whats-the-difference-between-using-an-else-if-statement-and-just-creating-a-new/48166689?noredirect=1#comment83312646_48166689) below (and now in [his answer](https://stackoverflow.com/a/48166967/157247)), if `x` is a volatile field and its value is changed by another thread after the first check and before the second, without the `else` both conditions could match and both `if` bodies could be executed.
To see what I mean about evaluation, let's make `x` a function call with a side effect instead of just a variable (Java and JavaScript are **very different**, but in this case, we can use JavaScript to demonstrate the concept):
```js
function x() {
console.log("x called");
return 42;
}
console.log("With else:");
if (x() > 1) {
console.log("> 1");
} else if (x() < 1) {
console.log("< 1");
}
console.log("Without else:");
if (x() > 1) {
console.log("> 1");
}
if (x() < 1) {
console.log("< 1");
}
```
```css
.as-console-wrapper {
max-height: 100% !important;
}
```
Note that `x` is called *twice* without the `else`, but only once with the `else`.
|
As far as the logic is concerned, as long as the two statements use mutually exclusive condition, and it is not possible to change `x` concurrently with your running thread, there would be no difference.
However,
* There would be a difference in execution if `x` is modified concurrently: the second version could produce both `"Hello"` and `"Bye"`, or no output at all
* There would be a difference in execution because the second condition must be re-evaluated in your second snippet regardless of the computation of the first condition, while your first snippet will evaluate only one condition when `x > 1`
* The above assumes that the statements inside the first condition do not interrupt the thread, i.e. it's not a `return`, a `break`, a `continue`, or a `throw`. If the thread is interrupted, `else` is no longer necessary.
|
48,166,675
|
I have 3 tables (T\_BONUS\_TAB, T\_COND, T\_BONUS\_COND\_LINK).
One of them connects (T\_BONUS\_COND\_LINK) two other tables.
This table has 3 columns: bonus\_id, cond\_id (references to parent tables) and another column with additional value (priority).
```
create table T_BONUS_COND_LINK
(
cond_id NUMBER(9) not null,
bonus_id NUMBER(9) not null,
priority NUMBER(1)
)
alter table T_BONUS_COND_LINK
add constraint T_BONUS_COND_B_FK foreign key (BONUS_ID)
references T_BONUS_TAB (ROW_ID);
alter table T_BONUS_COND_LINK
add constraint T_BONUS_COND_M_FK foreign key (COND_ID)
references T_COND (ROW_ID);
```
The question is how get value of priority column?
```
@Entity(name = ENTITY_NAME)
@Table(name = "T_BONUS_TAB")
@Customizer(EclipseLinkIssuesFixer.class)
public class BonusApplication extends AbstractIdentifiableByLongEntity {
...
@OneToMany(fetch = EAGER)
@JoinTable(
name="T_BONUS_COND_LINK",
joinColumns = @JoinColumn( name="BONUS_ID"),
inverseJoinColumns = @JoinColumn( name="COND_ID")
)
private List<Condition> conds;
....
}
@Entity(name = ENTITY_NAME)
@Table(name = "T_COND")
@Customizer(EclipseLinkIssuesFixer.class)
public class CONDITION extends AbstractIdentifiableByLongEntity {
@Id
@Column(name = "ROW_ID", nullable = false, updatable = false)
private Long id;
@Column(name = "NAME", insertable = false, updatable = false)
private String name;
@Column(name = "DESCX", updatable = false)
private String desc;
}
```
|
2018/01/09
|
[
"https://Stackoverflow.com/questions/48166675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7913988/"
] |
The big difference is that with the `else`, the second condition will not be checked *at all* if the first condition was true. Without the `else`, the second condition will be checked.
Ramifications of that:
* If the conditions are not mutually-exclusive, without the `else` both could match and both `if` bodies could be executed.
* If the conditions involve *side effects*, without the `else` the second evaluation will trigger the side-effect a second time.
* As [dasblinkenlight](https://stackoverflow.com/users/335858/dasblinkenlight) pointed out in a now-deleted [comment](https://stackoverflow.com/questions/48166660/whats-the-difference-between-using-an-else-if-statement-and-just-creating-a-new/48166689?noredirect=1#comment83312646_48166689) below (and now in [his answer](https://stackoverflow.com/a/48166967/157247)), if `x` is a volatile field and its value is changed by another thread after the first check and before the second, without the `else` both conditions could match and both `if` bodies could be executed.
To see what I mean about evaluation, let's make `x` a function call with a side effect instead of just a variable (Java and JavaScript are **very different**, but in this case, we can use JavaScript to demonstrate the concept):
```js
function x() {
console.log("x called");
return 42;
}
console.log("With else:");
if (x() > 1) {
console.log("> 1");
} else if (x() < 1) {
console.log("< 1");
}
console.log("Without else:");
if (x() > 1) {
console.log("> 1");
}
if (x() < 1) {
console.log("< 1");
}
```
```css
.as-console-wrapper {
max-height: 100% !important;
}
```
Note that `x` is called *twice* without the `else`, but only once with the `else`.
|
The difference is on the runtime. In the if...else if... case if the case of if it is correct the else if will not be examined. In if.. and then another if.. both the cases of if's will be examined, so on the runtime you have one more comparison. In such a small programm will not make the difference, but consider a huge program with thousands of if cases.
Hope I covered you!
|
48,166,675
|
I have 3 tables (T\_BONUS\_TAB, T\_COND, T\_BONUS\_COND\_LINK).
One of them connects (T\_BONUS\_COND\_LINK) two other tables.
This table has 3 columns: bonus\_id, cond\_id (references to parent tables) and another column with additional value (priority).
```
create table T_BONUS_COND_LINK
(
cond_id NUMBER(9) not null,
bonus_id NUMBER(9) not null,
priority NUMBER(1)
)
alter table T_BONUS_COND_LINK
add constraint T_BONUS_COND_B_FK foreign key (BONUS_ID)
references T_BONUS_TAB (ROW_ID);
alter table T_BONUS_COND_LINK
add constraint T_BONUS_COND_M_FK foreign key (COND_ID)
references T_COND (ROW_ID);
```
The question is how get value of priority column?
```
@Entity(name = ENTITY_NAME)
@Table(name = "T_BONUS_TAB")
@Customizer(EclipseLinkIssuesFixer.class)
public class BonusApplication extends AbstractIdentifiableByLongEntity {
...
@OneToMany(fetch = EAGER)
@JoinTable(
name="T_BONUS_COND_LINK",
joinColumns = @JoinColumn( name="BONUS_ID"),
inverseJoinColumns = @JoinColumn( name="COND_ID")
)
private List<Condition> conds;
....
}
@Entity(name = ENTITY_NAME)
@Table(name = "T_COND")
@Customizer(EclipseLinkIssuesFixer.class)
public class CONDITION extends AbstractIdentifiableByLongEntity {
@Id
@Column(name = "ROW_ID", nullable = false, updatable = false)
private Long id;
@Column(name = "NAME", insertable = false, updatable = false)
private String name;
@Column(name = "DESCX", updatable = false)
private String desc;
}
```
|
2018/01/09
|
[
"https://Stackoverflow.com/questions/48166675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7913988/"
] |
As far as the logic is concerned, as long as the two statements use mutually exclusive condition, and it is not possible to change `x` concurrently with your running thread, there would be no difference.
However,
* There would be a difference in execution if `x` is modified concurrently: the second version could produce both `"Hello"` and `"Bye"`, or no output at all
* There would be a difference in execution because the second condition must be re-evaluated in your second snippet regardless of the computation of the first condition, while your first snippet will evaluate only one condition when `x > 1`
* The above assumes that the statements inside the first condition do not interrupt the thread, i.e. it's not a `return`, a `break`, a `continue`, or a `throw`. If the thread is interrupted, `else` is no longer necessary.
|
The difference is on the runtime. In the if...else if... case if the case of if it is correct the else if will not be examined. In if.. and then another if.. both the cases of if's will be examined, so on the runtime you have one more comparison. In such a small programm will not make the difference, but consider a huge program with thousands of if cases.
Hope I covered you!
|
203,022
|
On Christmas I got a 3DS XL with new Super Mario Bros. 2 Gold Edition. I wanted to do a system transfer from my old 3DS. But after the transfer my Mario game was gone.
How should I get my game back?
|
2015/01/26
|
[
"https://gaming.stackexchange.com/questions/203022",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/100565/"
] |
If you did a system transfer, it should have transferred the downloaded game and/or any save data as long as you followed all of the instructions, and moved the SD card from the old 3DS to the new one.
You can try redownloading the game from the 3DS eShop, if you connected your Nintendo ID to it and that information transferred appropriately, and you had it as a downloaded game instead of the physical card, but your save will likely be gone.
|
When you get a new 3DS with a game pre-installed, and you transferred data to that 3DS, the game will be gone. Simply re-download it for free off the e-shop. Save data stays as I redownloaded games I already had digitally and all my progress stayed intact.
|
72,385,128
|
I have a working script that contains the following code in a method of a custom class:
```
destination = this
._source
.makeCopy(
this._name,
this._folder
)
.setStarred(true);
```
This script is taking approximately 15 seconds to complete. `this._source` is an instance of DriveApp.File (`DriveApp.getFileById('xxxxxxxxxxxx')`) of the template file the user is working with. `this._name` is simply a string created by tacking the year onto the title. 'this.\_folder' is an instance of DriveApp.Folder (`DriveApp.getFolderById('xxxxxxxxxxxx')`). All of these except for `destination` are instantiated when the class is instantiated in my On Open trigger, long before the user begins making the copy, while `destination` is instantiated at the beginning of this method (though I measured that instantiation to be pretty fast).
I measured 15380 milliseconds before and after this statement. I isolated `DriveApp.File.setStarred()` and measured 100 milliseconds, so the problem is down to `DriveApp.File.makeCopy()`. Is there anything I can do to get a faster result? I tried the various versions of `.makeCopy`, and they all seemed to take a while. I think the problem is the size of my actual file (178 KB, which I believe is fairly large for a Sheets file). It has 13 Sheets, one for the entire year's revenue numbers, and twelve months of daily reconciliation for cash drawers, the safe, and bank deposits/withdrawals, so it has a myriad of formulas in it.
|
2022/05/25
|
[
"https://Stackoverflow.com/questions/72385128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/579701/"
] |
**SUGGESTION:**
You could try [Drive API V2 Files:copy](https://developers.google.com/drive/api/v2/reference/files/copy) method. Initially tested this on a 280kb sheets file which resulted in 11000 milliseconds in computation time using the API Explorer.
|
### Not sure if it's faster all of the time but it seems faster to me
```
function makeCopy() {
var folderid = "dfolderid";
var fileid = "fileid";
var folder = Drive.Files.get(folderid, { "supportsAllDrives": true });
var newFile = { "fileId": fileid, "parents": [folder] };
var args = { "resource": { "parents": [folder], "title": "new Title" }, "supportsAllDrives": true };
Drive.Files.copy(newFile, fileid, args);
}
```
|
17,367,700
|
I have created a form with the option to dynamically add fields with excellent code help from <http://charlie.griefer.com/blog/2009/09/17/jquery-dynamically-adding-form-elements/>. The only issue is that I want the fields to generate without also showing new 'Add' and 'Remove' buttons. How should I go about doing this? I can get it to work by having the buttons displayed underneath the field with a new `<div>` but I want them to be to the right of the field.
```
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first')
.attr('id', 'device' + newNum)
.attr('name', 'device' + newNum);
$('#input' + num).after(newElem);
$('#btnDel').attr('disabled','');
if (newNum == 3)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove();
$('#btnAdd').attr('disabled','');
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
```
```
<div> Name: <input type="text" name="name" id="name" /></div>
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
Device(s): <input type="text" name="device1" id="device1" />
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnDel" value="Remove" />
</div>
```
|
2013/06/28
|
[
"https://Stackoverflow.com/questions/17367700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2532297/"
] |
Like this?
```
var arrClasses = [];
$("div[class*='some-class-']").removeClass(function () { // Select the element divs which has class that starts with some-class-
var className = this.className.match(/some-class-\d+/); //get a match to match the pattern some-class-somenumber and extract that classname
if (className) {
arrClasses.push(className[0]); //if it is the one then push it to array
return className[0]; //return it for removal
}
});
console.log(arrClasses);
```
**[Fiddle](http://jsfiddle.net/ps6hK/)**
**[.removeClass()](http://api.jquery.com/removeClass/)** accepts a callback function to do some operation and return the className to be removed, if nothing to be removed return nothing.
|
You could loop through all the elements, pull the class name using a regular expression, and store them in an array:
```js
var classNames = [];
$('div[class*="some-class-"]').each(function(i, el){
var name = (el.className.match(/(^|\s)(some\-class\-[^\s]*)/) || [,,''])[2];
if(name){
classNames.push(name);
$(el).removeClass(name);
}
});
console.log(classNames);
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class-x some-class-1 other-class"></div>
<div class="some-class-45 class-y"></div>
<div class="some-class-123 something-else"></div>
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.