qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
12,176 | What are the best ways to translate `For all you know`?
For example:
>
> For all you know, she could be lying to you.
>
>
> In response to a friend getting upset that her friend isn't picking up her phone, I respond, "For all you know, something could have happened."
>
>
> A neighbor sends us some vegetables and I tell my wife, "We better wash them first, for all we know, they could be covered in pesticide"
>
>
> | 2015/01/22 | [
"https://chinese.stackexchange.com/questions/12176",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/3011/"
] | Agree with StumpyJoePete.
As we all know = Everybody knows.
For all you know = You don't really know for sure.
I think Damian Siniakowicz's suggestion will work.
We better wash the vegetables first, for all we know, they could be covered in pesticide
我们还是先把蔬菜洗一下,说不定有農藥呢。
A couple more suggestions:
我们还是先把蔬菜洗一下,誰知道有沒有農藥呢?
我们还是先把蔬菜洗一下,可能有農藥呢。 | For all you know, she could be lying to you.
听你所见,她可有在骗你. |
12,176 | What are the best ways to translate `For all you know`?
For example:
>
> For all you know, she could be lying to you.
>
>
> In response to a friend getting upset that her friend isn't picking up her phone, I respond, "For all you know, something could have happened."
>
>
> A neighbor sends us some vegetables and I tell my wife, "We better wash them first, for all we know, they could be covered in pesticide"
>
>
> | 2015/01/22 | [
"https://chinese.stackexchange.com/questions/12176",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/3011/"
] | Agree with StumpyJoePete.
As we all know = Everybody knows.
For all you know = You don't really know for sure.
I think Damian Siniakowicz's suggestion will work.
We better wash the vegetables first, for all we know, they could be covered in pesticide
我们还是先把蔬菜洗一下,说不定有農藥呢。
A couple more suggestions:
我们还是先把蔬菜洗一下,誰知道有沒有農藥呢?
我们还是先把蔬菜洗一下,可能有農藥呢。 | 天知道 is also ok
"For all you know, something could have happened."
說不定發生了一些事情
"We better wash them first, for all we know, they could be covered in pesticide"
還是先洗洗,天知道有沒有農藥 |
12,176 | What are the best ways to translate `For all you know`?
For example:
>
> For all you know, she could be lying to you.
>
>
> In response to a friend getting upset that her friend isn't picking up her phone, I respond, "For all you know, something could have happened."
>
>
> A neighbor sends us some vegetables and I tell my wife, "We better wash them first, for all we know, they could be covered in pesticide"
>
>
> | 2015/01/22 | [
"https://chinese.stackexchange.com/questions/12176",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/3011/"
] | Just found this interesting [discussion](http://forum.wordreference.com/showthread.php?t=477816). It offered a definition:
>
> This expression [for all you know] can be used in any context where the speaker wishes to convey that the listener is failing (deliberately or otherwise) to consider all the possibilities.
>
>
>
And some paraphrases:
```
it wouldn't be surprising if
it would make sense to think
You have no knowledge that would disprove that
As far as you're concerned, it is entirely possible that
You might very well assume that
```
All typical English style phrases that defy direct translation.
没准, 说不定, 谁知道 are all good, but the style is a bit off because the "you" part is omitted. So I propose this:
>
> For all you know, she could be lying to you.
> 你也说不准, 也许她对你撒谎了呢。
>
>
>
Also:
* for all I know -- 我也不敢肯定.
* for all we know -- 我们都说不准.
But sometimes it might be better to drop the pronoun and just use 说不准 and alike, depends on the situation and mood. | For all you know, she could be lying to you.
听你所见,她可有在骗你. |
12,176 | What are the best ways to translate `For all you know`?
For example:
>
> For all you know, she could be lying to you.
>
>
> In response to a friend getting upset that her friend isn't picking up her phone, I respond, "For all you know, something could have happened."
>
>
> A neighbor sends us some vegetables and I tell my wife, "We better wash them first, for all we know, they could be covered in pesticide"
>
>
> | 2015/01/22 | [
"https://chinese.stackexchange.com/questions/12176",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/3011/"
] | Just found this interesting [discussion](http://forum.wordreference.com/showthread.php?t=477816). It offered a definition:
>
> This expression [for all you know] can be used in any context where the speaker wishes to convey that the listener is failing (deliberately or otherwise) to consider all the possibilities.
>
>
>
And some paraphrases:
```
it wouldn't be surprising if
it would make sense to think
You have no knowledge that would disprove that
As far as you're concerned, it is entirely possible that
You might very well assume that
```
All typical English style phrases that defy direct translation.
没准, 说不定, 谁知道 are all good, but the style is a bit off because the "you" part is omitted. So I propose this:
>
> For all you know, she could be lying to you.
> 你也说不准, 也许她对你撒谎了呢。
>
>
>
Also:
* for all I know -- 我也不敢肯定.
* for all we know -- 我们都说不准.
But sometimes it might be better to drop the pronoun and just use 说不准 and alike, depends on the situation and mood. | 天知道 is also ok
"For all you know, something could have happened."
說不定發生了一些事情
"We better wash them first, for all we know, they could be covered in pesticide"
還是先洗洗,天知道有沒有農藥 |
12,176 | What are the best ways to translate `For all you know`?
For example:
>
> For all you know, she could be lying to you.
>
>
> In response to a friend getting upset that her friend isn't picking up her phone, I respond, "For all you know, something could have happened."
>
>
> A neighbor sends us some vegetables and I tell my wife, "We better wash them first, for all we know, they could be covered in pesticide"
>
>
> | 2015/01/22 | [
"https://chinese.stackexchange.com/questions/12176",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/3011/"
] | 天知道 is also ok
"For all you know, something could have happened."
說不定發生了一些事情
"We better wash them first, for all we know, they could be covered in pesticide"
還是先洗洗,天知道有沒有農藥 | For all you know, she could be lying to you.
听你所见,她可有在骗你. |
31,423 | I'm just starting to use CiviCRM. So I realize that this could be a very dumb question.
I'm trying to deduplicate contacts by name AND surname. When I create a new deduplicating rule using name and surname, it looks like it gets all the contacts with the same name OR surname.
For example, if I have
* Mario Rossi
* Mario Verdi
* Mario Bianchi
* Mario Neri
they are all shown as duplicates...but they are not.
Is there a way to create a rule which addresses just contacts with same name AND surname (or vice versa)?
Thank you in advance. | 2019/07/19 | [
"https://civicrm.stackexchange.com/questions/31423",
"https://civicrm.stackexchange.com",
"https://civicrm.stackexchange.com/users/7271/"
] | Welcome to CiviCRM SE. Eileen's answer is definitely the right place to start, but you might want to look at a related question that I asked about the built-in (reserved) de-duplicate rules, as they aren't entirely clear from the documentation. It says "NAME" in the description, but actually uses the fields "First Name" and "Last Name" (You have used different terminology. It took me a while to work out how it worked.
See [Reserved de-dupe rules](https://civicrm.stackexchange.com/questions/29155/reserved-de-dupe-rules)
Update: Remembering odd behaviour with my previous issues, I looked again and have found that the de-dupe rules appear to be cached. So if you create a rule, adjust it and try with the new version, the old version is still used. I missed this before because I was checking the database and the rule is updated properly there. If you go to Administer >> System >> Cleanup Caches and Update Paths and select Cleanup Caches then try the de-dupe rule again it works as expected. If you were experimenting, then I expect this is the problem.
Alternatively if you delete the rule and add the new version it will also work.
A note on the page where you edit de-dupe rules to tell you to clear the cache would be very helpful. Let me know if this solves your problem and I'll report it as a bug/enhancement. | I think this blog does a reasonable job of describing it <https://civicrm.org/blog/spidersilk/understanding-civicrm-dedupe-rules>
Here are the official docs
<https://docs.civicrm.org/user/en/latest/common-workflows/deduping-and-merging/>
* but we could do with pulling some in from the docs
Basically you need to check your weights - if you have them both set to '5' & the threshold is 10 then you need both for a dupe. If the threshold is 5 then either/or |
95,071 | Does anyone know if the house number is included in Mapbox’ vector tiles, and if so how to access it for styling? | 2014/05/06 | [
"https://gis.stackexchange.com/questions/95071",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/27171/"
] | Version 5 of the Mapbox Streets vector tiles includes the house number in a new layer.
I used the following to add them to the starting style:
```
#housenum_label {
text-name: '[house_num]';
text-face-name: @sans;
text-fill: darken(#cde, 20%);
text-size: 9;
}
``` | As far as I know, house numbers are not currently included in MapBox's vector tiles.
If you need to render a small region, you can get them in GeoJSON with [Overpass Turbo](http://overpass-turbo.eu/s/3mZ) (press "Run", then "Export" and "geoJSON"), which you can use in TileMill as a layer. For bigger regions you might need to process [planet extracts](http://download.geofabrik.de/) or the planet file itself. |
12,252,363 | 1) Does LSP also apply to interfaces, meaning that we should be able to use a class implementing a specific interface and still get the expected behavior?
2) If that is indeed the case, then why is programming to an interface considered a good thing ( BTW- I know that programming to an interface increases loose coupling ), if one of the main reasons against using inheritance is due to risk of not complying to LSP? Perhaps because:
a) benefits of loose coupling outweight the risks of not complying to LSP
b) compared to inheritance, chances that a class ( implementing an interface ) will not adher to LSP are much smaller
thank you | 2012/09/03 | [
"https://Stackoverflow.com/questions/12252363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483278/"
] | >
> Does LSP also apply to interfaces, meaning that we should be able to use a class implementing a specific interface and still get the expected behavior?
>
>
>
LSP applies to the contract. The contract may be a class or an interface.
>
> If that is indeed the case, then why is programming to an interface considered a good thing ( BTW- I know that programming to an interface increases loose coupling ), if one of the main reasons against using inheritance is due to risk of not complying to LSP? Perhaps because:
>
>
>
It's not about an interface or a class. It's about a violation of the contract. Let's say that you have a `Break()` method in a `IVehicle` (or `VehicleBase`). Anyone calling it would expect the vehicle to break. Imagine the surprise if one of the implementations didn't break. That's what LSP is all about.
>
> a) benefits of loose coupling outweight the risks of not complying to LSP
>
>
>
ehh?
>
> b) compared to inheritance, chances that a class ( implementing an interface ) will not adher to LSP are much smaller
>
>
>
ehh?
You might want to read my SOLID article to understand the principle better: <http://blog.gauffin.org/2012/05/solid-principles-with-real-world-examples/>
**Update**
>
> To elaborate - with inheritance virtual methods may consume private members, to which subclasses overriding these virtual methods don't have access to.
>
>
>
Yes. That's good. members (fields) should always be protected ( = declared as private). Only the class that defined them really know what their values should be.
>
> Also, derived class inherits the context from parent and as such can be broken by future changes to parent class etc.
>
>
>
That's a violation of Open/closed principle. i.e. the class contract is changed by changing the behavior. Classes should be extended and not modified. Sure, it's not possible all the time, but changes should not make the class behave differently (other than bugfixes).
>
> Thus I feel it's more difficult to make subclass honour the contract than it is to make class implementing an interface honour it
>
>
>
There is a common reason to why extension through inheritance is hard. And that's because the relationship isn't a true `is-a` relationship, but that the developer just want to take advantage of the base class functionality.
That's wrong. Better to use composition then. | I'm comparing/contrasting my code practice with LSP at the moment. I think it must be all to do with expectation and deciding how to define what should be expected. I'm not convinced that substitution always means the same thing. For instance, if I defined
```
interface ICalculation
{
double Calculate(double A, double B);
}
```
with the intention of defining `class Add : ICalculation`, `class Subtract : ICalculation`, `class Multiply : ICalculation` and `class Divide : ICalculation`, I believe that those classes should perform the respective `Calculation(A, B)`, however, I do not believe they should all pass the same unit tests. I like to use interfaces for extensibility, where each extension has a different function. In the case of a car braking, I would give classes the interface IBrakable and do this:
```
var myBrakableCar = MyCar as IBrakable;
if(myBrakableCar != null)
{
myBrakableCar.Brake();
}
```
I believe that classes should be predictable in their use, but also useful. Useful comes top.
I'm just going to create a new concept - "Respective Substition": it does what it says on the tin. |
12,252,363 | 1) Does LSP also apply to interfaces, meaning that we should be able to use a class implementing a specific interface and still get the expected behavior?
2) If that is indeed the case, then why is programming to an interface considered a good thing ( BTW- I know that programming to an interface increases loose coupling ), if one of the main reasons against using inheritance is due to risk of not complying to LSP? Perhaps because:
a) benefits of loose coupling outweight the risks of not complying to LSP
b) compared to inheritance, chances that a class ( implementing an interface ) will not adher to LSP are much smaller
thank you | 2012/09/03 | [
"https://Stackoverflow.com/questions/12252363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483278/"
] | >
> Does LSP also apply to interfaces, meaning that we should be able to use a class implementing a specific interface and still get the expected behavior?
>
>
>
LSP applies to the contract. The contract may be a class or an interface.
>
> If that is indeed the case, then why is programming to an interface considered a good thing ( BTW- I know that programming to an interface increases loose coupling ), if one of the main reasons against using inheritance is due to risk of not complying to LSP? Perhaps because:
>
>
>
It's not about an interface or a class. It's about a violation of the contract. Let's say that you have a `Break()` method in a `IVehicle` (or `VehicleBase`). Anyone calling it would expect the vehicle to break. Imagine the surprise if one of the implementations didn't break. That's what LSP is all about.
>
> a) benefits of loose coupling outweight the risks of not complying to LSP
>
>
>
ehh?
>
> b) compared to inheritance, chances that a class ( implementing an interface ) will not adher to LSP are much smaller
>
>
>
ehh?
You might want to read my SOLID article to understand the principle better: <http://blog.gauffin.org/2012/05/solid-principles-with-real-world-examples/>
**Update**
>
> To elaborate - with inheritance virtual methods may consume private members, to which subclasses overriding these virtual methods don't have access to.
>
>
>
Yes. That's good. members (fields) should always be protected ( = declared as private). Only the class that defined them really know what their values should be.
>
> Also, derived class inherits the context from parent and as such can be broken by future changes to parent class etc.
>
>
>
That's a violation of Open/closed principle. i.e. the class contract is changed by changing the behavior. Classes should be extended and not modified. Sure, it's not possible all the time, but changes should not make the class behave differently (other than bugfixes).
>
> Thus I feel it's more difficult to make subclass honour the contract than it is to make class implementing an interface honour it
>
>
>
There is a common reason to why extension through inheritance is hard. And that's because the relationship isn't a true `is-a` relationship, but that the developer just want to take advantage of the base class functionality.
That's wrong. Better to use composition then. | Ad 1): Yes. However, it is hard to make interfaces enforce the contracts, and they really should.
Ad 2): Programming against an interface is a trade-off. As you point out interfaces encourages violation of LSP for all interfaces with a non-trivial contract.
I believe these are the answers to your questions, or at least my recognition that tese are unanswered questions that challenge the encouraged use of interfaces.
I use interfaces all the time (in C#) because I like doing TDD. I then just hope that my mocks and corresponding implementations don't violate LSP, because when they do my test suite is no longer sound (it claims something to work, but it doesn't).
Occasionally, I'll make an abstract base class instead of an interface. The abstract base class simply enforces the contract, and delegates to virtual protected methods that are supposed to define the actual implementation or being mocked during unit testing. This has proven to be useful in some applications, where errors in the unit tests themselves are discovered.
But then we run into the missing support for multiple inheritance in C#, and we are stuck with the interfaces anyway (or simply more classes, you can hide behind the SRP if you choose this approach) |
12,252,363 | 1) Does LSP also apply to interfaces, meaning that we should be able to use a class implementing a specific interface and still get the expected behavior?
2) If that is indeed the case, then why is programming to an interface considered a good thing ( BTW- I know that programming to an interface increases loose coupling ), if one of the main reasons against using inheritance is due to risk of not complying to LSP? Perhaps because:
a) benefits of loose coupling outweight the risks of not complying to LSP
b) compared to inheritance, chances that a class ( implementing an interface ) will not adher to LSP are much smaller
thank you | 2012/09/03 | [
"https://Stackoverflow.com/questions/12252363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483278/"
] | I'm comparing/contrasting my code practice with LSP at the moment. I think it must be all to do with expectation and deciding how to define what should be expected. I'm not convinced that substitution always means the same thing. For instance, if I defined
```
interface ICalculation
{
double Calculate(double A, double B);
}
```
with the intention of defining `class Add : ICalculation`, `class Subtract : ICalculation`, `class Multiply : ICalculation` and `class Divide : ICalculation`, I believe that those classes should perform the respective `Calculation(A, B)`, however, I do not believe they should all pass the same unit tests. I like to use interfaces for extensibility, where each extension has a different function. In the case of a car braking, I would give classes the interface IBrakable and do this:
```
var myBrakableCar = MyCar as IBrakable;
if(myBrakableCar != null)
{
myBrakableCar.Brake();
}
```
I believe that classes should be predictable in their use, but also useful. Useful comes top.
I'm just going to create a new concept - "Respective Substition": it does what it says on the tin. | Ad 1): Yes. However, it is hard to make interfaces enforce the contracts, and they really should.
Ad 2): Programming against an interface is a trade-off. As you point out interfaces encourages violation of LSP for all interfaces with a non-trivial contract.
I believe these are the answers to your questions, or at least my recognition that tese are unanswered questions that challenge the encouraged use of interfaces.
I use interfaces all the time (in C#) because I like doing TDD. I then just hope that my mocks and corresponding implementations don't violate LSP, because when they do my test suite is no longer sound (it claims something to work, but it doesn't).
Occasionally, I'll make an abstract base class instead of an interface. The abstract base class simply enforces the contract, and delegates to virtual protected methods that are supposed to define the actual implementation or being mocked during unit testing. This has proven to be useful in some applications, where errors in the unit tests themselves are discovered.
But then we run into the missing support for multiple inheritance in C#, and we are stuck with the interfaces anyway (or simply more classes, you can hide behind the SRP if you choose this approach) |
15,442,919 | I've been reading up on SimpleDB and one downfall (for me) is the 1kb max per attribute limit. I do a lot of RSS feed processing and I was hoping to store feed data in SimpleDB (articles) and from what I've read the best way to do this is to shard the article across several attributes. The typical article is < 30kb of plain text.
I'm currently storing article data in DynamoDB (gzip compressed) without any issues, but the cost is fairly high. Was hoping to migrate to SimpleDB for cheaper storage with still fast retrievals. I do archive a json copy of all rss articles on S3 as well (many years of mysql headaches make me wary of db's).
Does anyone know to shard a string into < 1kb pieces? I'm assuming an identifier would need to be appended to each chunk for order of reassembly.
Any thoughts would be much appreciated! | 2013/03/15 | [
"https://Stackoverflow.com/questions/15442919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/799575/"
] | Your code doesn't do what you think it does.
```
ArrayList[][] gridList = new ArrayList[300][150];
```
This first line allocates an `array` of `array` of `ArrayList`.
```
ArrayList al = this.gridList[a][b];
```
This second line retrieves the `ArrayList` at offset `b` in the `array` at offset `a` in the `array` gridList. *You should be aware that your code doesn't initialize either arrays*.
The equivalent type in C++ could be:
```
#include <vector>
#include <array>
std::array< std::array< std::vector<T>, 150>, 300> gridList;
```
where `T` is the type of the element stored in the vectors. Note that Java prior to generics only allowed to define ArrayList without specifying the element type, which is pretty much what your code does. In C++, this parameter is mandatory. The above variable definition will instantiate it for the current scope. you will need to use a `new` statement for a dynamic value (as in Java), and probably wrap it with a smart pointer.
To access an element of the grid, you can use the `[]` operator:
```
vector v = gridList[a][b];
```
Beware that this will trigger a full copy of the `vector` content in the grid at position < a,b > into `v`. As suggested, a more efficient way would be to write:
```
auto const &al = gridList[a][b];
```
Again, the memory model used by Java is very dynamic, so if you want code closer in behaviour to the Java version, you would probably have something like:
```
#include<memory>
typedef std::vector<int> i_vector;
typedef std::shared_ptr<i_vector> i_vector_ptr;
typedef std::array< std::array< i_vector_ptr>, 150>, 300> vector_grid;
typedef std::shared_ptr<vector_grid> vector_grid_ptr;
vector_grid_ptr gridList;
i_vector_ptr al = (*gridList)[a][b];
```
with type `T` being `int`, and each component of the grid type clearly defined. You still have to allocate the grid and each element (ie. `i_vector` here). | Something like this may work (if you need container class):
```
struct Item
{ ...
};
typedef std::vector<Item> ArrayList;
// Single row.
struct ArrayListVector : public std::vector<ArrayList>
{
ArrayListVector() { resize(150); }
};
// Whole matrix
struct ArrayListMatrix : public std::vector<ArrayListVector>
{
ArrayListMatrix() { resize(300); }
};
...
ArrayListMatrix gridList; //< yes, it is 300 x 150
ArrayList &a = gridList[a][b]; //< or, you can make a copy
gridList[b][a] = a; //< assign an entry
```
Or do you need templates?
However there is a simple option, that doesn't need templates, classes, etc:
```
ArrayList array[300][150]; //< array is allocated (on stack, or statically).
``` |
15,442,919 | I've been reading up on SimpleDB and one downfall (for me) is the 1kb max per attribute limit. I do a lot of RSS feed processing and I was hoping to store feed data in SimpleDB (articles) and from what I've read the best way to do this is to shard the article across several attributes. The typical article is < 30kb of plain text.
I'm currently storing article data in DynamoDB (gzip compressed) without any issues, but the cost is fairly high. Was hoping to migrate to SimpleDB for cheaper storage with still fast retrievals. I do archive a json copy of all rss articles on S3 as well (many years of mysql headaches make me wary of db's).
Does anyone know to shard a string into < 1kb pieces? I'm assuming an identifier would need to be appended to each chunk for order of reassembly.
Any thoughts would be much appreciated! | 2013/03/15 | [
"https://Stackoverflow.com/questions/15442919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/799575/"
] | Your code doesn't do what you think it does.
```
ArrayList[][] gridList = new ArrayList[300][150];
```
This first line allocates an `array` of `array` of `ArrayList`.
```
ArrayList al = this.gridList[a][b];
```
This second line retrieves the `ArrayList` at offset `b` in the `array` at offset `a` in the `array` gridList. *You should be aware that your code doesn't initialize either arrays*.
The equivalent type in C++ could be:
```
#include <vector>
#include <array>
std::array< std::array< std::vector<T>, 150>, 300> gridList;
```
where `T` is the type of the element stored in the vectors. Note that Java prior to generics only allowed to define ArrayList without specifying the element type, which is pretty much what your code does. In C++, this parameter is mandatory. The above variable definition will instantiate it for the current scope. you will need to use a `new` statement for a dynamic value (as in Java), and probably wrap it with a smart pointer.
To access an element of the grid, you can use the `[]` operator:
```
vector v = gridList[a][b];
```
Beware that this will trigger a full copy of the `vector` content in the grid at position < a,b > into `v`. As suggested, a more efficient way would be to write:
```
auto const &al = gridList[a][b];
```
Again, the memory model used by Java is very dynamic, so if you want code closer in behaviour to the Java version, you would probably have something like:
```
#include<memory>
typedef std::vector<int> i_vector;
typedef std::shared_ptr<i_vector> i_vector_ptr;
typedef std::array< std::array< i_vector_ptr>, 150>, 300> vector_grid;
typedef std::shared_ptr<vector_grid> vector_grid_ptr;
vector_grid_ptr gridList;
i_vector_ptr al = (*gridList)[a][b];
```
with type `T` being `int`, and each component of the grid type clearly defined. You still have to allocate the grid and each element (ie. `i_vector` here). | If your ArrayList is holding something of type 'Foo', then:
```
std::vector<Foo*> gridList[300][150];
std::vector al = this->gridList[a][b];
``` |
56,019,584 | I have a big file with many lines starting like this:
```
22 16052167 rs375684679 A AAAAC . PASS DR2=0.02;AF=0.4728;IMP GT:DS
```
In these lines, `DR2`values range from 0 to 1 and I would like to extract those lines that contains`DR2`values higher than 0.8.
I've tried both `sed` or `awk` solutions, but neither seems to work... I've tried the following:
```
grep "DR2=[0-1]\.[8-9]*" myfile
``` | 2019/05/07 | [
"https://Stackoverflow.com/questions/56019584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9717188/"
] | This matches lines with a value greater than *or equal to* 0.8. If you insist on strictly greater than, then I'll have to add some complexity to prevent 0.8 from matching.
```
grep 'DR2=\(1\|0\.[89]\)' myfile
```
The trick is that you need two separate subpatterns: one to match 1 and greater, one to match 0.8 and greater. | * **grep:** `grep -E 'DR2=\([1-9]\|0[.][89]\)'`
* **sed:** `sed -n '/\([1-9]\|0[.][89]\)/p'`
* **awk:** `awk '/\([1-9]\|0[.][89]\)/'`
These 3 solutions are all based on a single regular expression and all do the same (see [Ruud HelderMan's solution](https://stackoverflow.com/a/56019874/8344060))
With awk, however, you could do an artithmetic check if your limits are a bit more tricky. Let's say, I want the value of DR2 to be between 0.53 and 1.39.
```
awk '! match($0,/DR2=/) { next }
{ val = substr($0,RSTART+RLENGTH)+0 }
( 0.53 < val) && ( val < 1.39 )'
``` |
56,019,584 | I have a big file with many lines starting like this:
```
22 16052167 rs375684679 A AAAAC . PASS DR2=0.02;AF=0.4728;IMP GT:DS
```
In these lines, `DR2`values range from 0 to 1 and I would like to extract those lines that contains`DR2`values higher than 0.8.
I've tried both `sed` or `awk` solutions, but neither seems to work... I've tried the following:
```
grep "DR2=[0-1]\.[8-9]*" myfile
``` | 2019/05/07 | [
"https://Stackoverflow.com/questions/56019584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9717188/"
] | This matches lines with a value greater than *or equal to* 0.8. If you insist on strictly greater than, then I'll have to add some complexity to prevent 0.8 from matching.
```
grep 'DR2=\(1\|0\.[89]\)' myfile
```
The trick is that you need two separate subpatterns: one to match 1 and greater, one to match 0.8 and greater. | Whenever you have tag=value pairs in your data I find it best to first create an array of those pairings (`f[]`) below and then you can just access the values by their tags. You didn't provide any input of 0.8 to test against so using the data you did provide:
```
$ awk '{split($8,t,/[=;]/); for (i=1; i in t; i+=2) f[t[i]]=t[i+1]} f["DR2"] > 0.01' file
22 16052167 rs375684679 A AAAAC . PASS DR2=0.02;AF=0.4728;IMP GT:DS
```
or using variables for the tag and value:
```
$ awk -v tag='DR2' -v val='0.8' '{split($8,t,/[=;]/); for (i=1; i in t; i+=2) f[t[i]]=t[i+1]} f[tag] > val' file
$
$ awk -v tag='DR2' -v val='0.01' '{split($8,t,/[=;]/); for (i=1; i in t; i+=2) f[t[i]]=t[i+1]} f[tag] > val' file
22 16052167 rs375684679 A AAAAC . PASS DR2=0.02;AF=0.4728;IMP GT:DS
$
$ awk -v tag='AF' -v val='0.4' '{split($8,t,/[=;]/); for (i=1; i in t; i+=2) f[t[i]]=t[i+1]} f[tag] > val' file
22 16052167 rs375684679 A AAAAC . PASS DR2=0.02;AF=0.4728;IMP GT:DS
$
$ awk -v tag='AF' -v val='0.5' '{split($8,t,/[=;]/); for (i=1; i in t; i+=2) f[t[i]]=t[i+1]} f[tag] > val' file
$
```
or using compound conditions:
```
$ awk '{split($8,t,/[=;]/); for (i=1; i in t; i+=2) f[t[i]]=t[i+1]}
(f["AF"] > 0.4) && (f["AF"] < 0.5) && (f["DR2"] >= 0.02)
' file
22 16052167 rs375684679 A AAAAC . PASS DR2=0.02;AF=0.4728;IMP GT:DS
```
The point is whatever comparisons you want to do with the values of those tags is trivial and you don't need to write more code to isolate and save those tags and their values. |
2,508,720 | I'm trying to create JUnit tests for my JPA DAO classes, using Spring 2.5.6 and JUnit 4.8.1.
My test case looks like this:
```
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:config/jpaDaoTestsConfig.xml"} )
public class MenuItem_Junit4_JPATest extends BaseJPATestCase {
private ApplicationContext context;
private InputStream dataInputStream;
private IDataSet dataSet;
@Resource
private IMenuItemDao menuItemDao;
@Test
public void testFindAll() throws Exception {
assertEquals(272, menuItemDao.findAll().size());
}
... Other test methods ommitted for brevity ...
}
```
I have the following in my jpaDaoTestsConfig.xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- uses the persistence unit defined in the META-INF/persistence.xml JPA configuration file -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="CONOPS_PU" />
</bean>
<bean id="groupDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.GroupDao" lazy-init="true" />
<bean id="permissionDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.PermissionDao" lazy-init="true" />
<bean id="applicationUserDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.ApplicationUserDao" lazy-init="true" />
<bean id="conopsUserDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.ConopsUserDao" lazy-init="true" />
<bean id="menuItemDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.MenuItemDao" lazy-init="true" />
<!-- enables interpretation of the @Required annotation to ensure that dependency injection actually occures -->
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<!-- enables interpretation of the @PersistenceUnit/@PersistenceContext annotations providing convenient
access to EntityManagerFactory/EntityManager -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<!-- transaction manager for use with a single JPA EntityManagerFactory for transactional data access
to a single datasource -->
<bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- enables interpretation of the @Transactional annotation for declerative transaction managment
using the specified JpaTransactionManager -->
<tx:annotation-driven transaction-manager="jpaTransactionManager" proxy-target-class="false"/>
</beans>
```
Now, when I try to run this, I get the following:
```
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@fa60fa6] to prepare test instance [null(mil.navy.ndms.conops.common.dao.impl.MenuItem_Junit4_JPATest)]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mil.navy.ndms.conops.common.dao.impl.MenuItem_Junit4_JPATest': Injection of resource fields failed; nested exception is java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(CommonAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:255)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:93)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:130)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:54)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:52)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.checkResourceType(InjectionMetadata.java:159)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.(PersistenceAnnotationBeanPostProcessor.java:559)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$1.doWith(PersistenceAnnotationBeanPostProcessor.java:359)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:492)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:469)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:351)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:296)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:745)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:448)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(AccessController.java:219)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:168)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:537)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(CommonAnnotationBeanPostProcessor.java:289)
... 18 more
```
It seems to be telling me that its attempting to store an EntityManager object into an EntityManagerFactory field, but I don't understand how or why. My DAO classes accept both an EntityManager and EntityManagerFactory via the @PersistenceContext attribute, and they work find if I load them up and run them without the @ContextConfiguration attribute (i.e. if I just use the XmlApplcationContext to load the DAO and the EntityManagerFactory directly in setUp ()).
Any insights would be appreciated. | 2010/03/24 | [
"https://Stackoverflow.com/questions/2508720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136449/"
] | These are the correct combinations of annotation + interface:
```
@PersistenceContext
private EntityManager entityManager;
@PersistenceUnit
private EntityManagerFactory entityManagerFactory;
```
But when using spring's transaction and entity manager support, you don't need the `EntityManagerFactory` at all.
The reason why you don't need `EntityManagerFactory` is because the creation of the `EntityManager` is responsibility of the transaction manager. Here's what happens in short:
* the transaction manager is triggered before your methods
* the transaction manager gets the `EntityManagerFactory` (it is injected in it), creates a new `EntityManager`, *sets in in a `ThreadLocal`*, and starts a new transaction.
* then it delegates to the service method
* whenever `@PersistenceContext` is encountered, a proxy is injected (in your Dao), which, whenever accessed, gets the current `EntityManager` which has been set in the `ThreadLocal` | I had to do the below combination, apart from adding spring-aspects jar to the project properties->Aspect Path and enabling spring aspects in sts. Ofcourse in my application context config file i defined the Entitymanagerfactory.
@ContextConfiguration(locations = { "/META-INF/spring/applicationContext-domain.xml" })
public class ReaderTest extends AbstractJUnit4SpringContextTests {
@PersistenceContext
private EntityManager entityManager; |
2,508,720 | I'm trying to create JUnit tests for my JPA DAO classes, using Spring 2.5.6 and JUnit 4.8.1.
My test case looks like this:
```
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:config/jpaDaoTestsConfig.xml"} )
public class MenuItem_Junit4_JPATest extends BaseJPATestCase {
private ApplicationContext context;
private InputStream dataInputStream;
private IDataSet dataSet;
@Resource
private IMenuItemDao menuItemDao;
@Test
public void testFindAll() throws Exception {
assertEquals(272, menuItemDao.findAll().size());
}
... Other test methods ommitted for brevity ...
}
```
I have the following in my jpaDaoTestsConfig.xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- uses the persistence unit defined in the META-INF/persistence.xml JPA configuration file -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="CONOPS_PU" />
</bean>
<bean id="groupDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.GroupDao" lazy-init="true" />
<bean id="permissionDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.PermissionDao" lazy-init="true" />
<bean id="applicationUserDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.ApplicationUserDao" lazy-init="true" />
<bean id="conopsUserDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.ConopsUserDao" lazy-init="true" />
<bean id="menuItemDao" class="mil.navy.ndms.conops.common.dao.impl.jpa.MenuItemDao" lazy-init="true" />
<!-- enables interpretation of the @Required annotation to ensure that dependency injection actually occures -->
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<!-- enables interpretation of the @PersistenceUnit/@PersistenceContext annotations providing convenient
access to EntityManagerFactory/EntityManager -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<!-- transaction manager for use with a single JPA EntityManagerFactory for transactional data access
to a single datasource -->
<bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- enables interpretation of the @Transactional annotation for declerative transaction managment
using the specified JpaTransactionManager -->
<tx:annotation-driven transaction-manager="jpaTransactionManager" proxy-target-class="false"/>
</beans>
```
Now, when I try to run this, I get the following:
```
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@fa60fa6] to prepare test instance [null(mil.navy.ndms.conops.common.dao.impl.MenuItem_Junit4_JPATest)]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mil.navy.ndms.conops.common.dao.impl.MenuItem_Junit4_JPATest': Injection of resource fields failed; nested exception is java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager]
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(CommonAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:255)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:93)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:130)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:61)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:54)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:52)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: java.lang.IllegalStateException: Specified field type [interface javax.persistence.EntityManagerFactory] is incompatible with resource type [javax.persistence.EntityManager]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.checkResourceType(InjectionMetadata.java:159)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.(PersistenceAnnotationBeanPostProcessor.java:559)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$1.doWith(PersistenceAnnotationBeanPostProcessor.java:359)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:492)
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:469)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:351)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:296)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:745)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:448)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(AccessController.java:219)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:168)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:537)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation(CommonAnnotationBeanPostProcessor.java:289)
... 18 more
```
It seems to be telling me that its attempting to store an EntityManager object into an EntityManagerFactory field, but I don't understand how or why. My DAO classes accept both an EntityManager and EntityManagerFactory via the @PersistenceContext attribute, and they work find if I load them up and run them without the @ContextConfiguration attribute (i.e. if I just use the XmlApplcationContext to load the DAO and the EntityManagerFactory directly in setUp ()).
Any insights would be appreciated. | 2010/03/24 | [
"https://Stackoverflow.com/questions/2508720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136449/"
] | These are the correct combinations of annotation + interface:
```
@PersistenceContext
private EntityManager entityManager;
@PersistenceUnit
private EntityManagerFactory entityManagerFactory;
```
But when using spring's transaction and entity manager support, you don't need the `EntityManagerFactory` at all.
The reason why you don't need `EntityManagerFactory` is because the creation of the `EntityManager` is responsibility of the transaction manager. Here's what happens in short:
* the transaction manager is triggered before your methods
* the transaction manager gets the `EntityManagerFactory` (it is injected in it), creates a new `EntityManager`, *sets in in a `ThreadLocal`*, and starts a new transaction.
* then it delegates to the service method
* whenever `@PersistenceContext` is encountered, a proxy is injected (in your Dao), which, whenever accessed, gets the current `EntityManager` which has been set in the `ThreadLocal` | I too have same problem, When I added java-persistence api problem got resolved.
```
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
``` |
11,053,878 | In a Rails 3.2 app, when I call a non-html format on a class - e.g. json, csv, etc - I get an error
```
Template is missing
Missing partial /path/to/template with {:locale=>[:en], :formats=>[:json].....
```
The template is called from a method in the controller.
How can I create a conditional statement in the controller that does something like:
```
if format is html
my_method_that_causes_the_error
end
```
Thanks | 2012/06/15 | [
"https://Stackoverflow.com/questions/11053878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716294/"
] | In your controller
```
def index # or other method
...
respond_to do |format|
format.html # render index.html.erb
format.json { render json: ...} # one-line block
format.xml do
# multi-line block
end
end
end
``` | Is maybe [this](http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to) what your are looking for? |
11,053,878 | In a Rails 3.2 app, when I call a non-html format on a class - e.g. json, csv, etc - I get an error
```
Template is missing
Missing partial /path/to/template with {:locale=>[:en], :formats=>[:json].....
```
The template is called from a method in the controller.
How can I create a conditional statement in the controller that does something like:
```
if format is html
my_method_that_causes_the_error
end
```
Thanks | 2012/06/15 | [
"https://Stackoverflow.com/questions/11053878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716294/"
] | ```
respond_to do |format|
format.html { my_method_that_causes_the_error }
format.csv { render :something }
end
``` | Is maybe [this](http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to) what your are looking for? |
11,053,878 | In a Rails 3.2 app, when I call a non-html format on a class - e.g. json, csv, etc - I get an error
```
Template is missing
Missing partial /path/to/template with {:locale=>[:en], :formats=>[:json].....
```
The template is called from a method in the controller.
How can I create a conditional statement in the controller that does something like:
```
if format is html
my_method_that_causes_the_error
end
```
Thanks | 2012/06/15 | [
"https://Stackoverflow.com/questions/11053878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716294/"
] | ```
respond_to do |format|
format.html { my_method_that_causes_the_error }
format.csv { render :something }
end
``` | In your controller
```
def index # or other method
...
respond_to do |format|
format.html # render index.html.erb
format.json { render json: ...} # one-line block
format.xml do
# multi-line block
end
end
end
``` |
14,849,026 | I'm trying to pass some values through onclick which to me is so much faster. But I need to use some kind of "live" clicking and I was looking into .on() or .delegate(). However, if I do any of those, passing those values within `followme()` seems a little harder to get. Is there some kind of method that I'm not seeing?
```
<div class='btn btn-mini follow-btn'
data-status='follow'
onclick="followme(<?php echo $_SESSION['user_auth'].','.$randId;?>)">
Follow
</div>
function followme(iduser_follower,iduser_following)
{
$.ajax({
url: '../follow.php',
type: 'post',
data: 'iduser_follower='+iduser_follower+'&iduser_following='+iduser_following+'&unfollow=1',
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text('Follow');
}
});
}
```
As you can see, its easier to just pass values from PHP to jQuery... Is there another way? | 2013/02/13 | [
"https://Stackoverflow.com/questions/14849026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/659751/"
] | You can assign more data values, and you know what use is logged in, all you need is to pass who to follow:
```
<div class='btn btn-mini follow-btn'
data-status='follow'
data-who='<?php echo $randId; ?>'
id='followBTN'>
Follow
</div>
<script>
$('#followBTN').on('click', function(){
$.ajax({
url: '../follow.php',
type: 'post',
data: {
iduser_following: $(this).attr('data-who')
},
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text(data.text);
}
});
});
</script>
```
You can process `$_SESSION['user_auth']` and the status directly from PHP, there is no need for you to pass them in jQuery. Make sure `document` is ready when you insert `on` click event. | just use the jquery 'on' event. Attach a new attribute called data-session to the div and then retrieve it using .attr method. You have the example bellow to show you an alert with the data, you just have to substitute it with your code
```
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '#follow-me-button', function(){
alert($(this).attr('data-session'));
})
})
</script>
</head>
<body>
<div id="follow-me-button" class='btn btn-mini follow-btn' data-status='follow' data-session ="MY-SESSION-DATA-FROM-PHP">
Follow
</div>
</body>
</html>
``` |
26,821,797 | Please advise me why I can't create this example in my home html file?
Here is an example from the [site](http://jsfiddle.net/eM2Mg/) and my html file:
```
<head>
<script src="http://dygraphs.com/dygraph-dev.js"></script>
<script>
g = new Dygraph(document.getElementById("graph"),
"X,Y,Z\n" +
"1,0,3\n" +
"2,2,6\n" +
"8,14,3\n",
{
legend: 'always',
animatedZooms: true,
title: 'dygraphs chart template'
});
</script>
<style>
.dygraph-title {
color: gray;
}
</style>
</head>
<body>
<div id="graph"></div>
</body>
```
what am I doing wrong? | 2014/11/08 | [
"https://Stackoverflow.com/questions/26821797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] | javascript script must be after div or you need to use document ready to load body first and then script
```
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://dygraphs.com/dygraph-dev.js"></script>
<style>
.dygraph-title {
color: gray;
}
</style>
</head>
<body>
<div id="graph"></div>
<script>
g = new Dygraph(document.getElementById("graph"),
"X,Y,Z\n" +
"1,0,3\n" +
"2,2,6\n" +
"8,14,3\n",
{
legend: 'always',
animatedZooms: true,
title: 'dygraphs chart template'
});
</script>
</body>
</html>
``` | One main issue is that your code is running too early. You are trying to operate on DOM elements before they have even been loaded. Code running in the `<head>` section cannot yet access elements in the DOM because it has not yet been loaded.
You can move your second `<script>` tag to right before the `</body>` tag and that problem should go away. |
26,821,797 | Please advise me why I can't create this example in my home html file?
Here is an example from the [site](http://jsfiddle.net/eM2Mg/) and my html file:
```
<head>
<script src="http://dygraphs.com/dygraph-dev.js"></script>
<script>
g = new Dygraph(document.getElementById("graph"),
"X,Y,Z\n" +
"1,0,3\n" +
"2,2,6\n" +
"8,14,3\n",
{
legend: 'always',
animatedZooms: true,
title: 'dygraphs chart template'
});
</script>
<style>
.dygraph-title {
color: gray;
}
</style>
</head>
<body>
<div id="graph"></div>
</body>
```
what am I doing wrong? | 2014/11/08 | [
"https://Stackoverflow.com/questions/26821797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] | javascript script must be after div or you need to use document ready to load body first and then script
```
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://dygraphs.com/dygraph-dev.js"></script>
<style>
.dygraph-title {
color: gray;
}
</style>
</head>
<body>
<div id="graph"></div>
<script>
g = new Dygraph(document.getElementById("graph"),
"X,Y,Z\n" +
"1,0,3\n" +
"2,2,6\n" +
"8,14,3\n",
{
legend: 'always',
animatedZooms: true,
title: 'dygraphs chart template'
});
</script>
</body>
</html>
``` | Because your `getElementById` call will return null because the element doesn't exist yet when you run the Javascript code.
Put the code in the load event so that it runs after the page has been parsed:
```
window.onload = function(){
g = new Dygraph(document.getElementById("graph"),
...
};
``` |
26,821,797 | Please advise me why I can't create this example in my home html file?
Here is an example from the [site](http://jsfiddle.net/eM2Mg/) and my html file:
```
<head>
<script src="http://dygraphs.com/dygraph-dev.js"></script>
<script>
g = new Dygraph(document.getElementById("graph"),
"X,Y,Z\n" +
"1,0,3\n" +
"2,2,6\n" +
"8,14,3\n",
{
legend: 'always',
animatedZooms: true,
title: 'dygraphs chart template'
});
</script>
<style>
.dygraph-title {
color: gray;
}
</style>
</head>
<body>
<div id="graph"></div>
</body>
```
what am I doing wrong? | 2014/11/08 | [
"https://Stackoverflow.com/questions/26821797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] | Because your `getElementById` call will return null because the element doesn't exist yet when you run the Javascript code.
Put the code in the load event so that it runs after the page has been parsed:
```
window.onload = function(){
g = new Dygraph(document.getElementById("graph"),
...
};
``` | One main issue is that your code is running too early. You are trying to operate on DOM elements before they have even been loaded. Code running in the `<head>` section cannot yet access elements in the DOM because it has not yet been loaded.
You can move your second `<script>` tag to right before the `</body>` tag and that problem should go away. |
17,955 | Just like it says in the title, how can I store blocks of cheese for max shelf life? I will be making a grilled cheese sandwich and shredding 3 varieties of cheese (cheddar, swiss, parm(?)) and I am afraid that I won't be able to use three whole blocks on one sandwich. | 2011/09/23 | [
"https://cooking.stackexchange.com/questions/17955",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/3818/"
] | Hard, aged cheeses like cheddar and Parmesan are fine to freeze, particularly if you're going to be melting them when you get around to using them anyway. Freezing causes ice particles to break up the molecules of the cheese, and when they thaw, they leave holes in what was (prior to freezing) a pretty smooth cheese. So you might notice if you freeze blocks of cheese, they are more crumbly when you unfreeze them than they were when you bought them. The cheeses you're working with should be fine if stored properly, but softer / creamier cheeses (brie, harvarti, etc.) might become somewhat unpleasant if you freeze them.
As far as storage is concerned, you can actually do one of two things:
1. Grate the cheese before you freeze it. All you need to do for this method is grate your cheese and put it in a ziploc freezer bag (thicker than a regular zip-top bag). Just make sure to squeeze the air out before sealing, and seal it well.
2. Freeze the cheese in blocks. Wrap them in plastic wrap and then put then in a ziploc bag, and you should be all set; it'll keep for 4-6 months. ([source](http://food.unl.edu/web/fnh/food-facts#canufreeze))
No matter which method you use, you may notice a slight change in texture. Make sure you thaw the cheese before using it. (Though I've put frozen shredded mozzarella on pizza and frozen shredded Mexican cheese blend - a blend of cheddar, monterey jack, queso blanco and asadero - on tacos and not had any trouble.) | The best way to keep cheese in the fridge ... and the way I've made semisoft cheeses like cheddar last 6-10 weeks, sometimes more:
1. Wrap the cheese in butcher paper, or baking parchment if you can't get butcher paper.
2. Enclose the wrapped cheese in a plastic grocery bag or plastic wrap.
3. Each time you slice off some of the cheese, change the paper.
The paper keeps the cheese dry, and the plastic keeps it moist. So the cheese doesn't dessicate, but doesn't get moldy either. Works a charm. |
17,955 | Just like it says in the title, how can I store blocks of cheese for max shelf life? I will be making a grilled cheese sandwich and shredding 3 varieties of cheese (cheddar, swiss, parm(?)) and I am afraid that I won't be able to use three whole blocks on one sandwich. | 2011/09/23 | [
"https://cooking.stackexchange.com/questions/17955",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/3818/"
] | Hard, aged cheeses like cheddar and Parmesan are fine to freeze, particularly if you're going to be melting them when you get around to using them anyway. Freezing causes ice particles to break up the molecules of the cheese, and when they thaw, they leave holes in what was (prior to freezing) a pretty smooth cheese. So you might notice if you freeze blocks of cheese, they are more crumbly when you unfreeze them than they were when you bought them. The cheeses you're working with should be fine if stored properly, but softer / creamier cheeses (brie, harvarti, etc.) might become somewhat unpleasant if you freeze them.
As far as storage is concerned, you can actually do one of two things:
1. Grate the cheese before you freeze it. All you need to do for this method is grate your cheese and put it in a ziploc freezer bag (thicker than a regular zip-top bag). Just make sure to squeeze the air out before sealing, and seal it well.
2. Freeze the cheese in blocks. Wrap them in plastic wrap and then put then in a ziploc bag, and you should be all set; it'll keep for 4-6 months. ([source](http://food.unl.edu/web/fnh/food-facts#canufreeze))
No matter which method you use, you may notice a slight change in texture. Make sure you thaw the cheese before using it. (Though I've put frozen shredded mozzarella on pizza and frozen shredded Mexican cheese blend - a blend of cheddar, monterey jack, queso blanco and asadero - on tacos and not had any trouble.) | I've had good luck simply storing the cheese tightly wrapped in plastic wrap in the refrigerator. If you use a good quality wrap material and wrap it tightly, the cheese will stay dry and also not lose moisture.
In the past I tried using ziploc bags, evacuating air before sealing, but the simple plastic wrap approach works better. I can keep 6-7 types of cheese fresh during the time it takes my family of four to eat it... up to several months depending on cheese type. |
17,955 | Just like it says in the title, how can I store blocks of cheese for max shelf life? I will be making a grilled cheese sandwich and shredding 3 varieties of cheese (cheddar, swiss, parm(?)) and I am afraid that I won't be able to use three whole blocks on one sandwich. | 2011/09/23 | [
"https://cooking.stackexchange.com/questions/17955",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/3818/"
] | The best way to keep cheese in the fridge ... and the way I've made semisoft cheeses like cheddar last 6-10 weeks, sometimes more:
1. Wrap the cheese in butcher paper, or baking parchment if you can't get butcher paper.
2. Enclose the wrapped cheese in a plastic grocery bag or plastic wrap.
3. Each time you slice off some of the cheese, change the paper.
The paper keeps the cheese dry, and the plastic keeps it moist. So the cheese doesn't dessicate, but doesn't get moldy either. Works a charm. | I've had good luck simply storing the cheese tightly wrapped in plastic wrap in the refrigerator. If you use a good quality wrap material and wrap it tightly, the cheese will stay dry and also not lose moisture.
In the past I tried using ziploc bags, evacuating air before sealing, but the simple plastic wrap approach works better. I can keep 6-7 types of cheese fresh during the time it takes my family of four to eat it... up to several months depending on cheese type. |
58,720,960 | We can use @Input as passing input props or data. We also can use `<ng-content>` to dump a load of html into the children component. Is there any way to pass html as Input. Like @Input html1, @Input html2, and use them in the child class component?
Suppose I have this html in child class:
```
<div class='wrapper'>
<div class="content1 exclusive-css-defined-to-this-component">
<div>{$content1}</div>
</div>
<div class="content2 exclusive-css-defined-to-this-component-2">
<div>{$content2}</div>
</div>
</div>
```
And I want to pass $content1 & $content2 as input. | 2019/11/05 | [
"https://Stackoverflow.com/questions/58720960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7055636/"
] | We can use **innerHTML** to achieve this
Sample example demonstrating this,
parent.component.ts,
```
export class ParentComponent {
htmlOneAsString = `
<div>Welcome Text Header</div>
`;
htmlTwoAsString = `
<div>Welcome Text Content</div>
`;
htmlAsString = `
<div><div>${this.htmlOneAsString}</div><div>${this.htmlTwoAsString}</div></div>
`;
}
```
parent.component.html,
```
<child [innerHTML]="htmlAsString"></child>
```
child.component.ts,
```
@Component({
selector: 'child'
})
export class ChildComponent {
@Input() htmlAsString: string;
}
```
child.component.html,
```
<div>{{htmlAsString}}</div>
``` | You can place your html in a string like
```
htmlStr = "<strong>This is an example</strong>";
```
and pass it through to a service:
```
this.whateverService.setHtml(this.htmlStr);
```
then in the receiving component:
```
import { WhateverService } from 'src/app/shared/service/whatever.service';
export class ReceivingComponentThing implements OnInit {
htmlExample = '';
constructor(private whateverService: WhateverService) {}
}
ngOnInit() {
// have a getter/setter in service however you like
this.htmlExample = this.whateverService.getHtmlExample();
}
```
in your template:
```
<div [innerHtml]="htmlExample"><div>
``` |
58,720,960 | We can use @Input as passing input props or data. We also can use `<ng-content>` to dump a load of html into the children component. Is there any way to pass html as Input. Like @Input html1, @Input html2, and use them in the child class component?
Suppose I have this html in child class:
```
<div class='wrapper'>
<div class="content1 exclusive-css-defined-to-this-component">
<div>{$content1}</div>
</div>
<div class="content2 exclusive-css-defined-to-this-component-2">
<div>{$content2}</div>
</div>
</div>
```
And I want to pass $content1 & $content2 as input. | 2019/11/05 | [
"https://Stackoverflow.com/questions/58720960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7055636/"
] | I have found the solution, this can be done by:
```
<div class='wrapper'>
<div class="exclusive-css-defined-to-this-component">
<div><ng-content select="[content1]"></ng-content></div>
</div>
<div class="exclusive-css-defined-to-this-component-2">
<div><ng-content select="[content2]"></ng-content></div>
</div>
</div>
```
And we can use the component like:
```
<wrapper>
<div content>Any thing you want to put in content1</div>
<div content2>Any thing you want to put in content2</div>
</wrapper>
``` | You can place your html in a string like
```
htmlStr = "<strong>This is an example</strong>";
```
and pass it through to a service:
```
this.whateverService.setHtml(this.htmlStr);
```
then in the receiving component:
```
import { WhateverService } from 'src/app/shared/service/whatever.service';
export class ReceivingComponentThing implements OnInit {
htmlExample = '';
constructor(private whateverService: WhateverService) {}
}
ngOnInit() {
// have a getter/setter in service however you like
this.htmlExample = this.whateverService.getHtmlExample();
}
```
in your template:
```
<div [innerHtml]="htmlExample"><div>
``` |
58,720,960 | We can use @Input as passing input props or data. We also can use `<ng-content>` to dump a load of html into the children component. Is there any way to pass html as Input. Like @Input html1, @Input html2, and use them in the child class component?
Suppose I have this html in child class:
```
<div class='wrapper'>
<div class="content1 exclusive-css-defined-to-this-component">
<div>{$content1}</div>
</div>
<div class="content2 exclusive-css-defined-to-this-component-2">
<div>{$content2}</div>
</div>
</div>
```
And I want to pass $content1 & $content2 as input. | 2019/11/05 | [
"https://Stackoverflow.com/questions/58720960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7055636/"
] | I have found the solution, this can be done by:
```
<div class='wrapper'>
<div class="exclusive-css-defined-to-this-component">
<div><ng-content select="[content1]"></ng-content></div>
</div>
<div class="exclusive-css-defined-to-this-component-2">
<div><ng-content select="[content2]"></ng-content></div>
</div>
</div>
```
And we can use the component like:
```
<wrapper>
<div content>Any thing you want to put in content1</div>
<div content2>Any thing you want to put in content2</div>
</wrapper>
``` | We can use **innerHTML** to achieve this
Sample example demonstrating this,
parent.component.ts,
```
export class ParentComponent {
htmlOneAsString = `
<div>Welcome Text Header</div>
`;
htmlTwoAsString = `
<div>Welcome Text Content</div>
`;
htmlAsString = `
<div><div>${this.htmlOneAsString}</div><div>${this.htmlTwoAsString}</div></div>
`;
}
```
parent.component.html,
```
<child [innerHTML]="htmlAsString"></child>
```
child.component.ts,
```
@Component({
selector: 'child'
})
export class ChildComponent {
@Input() htmlAsString: string;
}
```
child.component.html,
```
<div>{{htmlAsString}}</div>
``` |
988,032 | I need to write a script which writes to a file how many times this script has been executed.
How can I do that? | 2017/12/20 | [
"https://askubuntu.com/questions/988032",
"https://askubuntu.com",
"https://askubuntu.com/users/773615/"
] | I assume you want to have a single file `countfile` that only contains one single number representing the execution counter.
You can read this counter into a shell variable `$counter` e.g. using one of these lines:
* ```
read counter < countfile
```
* ```
counter=$(cat countfile)
```
Simple integer additions can be done in Bash itself using the `$(( EXPRESSION ))` syntax. Then simply write the result back to our `countfile`:
```
echo "$(( counter + 1 ))" > countfile
```
You should probably also safeguard your script for the case that `countfile` doesn't exist yet and create one initialized with the value 1 then.
The whole thing might look like this:
```
#!/bin/bash
if [[ -f countfile ]] ; then
read counter < countfile
else
counter=0
fi
echo "$(( counter + 1 ))" > countfile
``` | Just let the script create a log file, add for example a line in your script at the end:
```
echo "Script has been executed at $(date +\%Y-\%m-\%d) $(date +\%H-\%M-\%S)" >> ~/script.log
```
This way you can format the way you present date and time yourself, but if you simply want to go with a full date and time (and `HH:MM:SS` is an acceptable format for you) you can as well simply use:
```
echo "Script has been executed at $(date +\%F-\%T)" >> ~/script.log
```
Then you could do:
```
wc -l ~/script.log
```
Which counts the newline characters and give you an estimate of how many lines are inside the log file. Up to that you can see within the log file even when it was executed. To adapt it for your needs, you can change the paths and names used for logging. I just did an example here which saves the logfile in `~`.
So for example you want the script add this count to the line you added at the end of your script you could do something like this at the start of your script:
```
count=$(( $(wc -l ~/script.log | awk '{print $1}') + 1 ))
# the next line can be simply skipped if you not want an output to std_out
echo "Script execution number: $count"
```
And change your line at the end of the script to something including even that information:
```
echo "Script has been executed $count times at $(date +\%F-\%T)" >> ~/script.log
``` |
988,032 | I need to write a script which writes to a file how many times this script has been executed.
How can I do that? | 2017/12/20 | [
"https://askubuntu.com/questions/988032",
"https://askubuntu.com",
"https://askubuntu.com/users/773615/"
] | I assume you want to have a single file `countfile` that only contains one single number representing the execution counter.
You can read this counter into a shell variable `$counter` e.g. using one of these lines:
* ```
read counter < countfile
```
* ```
counter=$(cat countfile)
```
Simple integer additions can be done in Bash itself using the `$(( EXPRESSION ))` syntax. Then simply write the result back to our `countfile`:
```
echo "$(( counter + 1 ))" > countfile
```
You should probably also safeguard your script for the case that `countfile` doesn't exist yet and create one initialized with the value 1 then.
The whole thing might look like this:
```
#!/bin/bash
if [[ -f countfile ]] ; then
read counter < countfile
else
counter=0
fi
echo "$(( counter + 1 ))" > countfile
``` | This solution uses the same approach as [Byte Commander’s answer](/a/988035/175814) but it doesn't rely on shell arithmetic or other Bashisms.
```
exec 2>&3 2>/dev/null
read counter < counter.txt || counter=0
exec 3>&2 3>&-
expr "$counter" + 1 > counter.txt
```
The stream redirections
1. duplicate the standard error stream (2) to a different file descriptor (3),
2. replace it (2) with a redirection to `/dev/null` (to suppress the error message in the subsequent redirection of the input of the `read` command if the counter file is missing expectedly),
3. later duplicate the original standard error stream (now at 3) back into place (2) and
4. close the copy of the standard error stream (3). |
988,032 | I need to write a script which writes to a file how many times this script has been executed.
How can I do that? | 2017/12/20 | [
"https://askubuntu.com/questions/988032",
"https://askubuntu.com",
"https://askubuntu.com/users/773615/"
] | I assume you want to have a single file `countfile` that only contains one single number representing the execution counter.
You can read this counter into a shell variable `$counter` e.g. using one of these lines:
* ```
read counter < countfile
```
* ```
counter=$(cat countfile)
```
Simple integer additions can be done in Bash itself using the `$(( EXPRESSION ))` syntax. Then simply write the result back to our `countfile`:
```
echo "$(( counter + 1 ))" > countfile
```
You should probably also safeguard your script for the case that `countfile` doesn't exist yet and create one initialized with the value 1 then.
The whole thing might look like this:
```
#!/bin/bash
if [[ -f countfile ]] ; then
read counter < countfile
else
counter=0
fi
echo "$(( counter + 1 ))" > countfile
``` | A different approach
====================
A separate counter file has disadvantages:
* It takes 4096 bytes (or whatever your block size is) for each counter file.
* You have to look up the name of the file in the bash script and then open the file to see the count.
* There is no file locking (in other answers) so it's possible that two people update the counter at the exact same time (called race condition in comments under Byte Commander's answer).
So this answer does away with a separate counter file and puts the count in the bash script itself!
* Putting the counter in the bash script itself allows you to see within your script itself how many times it has been run.
* Using `flock` guarantees that for a brief moment it's not possible for two users to run the script at the same time.
* Because counter file name isn't hard coded, you don't need to change the code for different scripts, you can simply source it or copy and paste it from a stub / boilerplate file.
The code
========
```bash
#!/bin/bash
# NAME: run-count.sh
# PATH: $HOME/bin
# DESC: Written for AU Q&A: https://askubuntu.com/questions/988032/how-can-i-cause-a-script-to-log-in-a-separate-file-the-number-of-times-it-has-be
# DATE: Mar 16, 2018.
# This script run count: 0
# ======== FROM HERE DOWN CAN GO INTO FILE INCLUDED WITH SOURCE COMMAND =======
[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :
# This is useful boilerplate code for shell scripts. Put it at the top of
# the shell script you want to lock and it'll automatically lock itself on
# the first run. If the env var $FLOCKER is not set to the shell script
# that is being run, then execute flock and grab an exclusive non-blocking
# lock (using the script itself as the lock file) before re-execing itself
# with the right arguments. It also sets the FLOCKER env var to the right
# value so it doesn't run again.
# Read this script with entries separated newline " " into array
mapfile -t ScriptArr < "$0"
# Build search string that cannot be named
SearchStr="This script"
SearchStr=$SearchStr" run count: "
# Find our search string in array and increment count
for i in ${!ScriptArr[@]}; do
if [[ ${ScriptArr[i]} = *"$SearchStr"* ]]; then
OldCnt=$( echo ${ScriptArr[i]} | cut -d':' -f2 )
NewCnt=$(( $OldCnt + 1 ))
ScriptArr[i]=$SearchStr$NewCnt
break
fi
done
# Rewrite our script to disk with new run count
# BONUS: Date of script after writing will be last run time
printf "%s\n" "${ScriptArr[@]}" > "$0"
# ========= FROM HERE UP CAN GO INTO FILE INCLUDED WITH SOURCE COMMAND ========
# Now we return you to your original programming....
exit 0
```
Another Approach using a Log File
=================================
Similar to Videonauth's answer I wrote a log file answer here: [Bash script to maintain audit trail / log of files accessed](https://askubuntu.com/questions/850315/bash-script-to-maintain-audit-trail-log-of-files-accessed/851051#851051) to log every time root powers were used with `gedit` or `nautilus`.
The catch though is rather than using `gksu` the script is named `gsu` and invokes `pkexec` the "modern" way of using sudo in the GUI, so I am told.
Another advantage is not only does it say each time root powers were used with `gedit` but it logs the file name that was edited.
Here is the code.
`~/bin/gsu`:
```
#!/bin/bash
# Usage: gsu gedit file1 file2...
# -OR- gsu natuilus /dirname
# & is used to spawn process and get prompt back ASAP
# > /dev/null is used to send gtk warnings into dumpster
COMMAND="$1" # extract gedit or nautilus
pkexec "$COMMAND" "${@:2}"
log-file "${@:2}" gsu-log-file-for-"$COMMAND"
```
`/usr/local/bin/log-file`:
```
#! /bin/bash
# NAME: log-file
# PATH: /usr/local/bin
# DESC: Update audit trail/log file with passed parameters.
# CALL: log-file FileName LogFileName
# DATE: Created Nov 18, 2016.
# NOTE: Primarily called from ~/bin/gsu
ABSOLUTE_NAME=$(realpath "$1")
TIME_STAMP=$(date +"%D - %T")
LOG_FILE="$2"
# Does log file need to be created?
if [ ! -f "$LOG_FILE" ]; then
touch "$LOG_FILE"
echo "__Date__ - __Time__ - ______File Name______" >> "$LOG_FILE"
# MM/DD/YY - hh:mm:ss - "a/b/c/FileName"
fi
echo "$TIME_STAMP" - '"'"$ABSOLUTE_NAME"'"' >> "$LOG_FILE"
exit 0
```
Contents of log file `gsu-log-file-for-gedit`after a few edits:
```
__Date__ - __Time__ - ______File Name______
11/18/16 - 19:07:54 - "/etc/default/grub"
11/18/16 - 19:08:34 - "/home/rick/bin/gsu"
11/18/16 - 19:09:26 - "/home/rick/bin/gsu"
``` |
988,032 | I need to write a script which writes to a file how many times this script has been executed.
How can I do that? | 2017/12/20 | [
"https://askubuntu.com/questions/988032",
"https://askubuntu.com",
"https://askubuntu.com/users/773615/"
] | Just let the script create a log file, add for example a line in your script at the end:
```
echo "Script has been executed at $(date +\%Y-\%m-\%d) $(date +\%H-\%M-\%S)" >> ~/script.log
```
This way you can format the way you present date and time yourself, but if you simply want to go with a full date and time (and `HH:MM:SS` is an acceptable format for you) you can as well simply use:
```
echo "Script has been executed at $(date +\%F-\%T)" >> ~/script.log
```
Then you could do:
```
wc -l ~/script.log
```
Which counts the newline characters and give you an estimate of how many lines are inside the log file. Up to that you can see within the log file even when it was executed. To adapt it for your needs, you can change the paths and names used for logging. I just did an example here which saves the logfile in `~`.
So for example you want the script add this count to the line you added at the end of your script you could do something like this at the start of your script:
```
count=$(( $(wc -l ~/script.log | awk '{print $1}') + 1 ))
# the next line can be simply skipped if you not want an output to std_out
echo "Script execution number: $count"
```
And change your line at the end of the script to something including even that information:
```
echo "Script has been executed $count times at $(date +\%F-\%T)" >> ~/script.log
``` | A different approach
====================
A separate counter file has disadvantages:
* It takes 4096 bytes (or whatever your block size is) for each counter file.
* You have to look up the name of the file in the bash script and then open the file to see the count.
* There is no file locking (in other answers) so it's possible that two people update the counter at the exact same time (called race condition in comments under Byte Commander's answer).
So this answer does away with a separate counter file and puts the count in the bash script itself!
* Putting the counter in the bash script itself allows you to see within your script itself how many times it has been run.
* Using `flock` guarantees that for a brief moment it's not possible for two users to run the script at the same time.
* Because counter file name isn't hard coded, you don't need to change the code for different scripts, you can simply source it or copy and paste it from a stub / boilerplate file.
The code
========
```bash
#!/bin/bash
# NAME: run-count.sh
# PATH: $HOME/bin
# DESC: Written for AU Q&A: https://askubuntu.com/questions/988032/how-can-i-cause-a-script-to-log-in-a-separate-file-the-number-of-times-it-has-be
# DATE: Mar 16, 2018.
# This script run count: 0
# ======== FROM HERE DOWN CAN GO INTO FILE INCLUDED WITH SOURCE COMMAND =======
[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :
# This is useful boilerplate code for shell scripts. Put it at the top of
# the shell script you want to lock and it'll automatically lock itself on
# the first run. If the env var $FLOCKER is not set to the shell script
# that is being run, then execute flock and grab an exclusive non-blocking
# lock (using the script itself as the lock file) before re-execing itself
# with the right arguments. It also sets the FLOCKER env var to the right
# value so it doesn't run again.
# Read this script with entries separated newline " " into array
mapfile -t ScriptArr < "$0"
# Build search string that cannot be named
SearchStr="This script"
SearchStr=$SearchStr" run count: "
# Find our search string in array and increment count
for i in ${!ScriptArr[@]}; do
if [[ ${ScriptArr[i]} = *"$SearchStr"* ]]; then
OldCnt=$( echo ${ScriptArr[i]} | cut -d':' -f2 )
NewCnt=$(( $OldCnt + 1 ))
ScriptArr[i]=$SearchStr$NewCnt
break
fi
done
# Rewrite our script to disk with new run count
# BONUS: Date of script after writing will be last run time
printf "%s\n" "${ScriptArr[@]}" > "$0"
# ========= FROM HERE UP CAN GO INTO FILE INCLUDED WITH SOURCE COMMAND ========
# Now we return you to your original programming....
exit 0
```
Another Approach using a Log File
=================================
Similar to Videonauth's answer I wrote a log file answer here: [Bash script to maintain audit trail / log of files accessed](https://askubuntu.com/questions/850315/bash-script-to-maintain-audit-trail-log-of-files-accessed/851051#851051) to log every time root powers were used with `gedit` or `nautilus`.
The catch though is rather than using `gksu` the script is named `gsu` and invokes `pkexec` the "modern" way of using sudo in the GUI, so I am told.
Another advantage is not only does it say each time root powers were used with `gedit` but it logs the file name that was edited.
Here is the code.
`~/bin/gsu`:
```
#!/bin/bash
# Usage: gsu gedit file1 file2...
# -OR- gsu natuilus /dirname
# & is used to spawn process and get prompt back ASAP
# > /dev/null is used to send gtk warnings into dumpster
COMMAND="$1" # extract gedit or nautilus
pkexec "$COMMAND" "${@:2}"
log-file "${@:2}" gsu-log-file-for-"$COMMAND"
```
`/usr/local/bin/log-file`:
```
#! /bin/bash
# NAME: log-file
# PATH: /usr/local/bin
# DESC: Update audit trail/log file with passed parameters.
# CALL: log-file FileName LogFileName
# DATE: Created Nov 18, 2016.
# NOTE: Primarily called from ~/bin/gsu
ABSOLUTE_NAME=$(realpath "$1")
TIME_STAMP=$(date +"%D - %T")
LOG_FILE="$2"
# Does log file need to be created?
if [ ! -f "$LOG_FILE" ]; then
touch "$LOG_FILE"
echo "__Date__ - __Time__ - ______File Name______" >> "$LOG_FILE"
# MM/DD/YY - hh:mm:ss - "a/b/c/FileName"
fi
echo "$TIME_STAMP" - '"'"$ABSOLUTE_NAME"'"' >> "$LOG_FILE"
exit 0
```
Contents of log file `gsu-log-file-for-gedit`after a few edits:
```
__Date__ - __Time__ - ______File Name______
11/18/16 - 19:07:54 - "/etc/default/grub"
11/18/16 - 19:08:34 - "/home/rick/bin/gsu"
11/18/16 - 19:09:26 - "/home/rick/bin/gsu"
``` |
988,032 | I need to write a script which writes to a file how many times this script has been executed.
How can I do that? | 2017/12/20 | [
"https://askubuntu.com/questions/988032",
"https://askubuntu.com",
"https://askubuntu.com/users/773615/"
] | This solution uses the same approach as [Byte Commander’s answer](/a/988035/175814) but it doesn't rely on shell arithmetic or other Bashisms.
```
exec 2>&3 2>/dev/null
read counter < counter.txt || counter=0
exec 3>&2 3>&-
expr "$counter" + 1 > counter.txt
```
The stream redirections
1. duplicate the standard error stream (2) to a different file descriptor (3),
2. replace it (2) with a redirection to `/dev/null` (to suppress the error message in the subsequent redirection of the input of the `read` command if the counter file is missing expectedly),
3. later duplicate the original standard error stream (now at 3) back into place (2) and
4. close the copy of the standard error stream (3). | A different approach
====================
A separate counter file has disadvantages:
* It takes 4096 bytes (or whatever your block size is) for each counter file.
* You have to look up the name of the file in the bash script and then open the file to see the count.
* There is no file locking (in other answers) so it's possible that two people update the counter at the exact same time (called race condition in comments under Byte Commander's answer).
So this answer does away with a separate counter file and puts the count in the bash script itself!
* Putting the counter in the bash script itself allows you to see within your script itself how many times it has been run.
* Using `flock` guarantees that for a brief moment it's not possible for two users to run the script at the same time.
* Because counter file name isn't hard coded, you don't need to change the code for different scripts, you can simply source it or copy and paste it from a stub / boilerplate file.
The code
========
```bash
#!/bin/bash
# NAME: run-count.sh
# PATH: $HOME/bin
# DESC: Written for AU Q&A: https://askubuntu.com/questions/988032/how-can-i-cause-a-script-to-log-in-a-separate-file-the-number-of-times-it-has-be
# DATE: Mar 16, 2018.
# This script run count: 0
# ======== FROM HERE DOWN CAN GO INTO FILE INCLUDED WITH SOURCE COMMAND =======
[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :
# This is useful boilerplate code for shell scripts. Put it at the top of
# the shell script you want to lock and it'll automatically lock itself on
# the first run. If the env var $FLOCKER is not set to the shell script
# that is being run, then execute flock and grab an exclusive non-blocking
# lock (using the script itself as the lock file) before re-execing itself
# with the right arguments. It also sets the FLOCKER env var to the right
# value so it doesn't run again.
# Read this script with entries separated newline " " into array
mapfile -t ScriptArr < "$0"
# Build search string that cannot be named
SearchStr="This script"
SearchStr=$SearchStr" run count: "
# Find our search string in array and increment count
for i in ${!ScriptArr[@]}; do
if [[ ${ScriptArr[i]} = *"$SearchStr"* ]]; then
OldCnt=$( echo ${ScriptArr[i]} | cut -d':' -f2 )
NewCnt=$(( $OldCnt + 1 ))
ScriptArr[i]=$SearchStr$NewCnt
break
fi
done
# Rewrite our script to disk with new run count
# BONUS: Date of script after writing will be last run time
printf "%s\n" "${ScriptArr[@]}" > "$0"
# ========= FROM HERE UP CAN GO INTO FILE INCLUDED WITH SOURCE COMMAND ========
# Now we return you to your original programming....
exit 0
```
Another Approach using a Log File
=================================
Similar to Videonauth's answer I wrote a log file answer here: [Bash script to maintain audit trail / log of files accessed](https://askubuntu.com/questions/850315/bash-script-to-maintain-audit-trail-log-of-files-accessed/851051#851051) to log every time root powers were used with `gedit` or `nautilus`.
The catch though is rather than using `gksu` the script is named `gsu` and invokes `pkexec` the "modern" way of using sudo in the GUI, so I am told.
Another advantage is not only does it say each time root powers were used with `gedit` but it logs the file name that was edited.
Here is the code.
`~/bin/gsu`:
```
#!/bin/bash
# Usage: gsu gedit file1 file2...
# -OR- gsu natuilus /dirname
# & is used to spawn process and get prompt back ASAP
# > /dev/null is used to send gtk warnings into dumpster
COMMAND="$1" # extract gedit or nautilus
pkexec "$COMMAND" "${@:2}"
log-file "${@:2}" gsu-log-file-for-"$COMMAND"
```
`/usr/local/bin/log-file`:
```
#! /bin/bash
# NAME: log-file
# PATH: /usr/local/bin
# DESC: Update audit trail/log file with passed parameters.
# CALL: log-file FileName LogFileName
# DATE: Created Nov 18, 2016.
# NOTE: Primarily called from ~/bin/gsu
ABSOLUTE_NAME=$(realpath "$1")
TIME_STAMP=$(date +"%D - %T")
LOG_FILE="$2"
# Does log file need to be created?
if [ ! -f "$LOG_FILE" ]; then
touch "$LOG_FILE"
echo "__Date__ - __Time__ - ______File Name______" >> "$LOG_FILE"
# MM/DD/YY - hh:mm:ss - "a/b/c/FileName"
fi
echo "$TIME_STAMP" - '"'"$ABSOLUTE_NAME"'"' >> "$LOG_FILE"
exit 0
```
Contents of log file `gsu-log-file-for-gedit`after a few edits:
```
__Date__ - __Time__ - ______File Name______
11/18/16 - 19:07:54 - "/etc/default/grub"
11/18/16 - 19:08:34 - "/home/rick/bin/gsu"
11/18/16 - 19:09:26 - "/home/rick/bin/gsu"
``` |
420,325 | **Problem: It's a common problem for "NON-inverter" type microwave ovens to pop circuit breakers**, and mine is no exception.
**UPDATE Jan 2021: Extension / power strip added, (mentioned below) has still eliminated this problem completely! I think I've only popped that breaker once in two years.** Fascinating as this subject was, I'm done. Note that both virtually identical KitchenAid microwaves popped that breaker, but the other same sized circuit breaker circuit, (slightly longer than this run's 1 foot away from the main panel), has never popped the breaker with either microwave. So, AFAIK, this problem has been confirmed as a design defect, and not a malfunction, on a circuit that is on an unusually short run. And further, the added small amount of impedance added, eliminated these design symptoms.
There could be a huge number of reasons for this. Even though I thought I had really researched microwave ovens extensively, have replaced magnetrons in two nearly identical ovens, I found this one resource that taught me more than I had ever known. It covers design goals, troubleshooting, and things you'd never know, unless you both designed these ovens and also repaired them as a full time job:
[Notes on the Troubleshooting and Repair of Microwave Ovens](https://repairfaq.org/sam/micfaq.htm), written and compiled by Sam Goldwasser. I highly suggest you read it carefully. It will likely save you a ton of time, even if you are a master IEEE designer.
Based on what I've learned, I have new questions and new concerns:
**-- Using an add-on power strip could be dangerous, if not properly designed.** (This "fixed", masked or worked around other problems for me.) My strip is well built and I'm not concerned. But be aware that the magnetron is 5000v hot on one side, and grounded directly to the case. Lose the ground and /or a lousy partially floating neutral, (which I've seen before), and you could get killed from the case becoming some fraction of 5,000 VAC, through you to earth ground.
I've got two identically designed ovens, both of which deliver the same solid 700W, computed from testing heating water. (Litton manual says 1 liter 1 minute -->> deg C x 70 = Watts -- mine 18 f = 10 c x 70 = 700 watts). So, I doubt if I have a shorted diode, or have lost some turns in my transformer. But, arcing in the transformer itself, the triac, the diode, the capacitor becoming weak and things going on inside the magenetron, the waveguide itself, food buildup; these and many more factors can ALL affect performance, and can affect the startup and continuous draw of the oven. Inverters just would add to the complexity of determining what's really happening, since adding a switching power supply can add a set of different problems.
Before I added the power strip, throwing the breaker seemed to be getting worse, which could mean that the 20A breaker itself is getting weaker, (which I'd rather not replace). I had replaced magnetrons in two nearly identical ovens, and understand the specific designs of both, which I don't intend to modify at all. It seems to me that the bleed resister across the capacitor that discharges it, (and *does* work), does a "great job", as intended. But other people have said that this means that startup draw, to charge that capacitor, is the cause of about an extra 5-10A on a 10A microwave, for the short startup time.
Again though, I'd like to add something external to the oven, without opening the case, which might then work for many that have the heavy transformer and not an inverter switched power supply type oven.
My goal would be to design an add-on device that would limit the voltage / current for 0.1-0.5 seconds while the microwave is charging that capacitor (which doubles the DC voltage AFTER it is fully charged). On most ovens, I would guess that the control board's filter capacitor should keep that operational with just a very short term voltage drop, even if a substantial voltage drop to its power supply.
In a standard oven, there's a huge and heavy transformer that is serving as a huge inductor, fed with normal 120 Vac, usually using a solid state triac as a switch. (Panasonic, Sharp and many others use inverter power supplies.)
**SIMPLE solution, that has so far, *works!***
**SEE cautions about adding this, mentioned above!!**
Adding a simple 6-8 FT AWG 14 extension cord to the circuit seems to have fixed the problem. As @Charles Cowey suggested, my oven is plugged into a circuit that is literally one foot from the breaker box. It seems cold weather reduces AC use, increases the available line voltage enough, and puts this right at the edge.
I will have to open the power strip [and report back] to see if there are some added inductors inside. (AWG 14 has an impedance @60 HZ of only 3 ohms / DC resistance 2.5 ohms per 1000 feet. So ~.03 ohms added to an effective 12 ohm oven doesn't seem significant enough to fix it. Ref.: [AC/DC Chart / pub. by Anexter](https://www.anixter.com/content/dam/Anixter/Guide/7H0011X0_W&C_Tech_Handbook_Sec_07.pdf) ) In any case, if building a universal solution as inexpensively as possible, it seems that simply **CHOOSING a good surge protector with an added torroid coil inside, (which I have seen), should solve most of these problems.**
"Older ovens with large transformers" (by @Charles Cowey) implies that standard designs have changed, perhaps to switching supplies?? IF so, am I solving a problem that will be phased out in the next decade?
**OTHER Possible solutions?:**
**NOTE -- EXPERIMENTALLY rewiring that 120/240 VAC circuit feed is NOT a good idea--Do it wrong and you could get a 5000 V shock!**
**1.2 ohm resistor, in-line, before oven's 120 V ordinary line cord**
One simple method might be to simply add an in-line resistor. A 10A microwave @ 120 V is drawing 1200 W, with an effective impedance of 12 ohms. Simply adding a ~1.2 ohm resistor in series would cut the voltage/power by 10%, as well as the surge power, which is tripping breakers, which might do the job. While running of course, that resistor would be creating the heat of a 100 W lightbulb.
**Lightbulb: NO!**
Unfortunately, I need a lightbulb to use as a resister, which would have less resistance as it heats up, which of course incandescent bulbs do not. Nevertheless, this would be the perfect inexpensive method to use as the main component of this device.
**??**
**So, what could I build that would accomplish this??**
What I need is a resistor that starts as a 12 ohm resistor and becomes a 1.2 ohm resistor, or less.
**After research, there are inexpensive ($5 for 2) NTC (Negative Temp. Coefficient) devices that do ICL (Inrush Current Limiting). Unfortunately, they work by heating, and won't cool in less than 30 seconds, and so won't work** in ovens that cycle on and off every 6 seconds (@ 50% power setting).
[Amtherm company focuses on RTC devices and designs](https://www.ametherm.com/), and seem to be the best resource for designing circuits that utilize RTCs.
As a sidenote, these NTCs are using in virtually all of today's variable speed motors used commonly in HVAC systems. These RTCs often fail, and commonly the AC tech unknowingly recommends replacing the whole motor at a cost of > $1,000 rather than the < $5 RTC replacement! | 2019/02/03 | [
"https://electronics.stackexchange.com/questions/420325",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/211801/"
] | In an older model microwave with a huge heavy transformer, the inrush current may be due to the transformer saturating when power is switched on at the peak of the voltage waveform. If that is the case, very little additional impedance may be required. I have seen the problem in a location where the distribution panel was in the basement directly below the kitchen counter. There may have been only about six feet of wire between the circuit breaker and the microwave. In that case, the problem was solved by replacing the standard 20-amp breaker with a 20-amp, high magnetic trip breaker.
It is possible that only a tiny impedance to the power feed, perhaps 15 feet of 12 AWG cable may be sufficient. | 3 recommendations
=================
* Test or replace bulk Film cap (test by RLC meter @120Hz)
* insert an Inrush Current Limiter (ICL) for rated current eg 120Vac, 10A a) 7 Ω to 0.08 Ω or b) 20 Ω to 0.18 Ω. (Slow response)
* add series 12 Ω power R and Time delay SPST 10A relay to shunt R
My Panasonic oven may have a soft start circuit as I can tell by the delay in lamp dim after it starts the turntable, fan and lamp first.
But in my experience , the 1st choice is the best for units beyond warranty and worked for me with **exactly your symptoms.**
You may also choose an ICL with your specs based on the bulk capacitance at 120V.
The R+ Relay solution also avoids the surge current.
However power distribution in the home and thermal response of wires fuses and breakers are normal never exceeded unless there is a component degradation or fault. Adding some short cable resistance only reduces the surge current a bit.
Therefore the universal solution is repair the unit and #1 recommendation is the most common. |
420,325 | **Problem: It's a common problem for "NON-inverter" type microwave ovens to pop circuit breakers**, and mine is no exception.
**UPDATE Jan 2021: Extension / power strip added, (mentioned below) has still eliminated this problem completely! I think I've only popped that breaker once in two years.** Fascinating as this subject was, I'm done. Note that both virtually identical KitchenAid microwaves popped that breaker, but the other same sized circuit breaker circuit, (slightly longer than this run's 1 foot away from the main panel), has never popped the breaker with either microwave. So, AFAIK, this problem has been confirmed as a design defect, and not a malfunction, on a circuit that is on an unusually short run. And further, the added small amount of impedance added, eliminated these design symptoms.
There could be a huge number of reasons for this. Even though I thought I had really researched microwave ovens extensively, have replaced magnetrons in two nearly identical ovens, I found this one resource that taught me more than I had ever known. It covers design goals, troubleshooting, and things you'd never know, unless you both designed these ovens and also repaired them as a full time job:
[Notes on the Troubleshooting and Repair of Microwave Ovens](https://repairfaq.org/sam/micfaq.htm), written and compiled by Sam Goldwasser. I highly suggest you read it carefully. It will likely save you a ton of time, even if you are a master IEEE designer.
Based on what I've learned, I have new questions and new concerns:
**-- Using an add-on power strip could be dangerous, if not properly designed.** (This "fixed", masked or worked around other problems for me.) My strip is well built and I'm not concerned. But be aware that the magnetron is 5000v hot on one side, and grounded directly to the case. Lose the ground and /or a lousy partially floating neutral, (which I've seen before), and you could get killed from the case becoming some fraction of 5,000 VAC, through you to earth ground.
I've got two identically designed ovens, both of which deliver the same solid 700W, computed from testing heating water. (Litton manual says 1 liter 1 minute -->> deg C x 70 = Watts -- mine 18 f = 10 c x 70 = 700 watts). So, I doubt if I have a shorted diode, or have lost some turns in my transformer. But, arcing in the transformer itself, the triac, the diode, the capacitor becoming weak and things going on inside the magenetron, the waveguide itself, food buildup; these and many more factors can ALL affect performance, and can affect the startup and continuous draw of the oven. Inverters just would add to the complexity of determining what's really happening, since adding a switching power supply can add a set of different problems.
Before I added the power strip, throwing the breaker seemed to be getting worse, which could mean that the 20A breaker itself is getting weaker, (which I'd rather not replace). I had replaced magnetrons in two nearly identical ovens, and understand the specific designs of both, which I don't intend to modify at all. It seems to me that the bleed resister across the capacitor that discharges it, (and *does* work), does a "great job", as intended. But other people have said that this means that startup draw, to charge that capacitor, is the cause of about an extra 5-10A on a 10A microwave, for the short startup time.
Again though, I'd like to add something external to the oven, without opening the case, which might then work for many that have the heavy transformer and not an inverter switched power supply type oven.
My goal would be to design an add-on device that would limit the voltage / current for 0.1-0.5 seconds while the microwave is charging that capacitor (which doubles the DC voltage AFTER it is fully charged). On most ovens, I would guess that the control board's filter capacitor should keep that operational with just a very short term voltage drop, even if a substantial voltage drop to its power supply.
In a standard oven, there's a huge and heavy transformer that is serving as a huge inductor, fed with normal 120 Vac, usually using a solid state triac as a switch. (Panasonic, Sharp and many others use inverter power supplies.)
**SIMPLE solution, that has so far, *works!***
**SEE cautions about adding this, mentioned above!!**
Adding a simple 6-8 FT AWG 14 extension cord to the circuit seems to have fixed the problem. As @Charles Cowey suggested, my oven is plugged into a circuit that is literally one foot from the breaker box. It seems cold weather reduces AC use, increases the available line voltage enough, and puts this right at the edge.
I will have to open the power strip [and report back] to see if there are some added inductors inside. (AWG 14 has an impedance @60 HZ of only 3 ohms / DC resistance 2.5 ohms per 1000 feet. So ~.03 ohms added to an effective 12 ohm oven doesn't seem significant enough to fix it. Ref.: [AC/DC Chart / pub. by Anexter](https://www.anixter.com/content/dam/Anixter/Guide/7H0011X0_W&C_Tech_Handbook_Sec_07.pdf) ) In any case, if building a universal solution as inexpensively as possible, it seems that simply **CHOOSING a good surge protector with an added torroid coil inside, (which I have seen), should solve most of these problems.**
"Older ovens with large transformers" (by @Charles Cowey) implies that standard designs have changed, perhaps to switching supplies?? IF so, am I solving a problem that will be phased out in the next decade?
**OTHER Possible solutions?:**
**NOTE -- EXPERIMENTALLY rewiring that 120/240 VAC circuit feed is NOT a good idea--Do it wrong and you could get a 5000 V shock!**
**1.2 ohm resistor, in-line, before oven's 120 V ordinary line cord**
One simple method might be to simply add an in-line resistor. A 10A microwave @ 120 V is drawing 1200 W, with an effective impedance of 12 ohms. Simply adding a ~1.2 ohm resistor in series would cut the voltage/power by 10%, as well as the surge power, which is tripping breakers, which might do the job. While running of course, that resistor would be creating the heat of a 100 W lightbulb.
**Lightbulb: NO!**
Unfortunately, I need a lightbulb to use as a resister, which would have less resistance as it heats up, which of course incandescent bulbs do not. Nevertheless, this would be the perfect inexpensive method to use as the main component of this device.
**??**
**So, what could I build that would accomplish this??**
What I need is a resistor that starts as a 12 ohm resistor and becomes a 1.2 ohm resistor, or less.
**After research, there are inexpensive ($5 for 2) NTC (Negative Temp. Coefficient) devices that do ICL (Inrush Current Limiting). Unfortunately, they work by heating, and won't cool in less than 30 seconds, and so won't work** in ovens that cycle on and off every 6 seconds (@ 50% power setting).
[Amtherm company focuses on RTC devices and designs](https://www.ametherm.com/), and seem to be the best resource for designing circuits that utilize RTCs.
As a sidenote, these NTCs are using in virtually all of today's variable speed motors used commonly in HVAC systems. These RTCs often fail, and commonly the AC tech unknowingly recommends replacing the whole motor at a cost of > $1,000 rather than the < $5 RTC replacement! | 2019/02/03 | [
"https://electronics.stackexchange.com/questions/420325",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/211801/"
] | In an older model microwave with a huge heavy transformer, the inrush current may be due to the transformer saturating when power is switched on at the peak of the voltage waveform. If that is the case, very little additional impedance may be required. I have seen the problem in a location where the distribution panel was in the basement directly below the kitchen counter. There may have been only about six feet of wire between the circuit breaker and the microwave. In that case, the problem was solved by replacing the standard 20-amp breaker with a 20-amp, high magnetic trip breaker.
It is possible that only a tiny impedance to the power feed, perhaps 15 feet of 12 AWG cable may be sufficient. | What happens is, the transformer saturates on startup. The magnetization current normally passes through zero at about 1/2 way through each 1/2 cycle. If it gets turned at the beginning, the mag. current starts from zero instead of -peak, so it heads towards double peak and saturates the core. The coil then behaves like an air core coil, so the current goes through the roof, and all the excess flux passes straight through the saturated core to the steel case underneath, causing that characteristic THUNK. The transformer needs to be turned on 1/2 way through a 1/2 cycle. Don't worry about the capacitor on secondary. The secondary is loosely coupled & the flux can bypass it through the magnetic shunts if necessary. Checkout my answer on this site for how the circuit works. [What are the bare minimum parts needed to operate a magnetron?](https://electronics.stackexchange.com/questions/129203/what-are-the-bare-minimum-parts-needed-to-operate-a-magnetron)
As far as I know, all of the microwave oven processors use the supply frequency as their clock, which means, the relay pickup will be synchronised to the supply. If there is no little silver can with a crystal in it, it will be, especially if it THUNKS every time the relay picks up. If so, you could try this super simple delay circuit I designed in place of the transistor that drives the transformer relay. Remove the transistor, set the pot fully CCW and install this circuit in place of it. Bend the wires as shown so they will bend if bumped and not push the tracks off the main board, then, with the power set low, so the relay drops in & out, adjust the pot until the transformer just stops thunking. Then count the turns until it just starts again, and set the pot ½ way between. That will switch the transformer on in the middle of a ½ cycle when the magnetisation current would be crossing zero. 2N7000s have a Vth spread of .8-3V and I don't know what voltage the processor feeds out to the base resistor, so if you run out of adjustment, change the capacitor to .022uF. Let me know is it works. Cheers!
[](https://i.stack.imgur.com/IiAzG.png) |
420,325 | **Problem: It's a common problem for "NON-inverter" type microwave ovens to pop circuit breakers**, and mine is no exception.
**UPDATE Jan 2021: Extension / power strip added, (mentioned below) has still eliminated this problem completely! I think I've only popped that breaker once in two years.** Fascinating as this subject was, I'm done. Note that both virtually identical KitchenAid microwaves popped that breaker, but the other same sized circuit breaker circuit, (slightly longer than this run's 1 foot away from the main panel), has never popped the breaker with either microwave. So, AFAIK, this problem has been confirmed as a design defect, and not a malfunction, on a circuit that is on an unusually short run. And further, the added small amount of impedance added, eliminated these design symptoms.
There could be a huge number of reasons for this. Even though I thought I had really researched microwave ovens extensively, have replaced magnetrons in two nearly identical ovens, I found this one resource that taught me more than I had ever known. It covers design goals, troubleshooting, and things you'd never know, unless you both designed these ovens and also repaired them as a full time job:
[Notes on the Troubleshooting and Repair of Microwave Ovens](https://repairfaq.org/sam/micfaq.htm), written and compiled by Sam Goldwasser. I highly suggest you read it carefully. It will likely save you a ton of time, even if you are a master IEEE designer.
Based on what I've learned, I have new questions and new concerns:
**-- Using an add-on power strip could be dangerous, if not properly designed.** (This "fixed", masked or worked around other problems for me.) My strip is well built and I'm not concerned. But be aware that the magnetron is 5000v hot on one side, and grounded directly to the case. Lose the ground and /or a lousy partially floating neutral, (which I've seen before), and you could get killed from the case becoming some fraction of 5,000 VAC, through you to earth ground.
I've got two identically designed ovens, both of which deliver the same solid 700W, computed from testing heating water. (Litton manual says 1 liter 1 minute -->> deg C x 70 = Watts -- mine 18 f = 10 c x 70 = 700 watts). So, I doubt if I have a shorted diode, or have lost some turns in my transformer. But, arcing in the transformer itself, the triac, the diode, the capacitor becoming weak and things going on inside the magenetron, the waveguide itself, food buildup; these and many more factors can ALL affect performance, and can affect the startup and continuous draw of the oven. Inverters just would add to the complexity of determining what's really happening, since adding a switching power supply can add a set of different problems.
Before I added the power strip, throwing the breaker seemed to be getting worse, which could mean that the 20A breaker itself is getting weaker, (which I'd rather not replace). I had replaced magnetrons in two nearly identical ovens, and understand the specific designs of both, which I don't intend to modify at all. It seems to me that the bleed resister across the capacitor that discharges it, (and *does* work), does a "great job", as intended. But other people have said that this means that startup draw, to charge that capacitor, is the cause of about an extra 5-10A on a 10A microwave, for the short startup time.
Again though, I'd like to add something external to the oven, without opening the case, which might then work for many that have the heavy transformer and not an inverter switched power supply type oven.
My goal would be to design an add-on device that would limit the voltage / current for 0.1-0.5 seconds while the microwave is charging that capacitor (which doubles the DC voltage AFTER it is fully charged). On most ovens, I would guess that the control board's filter capacitor should keep that operational with just a very short term voltage drop, even if a substantial voltage drop to its power supply.
In a standard oven, there's a huge and heavy transformer that is serving as a huge inductor, fed with normal 120 Vac, usually using a solid state triac as a switch. (Panasonic, Sharp and many others use inverter power supplies.)
**SIMPLE solution, that has so far, *works!***
**SEE cautions about adding this, mentioned above!!**
Adding a simple 6-8 FT AWG 14 extension cord to the circuit seems to have fixed the problem. As @Charles Cowey suggested, my oven is plugged into a circuit that is literally one foot from the breaker box. It seems cold weather reduces AC use, increases the available line voltage enough, and puts this right at the edge.
I will have to open the power strip [and report back] to see if there are some added inductors inside. (AWG 14 has an impedance @60 HZ of only 3 ohms / DC resistance 2.5 ohms per 1000 feet. So ~.03 ohms added to an effective 12 ohm oven doesn't seem significant enough to fix it. Ref.: [AC/DC Chart / pub. by Anexter](https://www.anixter.com/content/dam/Anixter/Guide/7H0011X0_W&C_Tech_Handbook_Sec_07.pdf) ) In any case, if building a universal solution as inexpensively as possible, it seems that simply **CHOOSING a good surge protector with an added torroid coil inside, (which I have seen), should solve most of these problems.**
"Older ovens with large transformers" (by @Charles Cowey) implies that standard designs have changed, perhaps to switching supplies?? IF so, am I solving a problem that will be phased out in the next decade?
**OTHER Possible solutions?:**
**NOTE -- EXPERIMENTALLY rewiring that 120/240 VAC circuit feed is NOT a good idea--Do it wrong and you could get a 5000 V shock!**
**1.2 ohm resistor, in-line, before oven's 120 V ordinary line cord**
One simple method might be to simply add an in-line resistor. A 10A microwave @ 120 V is drawing 1200 W, with an effective impedance of 12 ohms. Simply adding a ~1.2 ohm resistor in series would cut the voltage/power by 10%, as well as the surge power, which is tripping breakers, which might do the job. While running of course, that resistor would be creating the heat of a 100 W lightbulb.
**Lightbulb: NO!**
Unfortunately, I need a lightbulb to use as a resister, which would have less resistance as it heats up, which of course incandescent bulbs do not. Nevertheless, this would be the perfect inexpensive method to use as the main component of this device.
**??**
**So, what could I build that would accomplish this??**
What I need is a resistor that starts as a 12 ohm resistor and becomes a 1.2 ohm resistor, or less.
**After research, there are inexpensive ($5 for 2) NTC (Negative Temp. Coefficient) devices that do ICL (Inrush Current Limiting). Unfortunately, they work by heating, and won't cool in less than 30 seconds, and so won't work** in ovens that cycle on and off every 6 seconds (@ 50% power setting).
[Amtherm company focuses on RTC devices and designs](https://www.ametherm.com/), and seem to be the best resource for designing circuits that utilize RTCs.
As a sidenote, these NTCs are using in virtually all of today's variable speed motors used commonly in HVAC systems. These RTCs often fail, and commonly the AC tech unknowingly recommends replacing the whole motor at a cost of > $1,000 rather than the < $5 RTC replacement! | 2019/02/03 | [
"https://electronics.stackexchange.com/questions/420325",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/211801/"
] | 3 recommendations
=================
* Test or replace bulk Film cap (test by RLC meter @120Hz)
* insert an Inrush Current Limiter (ICL) for rated current eg 120Vac, 10A a) 7 Ω to 0.08 Ω or b) 20 Ω to 0.18 Ω. (Slow response)
* add series 12 Ω power R and Time delay SPST 10A relay to shunt R
My Panasonic oven may have a soft start circuit as I can tell by the delay in lamp dim after it starts the turntable, fan and lamp first.
But in my experience , the 1st choice is the best for units beyond warranty and worked for me with **exactly your symptoms.**
You may also choose an ICL with your specs based on the bulk capacitance at 120V.
The R+ Relay solution also avoids the surge current.
However power distribution in the home and thermal response of wires fuses and breakers are normal never exceeded unless there is a component degradation or fault. Adding some short cable resistance only reduces the surge current a bit.
Therefore the universal solution is repair the unit and #1 recommendation is the most common. | What happens is, the transformer saturates on startup. The magnetization current normally passes through zero at about 1/2 way through each 1/2 cycle. If it gets turned at the beginning, the mag. current starts from zero instead of -peak, so it heads towards double peak and saturates the core. The coil then behaves like an air core coil, so the current goes through the roof, and all the excess flux passes straight through the saturated core to the steel case underneath, causing that characteristic THUNK. The transformer needs to be turned on 1/2 way through a 1/2 cycle. Don't worry about the capacitor on secondary. The secondary is loosely coupled & the flux can bypass it through the magnetic shunts if necessary. Checkout my answer on this site for how the circuit works. [What are the bare minimum parts needed to operate a magnetron?](https://electronics.stackexchange.com/questions/129203/what-are-the-bare-minimum-parts-needed-to-operate-a-magnetron)
As far as I know, all of the microwave oven processors use the supply frequency as their clock, which means, the relay pickup will be synchronised to the supply. If there is no little silver can with a crystal in it, it will be, especially if it THUNKS every time the relay picks up. If so, you could try this super simple delay circuit I designed in place of the transistor that drives the transformer relay. Remove the transistor, set the pot fully CCW and install this circuit in place of it. Bend the wires as shown so they will bend if bumped and not push the tracks off the main board, then, with the power set low, so the relay drops in & out, adjust the pot until the transformer just stops thunking. Then count the turns until it just starts again, and set the pot ½ way between. That will switch the transformer on in the middle of a ½ cycle when the magnetisation current would be crossing zero. 2N7000s have a Vth spread of .8-3V and I don't know what voltage the processor feeds out to the base resistor, so if you run out of adjustment, change the capacitor to .022uF. Let me know is it works. Cheers!
[](https://i.stack.imgur.com/IiAzG.png) |
63,598,072 | I have a deeply nested JSON document that is variable length and has variable arrays respective to the document, I am looking to unnest certain sections and write them to BigQuery, and disregard others.
I was excited about Dataprep by Trifacta but as they will be accessing the data, this will not work for my company. We work with healthcare data and only have authorized Google.
Has anyone worked with other solutions in GCP to transform JSONs? The nature of the document is so long and nested that writing a custom Regex and running it on a pod before ingestion is taking significant compute. | 2020/08/26 | [
"https://Stackoverflow.com/questions/63598072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12928451/"
] | You can try this:
**[1] Flatten the JSON document using `jq`:**
```
cat source.json | jq -c '.[]' > target.json
```
**[2] Load transformed JSON file (using `autodetect`):**
```
bq load --autodetect --source_format=NEWLINE_DELIMITED_JSON mydataset.mytable target.json
```
**Result:**
>
> BigQuery will automatically create RECORD (STRUCT) data type for nested data
>
>
> | [Dataflow](https://cloud.google.com/dataflow) can also be useful for this purpose:
* With this product you can create Apache Beam preprocessing pipelines that run only on Google servers.
* With Beam's [ParDo funcion](https://beam.apache.org/releases/javadoc/2.2.0/org/apache/beam/sdk/transforms/ParDo.html) you can apply any given function written in Java, Python or Go to your nested data.
* Here you have an [example](https://towardsdatascience.com/how-to-flatten-deeply-nested-json-objects-in-non-recursive-elegant-python-55f96533103d) on how to do it efficiently in Python. |
32,631,274 | ```
#!/usr/bin/env perl
use strict;
use warnings FATAL => qw ( all );
my ( $func, @list, $num );
$func = sub {
print $num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach $num ( @list ) {
$func->();
};
```
This piece of perl prints
```
undef
undef
undef
```
instead of
```
1
2
3
```
The `$func` routine can see `@list`, so why not `$num`? | 2015/09/17 | [
"https://Stackoverflow.com/questions/32631274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1717295/"
] | Because `foreach` loops implicitly localise their iterator variables.
See: [`perlsyn`](http://perldoc.perl.org/perlsyn.html#Foreach-Loops)
>
> The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only in a foreach loop.
>
>
>
But really - this doesn't come up often, because it's really bad form to do any sort of messing around with a loop iterator from outside. Narrow down your scope, and pass variables around to avoid bugs and troubleshooting pain. | Well, guess the reason is this, from the docs:
>
> The foreach loop iterates over a normal list value and sets the
> variable VAR to be each element of the list in turn. If the variable
> is preceded with the keyword my, then it is lexically scoped, and is
> therefore visible only within the loop. Otherwise, the variable is
> implicitly local to the loop and regains its former value upon exiting
> the loop. If the variable was previously declared with my, it uses
> that variable instead of the global one, but it's still localized to
> the loop. This implicit localization occurs only in a foreach loop.
>
>
>
which means I should not use the foreach loop i guess, but for or while .. |
32,631,274 | ```
#!/usr/bin/env perl
use strict;
use warnings FATAL => qw ( all );
my ( $func, @list, $num );
$func = sub {
print $num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach $num ( @list ) {
$func->();
};
```
This piece of perl prints
```
undef
undef
undef
```
instead of
```
1
2
3
```
The `$func` routine can see `@list`, so why not `$num`? | 2015/09/17 | [
"https://Stackoverflow.com/questions/32631274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1717295/"
] | Because `foreach` loops implicitly localise their iterator variables.
See: [`perlsyn`](http://perldoc.perl.org/perlsyn.html#Foreach-Loops)
>
> The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only in a foreach loop.
>
>
>
But really - this doesn't come up often, because it's really bad form to do any sort of messing around with a loop iterator from outside. Narrow down your scope, and pass variables around to avoid bugs and troubleshooting pain. | You are accessing a localized version of the `$num` variable, like Sobrique says. What you intended was to use a reference to the variable `$num`. Which is what I show here:
```
my ( $func, @list, $num );
$func = sub {
print $$num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach ( @list ) {
$num = \$_;
$func->();
};
```
You can also use the global version of the variable, instead of the lexical:
```
my ( $func, @list, $num );
$func = sub {
print $main::num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach $main::num ( @list ) {
$func->();
};
```
But this is a silly way to encapsulate this. You should not use global variables inside subroutines. This is not good practice. Instead, pass the value to the sub and access it via the `@_` variable (in this case by the first array index `$_[0]`):
```
my $func = sub {
print $_[0] // "undef"; print "\n";
};
my @list = ( 1,2,3 );
for ( @list ) {
$func->($_);
};
```
I also fixed some idiomatic coding style above. |
32,631,274 | ```
#!/usr/bin/env perl
use strict;
use warnings FATAL => qw ( all );
my ( $func, @list, $num );
$func = sub {
print $num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach $num ( @list ) {
$func->();
};
```
This piece of perl prints
```
undef
undef
undef
```
instead of
```
1
2
3
```
The `$func` routine can see `@list`, so why not `$num`? | 2015/09/17 | [
"https://Stackoverflow.com/questions/32631274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1717295/"
] | Because `foreach` loops implicitly localise their iterator variables.
See: [`perlsyn`](http://perldoc.perl.org/perlsyn.html#Foreach-Loops)
>
> The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only in a foreach loop.
>
>
>
But really - this doesn't come up often, because it's really bad form to do any sort of messing around with a loop iterator from outside. Narrow down your scope, and pass variables around to avoid bugs and troubleshooting pain. | I could quote perlsyn, but perlsyn does not appear to say clearly what is the case. The variable is not "localized", and there is nothing that "regains" its value upon exiting the loop. The outer variable is *hidden* when you declare the loop variable, and visible after you're out of the loop.
It implicitly *hides* the variable in the outer scope, which *retains* its value.
The output from this code scrap will illustrate:
```
use 5.022;
use strict;
use warnings FATAL => qw ( all );
use Data::Dumper;
my ( $func, @list, $num );
$func = sub {
print $num // "undef"; print "\n";
};
$num = 101;
$func->();
my $np = \$num;
print Data::Dumper->Dump( [ $np ], [ '*np' ] );
@list = ( 1,2,3 );
foreach $num ( @list ) {
print Data::Dumper->Dump( [ $num ], [ '*num' ] );
print Data::Dumper->Dump( [ $np ], [ '*np' ] );
my $np2 = \$num;
print Data::Dumper->Dump( [ $np2 ], [ '*np2' ] );
print Data::Dumper->Dump( [ $np ], [ '*np' ] );
$$np++;
$func->();
}
```
Which outputs this:
```
101
$np = \101;
$num = 1;
$np = \101;
$np2 = \1;
$np = \101;
102
$num = 2;
$np = \102;
$np2 = \2;
$np = \102;
103
$num = 3;
$np = \103;
$np2 = \3;
$np = \103;
104
```
Thus, inside the loop, the symbol `$num` simply does not refer to the memory pointed to by `$np`, but instead at the memory pointed to by `$np2`. |
32,631,274 | ```
#!/usr/bin/env perl
use strict;
use warnings FATAL => qw ( all );
my ( $func, @list, $num );
$func = sub {
print $num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach $num ( @list ) {
$func->();
};
```
This piece of perl prints
```
undef
undef
undef
```
instead of
```
1
2
3
```
The `$func` routine can see `@list`, so why not `$num`? | 2015/09/17 | [
"https://Stackoverflow.com/questions/32631274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1717295/"
] | You are accessing a localized version of the `$num` variable, like Sobrique says. What you intended was to use a reference to the variable `$num`. Which is what I show here:
```
my ( $func, @list, $num );
$func = sub {
print $$num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach ( @list ) {
$num = \$_;
$func->();
};
```
You can also use the global version of the variable, instead of the lexical:
```
my ( $func, @list, $num );
$func = sub {
print $main::num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach $main::num ( @list ) {
$func->();
};
```
But this is a silly way to encapsulate this. You should not use global variables inside subroutines. This is not good practice. Instead, pass the value to the sub and access it via the `@_` variable (in this case by the first array index `$_[0]`):
```
my $func = sub {
print $_[0] // "undef"; print "\n";
};
my @list = ( 1,2,3 );
for ( @list ) {
$func->($_);
};
```
I also fixed some idiomatic coding style above. | Well, guess the reason is this, from the docs:
>
> The foreach loop iterates over a normal list value and sets the
> variable VAR to be each element of the list in turn. If the variable
> is preceded with the keyword my, then it is lexically scoped, and is
> therefore visible only within the loop. Otherwise, the variable is
> implicitly local to the loop and regains its former value upon exiting
> the loop. If the variable was previously declared with my, it uses
> that variable instead of the global one, but it's still localized to
> the loop. This implicit localization occurs only in a foreach loop.
>
>
>
which means I should not use the foreach loop i guess, but for or while .. |
32,631,274 | ```
#!/usr/bin/env perl
use strict;
use warnings FATAL => qw ( all );
my ( $func, @list, $num );
$func = sub {
print $num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach $num ( @list ) {
$func->();
};
```
This piece of perl prints
```
undef
undef
undef
```
instead of
```
1
2
3
```
The `$func` routine can see `@list`, so why not `$num`? | 2015/09/17 | [
"https://Stackoverflow.com/questions/32631274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1717295/"
] | You are accessing a localized version of the `$num` variable, like Sobrique says. What you intended was to use a reference to the variable `$num`. Which is what I show here:
```
my ( $func, @list, $num );
$func = sub {
print $$num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach ( @list ) {
$num = \$_;
$func->();
};
```
You can also use the global version of the variable, instead of the lexical:
```
my ( $func, @list, $num );
$func = sub {
print $main::num // "undef"; print "\n";
};
@list = ( 1,2,3 );
foreach $main::num ( @list ) {
$func->();
};
```
But this is a silly way to encapsulate this. You should not use global variables inside subroutines. This is not good practice. Instead, pass the value to the sub and access it via the `@_` variable (in this case by the first array index `$_[0]`):
```
my $func = sub {
print $_[0] // "undef"; print "\n";
};
my @list = ( 1,2,3 );
for ( @list ) {
$func->($_);
};
```
I also fixed some idiomatic coding style above. | I could quote perlsyn, but perlsyn does not appear to say clearly what is the case. The variable is not "localized", and there is nothing that "regains" its value upon exiting the loop. The outer variable is *hidden* when you declare the loop variable, and visible after you're out of the loop.
It implicitly *hides* the variable in the outer scope, which *retains* its value.
The output from this code scrap will illustrate:
```
use 5.022;
use strict;
use warnings FATAL => qw ( all );
use Data::Dumper;
my ( $func, @list, $num );
$func = sub {
print $num // "undef"; print "\n";
};
$num = 101;
$func->();
my $np = \$num;
print Data::Dumper->Dump( [ $np ], [ '*np' ] );
@list = ( 1,2,3 );
foreach $num ( @list ) {
print Data::Dumper->Dump( [ $num ], [ '*num' ] );
print Data::Dumper->Dump( [ $np ], [ '*np' ] );
my $np2 = \$num;
print Data::Dumper->Dump( [ $np2 ], [ '*np2' ] );
print Data::Dumper->Dump( [ $np ], [ '*np' ] );
$$np++;
$func->();
}
```
Which outputs this:
```
101
$np = \101;
$num = 1;
$np = \101;
$np2 = \1;
$np = \101;
102
$num = 2;
$np = \102;
$np2 = \2;
$np = \102;
103
$num = 3;
$np = \103;
$np2 = \3;
$np = \103;
104
```
Thus, inside the loop, the symbol `$num` simply does not refer to the memory pointed to by `$np`, but instead at the memory pointed to by `$np2`. |
307,168 | Why I can't feel the actual speed of plane when the plane in the sky? I mean I cannot judge how fast the plane is going in terms of the light on the ground and I feel it is flying so slow. How can I explain this mismatch? | 2017/01/24 | [
"https://physics.stackexchange.com/questions/307168",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/118807/"
] | You do not feel speed, you only feel acceleration, or other forces, like those from the wind on your face - and you cannot feel that in a plane.
So you do feel something when the plane is accelerating, taking off, sometimes when it banks, or in bad weather.
But a plane's speed is typically steady, unchanging, for most of the trip.
When changes in the plane's motion occur they are relatively small (except for very bad weather, jet stream turbulence and the like ). The plane's motion is normally kept within reasonable acceleration rates for the precise reason to avoid passenger discomfort (and to avoid excessive stress on the airframe).
So you're in a system that's designed to minimize your sensation of motion.
As you're high up, you cannot see how fast the plane's ground speed is. The closer you are to a passing object, the faster you think you're going. You're not close to the ground so it almost drifts by.
A similar effect is why some people experience more fear when driving that others. They concentrate on the road surface near their car and it gives a greater impression of speed than the place they should be looking (further ahead). You might also notice it if you were on a skateboard and compared the sensation of speed when standing to that when kneeling.
The speed doesn't change, but your brain picks up different clues to motion and interprets them as different speeds. In a high flying plane there are no obvious speed clues so your brain can interpret that as not moving fast. | I believe it's an illusion that has to do more with cognitive science. The treatment of objects movements and the evaluation of their speed is done pretty unconsciously through different visual areas of the cortex. [Some people for example cannot perceive](https://en.wikipedia.org/wiki/Akinetopsia) motion even though they see perfectly well! This information is also completed by other sources of information that help us "feel" the speed like feeling the wind, vibrations, noise and eye movements.
So the feel of speed is not a rational process! Most likely it was developed to help us hunt or escape the attack of an animal. But not to judge the speed of an aircraft.
Then somehow all this information reaches [Speed cells](http://www.sciencemag.org/news/2015/07/speed-cells-brain-track-how-fast-animals-run) that among Place cells, Grid cells, Boundary cell and Head direction cells form the "human GPS system". When in a plane, all the information reaching the speed cells is biased and thinking rationally about our real speed can't really change the slow "feel" of our speed cells. Maybe a lot of training could help. One should ask test or fighter pilots if they feel the real speed.
People who vote your question down should get [a life.](https://www.cheaptickets.com/) |
203,057 | I just realized that both seems to mean the same thing. However, I am not sure if this is something that's context-dependent or not. What do you think?
For example:
>
> I pressed and used the buttons at the right time and in the right
> combination.
>
>
> I pressed and used the buttons at the right time and with the right
> combination.
>
>
> | 2019/03/30 | [
"https://ell.stackexchange.com/questions/203057",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/91596/"
] | Interesting question! I've never thought about this before.
This might depend on the individual and the dialect, so I will only be answering for myself and Australian English.
**In** a combination is used to describe a series of actions (for example, pressing buttons) being done in a particular order. The actions themselves are the combination.
>
> I pressed the buttons in the right combination.
>
>
>
**With** a combination is used to describe an action (for example, opening a lock) that needs to *use* a combination (a particular sequence). The action is not part of the combination.
>
> I opened the lock with the right combination.
>
>
>
So in your question, **"in the right combination" is correct.** | I suggest using *I pressed and used the buttons in combination with right time and right combination*. If you'd like to use *with the right combination* I think you should add *of sth* after combination, i.e. *with the right combination of sth* Please refer to [this post](https://english.stackexchange.com/questions/76954/difference-between-combination-of-and-combination-between) |
5,095,525 | After discovering jQuery a few years ago, I realized how easy it was to really make interactive and user friendly websites without writing books of code. As the projects increased in size, so did also the time required to carry out any debugging or perhaps implementing a change or new feature.
From reading various blogs and staying somewhat updated, I've read about libraries similar to [Backbone.js](http://documentcloud.github.com/backbone/) and [JavascriptMVC](http://www.javascriptmvc.com/) which both sound like good alternatives in order to make the code more modular and separated.
However as being far from an Javascript or jQuery expert, I am not really not suited to tell what's a good cornerstone in a project where future ease of maintainability, debugging and development are prioritized.
**So with this in mind - what's common sense when starting a project where Javascript and jQuery stands for the majority of the user experience and data presentation to the user?**
Thanks a lot | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198128/"
] | Check out this book, mainly chapter 10 <http://jqfundamentals.com/book/index.html#chapter-10> | My suggestion would be is to isolate as much javascript as possible into external js files, outside of your views, and simply reference them in the headers. Not only does this allow javascript re-use from page to page, but it separates your concerns on a fair level, spreading out your code to allow for easier debugging (easier by my beliefs anyway). In addition, this makes your js a little bit more secure as it is not rendered directly onto the browser page. Granted, that security is fairly negligible since tools like firebug or IE's Developer Tools can access layered away javascript files.
Second, I would suggest using a tool like unto compress.msbuild to (at final compile for deployment) compress all your custom-written javascript to whatevertheirnameis-min.js. Not only does compacting everything to a single line actually reduce load and run-times for your code, it also obfuscates it into more secure. It is significantly more difficult to take apart a -min file, much less find any specific functions when all the code is a single line. |
5,095,525 | After discovering jQuery a few years ago, I realized how easy it was to really make interactive and user friendly websites without writing books of code. As the projects increased in size, so did also the time required to carry out any debugging or perhaps implementing a change or new feature.
From reading various blogs and staying somewhat updated, I've read about libraries similar to [Backbone.js](http://documentcloud.github.com/backbone/) and [JavascriptMVC](http://www.javascriptmvc.com/) which both sound like good alternatives in order to make the code more modular and separated.
However as being far from an Javascript or jQuery expert, I am not really not suited to tell what's a good cornerstone in a project where future ease of maintainability, debugging and development are prioritized.
**So with this in mind - what's common sense when starting a project where Javascript and jQuery stands for the majority of the user experience and data presentation to the user?**
Thanks a lot | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198128/"
] | Both Backbone.js and JavascriptMVC are great examples of using a framework to organize large projects in a sane way ([SproutCore](http://www.sproutcore.com/) and [Cappuccino](http://cappuccino.org/) are nice too). I definitely suggest you choose a standard way of deal with data from the server, handling events from the DOM and responses from the sever, and view creation. Otherwise it can be a maintenance nightmare.
Beyond an MVC framework, you should probably choose a solution for these problems:
* Dependency management: how will you compile and load javascript files in the right order? My suggestion would be [RequireJS](http://requirejs.org/).
* Testing: testing UI code is never easy but the guys over at jQuery have been doing for a while and their testing tool [QUnit](http://docs.jquery.com/Qunit) is well documented/tested.
* Minification: you'll want to minify your code before deploying to production RequireJS has this built in but you could also use the [Closure Compiler](http://code.google.com/closure/compiler/) if you want to get crazy small source.
* Build System: All these tools are great but you should pull them all together in one master build system so you can run a simple command on the commandline and have you debug or production application. The specific tool to use depends on your language of choice - Ruby => [Rake](http://rake.rubyforge.org/), Python -> Write your own, **NodeJS** as a build tool (i like this option the most) -> [Jake](https://github.com/jcoglan/jake)
Beyond that just be aware if something feels clunky or slow (either tooling or framework) and refactor. | Check out this book, mainly chapter 10 <http://jqfundamentals.com/book/index.html#chapter-10> |
5,095,525 | After discovering jQuery a few years ago, I realized how easy it was to really make interactive and user friendly websites without writing books of code. As the projects increased in size, so did also the time required to carry out any debugging or perhaps implementing a change or new feature.
From reading various blogs and staying somewhat updated, I've read about libraries similar to [Backbone.js](http://documentcloud.github.com/backbone/) and [JavascriptMVC](http://www.javascriptmvc.com/) which both sound like good alternatives in order to make the code more modular and separated.
However as being far from an Javascript or jQuery expert, I am not really not suited to tell what's a good cornerstone in a project where future ease of maintainability, debugging and development are prioritized.
**So with this in mind - what's common sense when starting a project where Javascript and jQuery stands for the majority of the user experience and data presentation to the user?**
Thanks a lot | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198128/"
] | Both Backbone.js and JavascriptMVC are great examples of using a framework to organize large projects in a sane way ([SproutCore](http://www.sproutcore.com/) and [Cappuccino](http://cappuccino.org/) are nice too). I definitely suggest you choose a standard way of deal with data from the server, handling events from the DOM and responses from the sever, and view creation. Otherwise it can be a maintenance nightmare.
Beyond an MVC framework, you should probably choose a solution for these problems:
* Dependency management: how will you compile and load javascript files in the right order? My suggestion would be [RequireJS](http://requirejs.org/).
* Testing: testing UI code is never easy but the guys over at jQuery have been doing for a while and their testing tool [QUnit](http://docs.jquery.com/Qunit) is well documented/tested.
* Minification: you'll want to minify your code before deploying to production RequireJS has this built in but you could also use the [Closure Compiler](http://code.google.com/closure/compiler/) if you want to get crazy small source.
* Build System: All these tools are great but you should pull them all together in one master build system so you can run a simple command on the commandline and have you debug or production application. The specific tool to use depends on your language of choice - Ruby => [Rake](http://rake.rubyforge.org/), Python -> Write your own, **NodeJS** as a build tool (i like this option the most) -> [Jake](https://github.com/jcoglan/jake)
Beyond that just be aware if something feels clunky or slow (either tooling or framework) and refactor. | My suggestion would be is to isolate as much javascript as possible into external js files, outside of your views, and simply reference them in the headers. Not only does this allow javascript re-use from page to page, but it separates your concerns on a fair level, spreading out your code to allow for easier debugging (easier by my beliefs anyway). In addition, this makes your js a little bit more secure as it is not rendered directly onto the browser page. Granted, that security is fairly negligible since tools like firebug or IE's Developer Tools can access layered away javascript files.
Second, I would suggest using a tool like unto compress.msbuild to (at final compile for deployment) compress all your custom-written javascript to whatevertheirnameis-min.js. Not only does compacting everything to a single line actually reduce load and run-times for your code, it also obfuscates it into more secure. It is significantly more difficult to take apart a -min file, much less find any specific functions when all the code is a single line. |
5,095,525 | After discovering jQuery a few years ago, I realized how easy it was to really make interactive and user friendly websites without writing books of code. As the projects increased in size, so did also the time required to carry out any debugging or perhaps implementing a change or new feature.
From reading various blogs and staying somewhat updated, I've read about libraries similar to [Backbone.js](http://documentcloud.github.com/backbone/) and [JavascriptMVC](http://www.javascriptmvc.com/) which both sound like good alternatives in order to make the code more modular and separated.
However as being far from an Javascript or jQuery expert, I am not really not suited to tell what's a good cornerstone in a project where future ease of maintainability, debugging and development are prioritized.
**So with this in mind - what's common sense when starting a project where Javascript and jQuery stands for the majority of the user experience and data presentation to the user?**
Thanks a lot | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198128/"
] | I would like to recommend using javascript in a functional style which can be helped by abstractions like [coffeescript](http://jashkenas.github.com/coffee-script/) and [underscore.js](http://documentcloud.github.com/underscore/).
Also minimising the cross module interaction and relying on an event driven code is a great way to keep your entire project organized. I defiantly like the way that [backbone.js](http://documentcloud.github.com/backbone/) handles the module-view weak coupling by having view's bind the change events on modules.
Functional event based code is great for macro structure. I would also advice coupling javascript to the DOM. (Again [backbone.js](http://documentcloud.github.com/backbone/) has a great example of how the model is completely dom independant and even the views aren't dependant on the dom. For all you care the views could be shooting data down a WebSocket)
I'm personally also a fan of having one central file manager rather then having a complicated require/include structure on every page. Load javascript modules from your central loader based on a page by page feature detection. (See here for an [example](https://stackoverflow.com/questions/5083409/pattern-for-javascript-module-pattern-and-sub-module-initialization/5083571#5083571) of a central file manager).
I would also like to advocate the growing possibility of good re-use through [node.js](http://nodejs.org/). There are quite a few people working on porting browser code verbatim to node.js or copying node.js code verbatim to the browser. (see [YUI3 running on nodejs](http://www.yuiblog.com/blog/2010/09/29/video-glass-node/), [node.js in the browser](https://github.com/Marak/gemini.js), [commonJS in the browser](https://github.com/Raynos/BrowserCJS) Admittedly most of these are WIP and not stable.) | My suggestion would be is to isolate as much javascript as possible into external js files, outside of your views, and simply reference them in the headers. Not only does this allow javascript re-use from page to page, but it separates your concerns on a fair level, spreading out your code to allow for easier debugging (easier by my beliefs anyway). In addition, this makes your js a little bit more secure as it is not rendered directly onto the browser page. Granted, that security is fairly negligible since tools like firebug or IE's Developer Tools can access layered away javascript files.
Second, I would suggest using a tool like unto compress.msbuild to (at final compile for deployment) compress all your custom-written javascript to whatevertheirnameis-min.js. Not only does compacting everything to a single line actually reduce load and run-times for your code, it also obfuscates it into more secure. It is significantly more difficult to take apart a -min file, much less find any specific functions when all the code is a single line. |
5,095,525 | After discovering jQuery a few years ago, I realized how easy it was to really make interactive and user friendly websites without writing books of code. As the projects increased in size, so did also the time required to carry out any debugging or perhaps implementing a change or new feature.
From reading various blogs and staying somewhat updated, I've read about libraries similar to [Backbone.js](http://documentcloud.github.com/backbone/) and [JavascriptMVC](http://www.javascriptmvc.com/) which both sound like good alternatives in order to make the code more modular and separated.
However as being far from an Javascript or jQuery expert, I am not really not suited to tell what's a good cornerstone in a project where future ease of maintainability, debugging and development are prioritized.
**So with this in mind - what's common sense when starting a project where Javascript and jQuery stands for the majority of the user experience and data presentation to the user?**
Thanks a lot | 2011/02/23 | [
"https://Stackoverflow.com/questions/5095525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198128/"
] | Both Backbone.js and JavascriptMVC are great examples of using a framework to organize large projects in a sane way ([SproutCore](http://www.sproutcore.com/) and [Cappuccino](http://cappuccino.org/) are nice too). I definitely suggest you choose a standard way of deal with data from the server, handling events from the DOM and responses from the sever, and view creation. Otherwise it can be a maintenance nightmare.
Beyond an MVC framework, you should probably choose a solution for these problems:
* Dependency management: how will you compile and load javascript files in the right order? My suggestion would be [RequireJS](http://requirejs.org/).
* Testing: testing UI code is never easy but the guys over at jQuery have been doing for a while and their testing tool [QUnit](http://docs.jquery.com/Qunit) is well documented/tested.
* Minification: you'll want to minify your code before deploying to production RequireJS has this built in but you could also use the [Closure Compiler](http://code.google.com/closure/compiler/) if you want to get crazy small source.
* Build System: All these tools are great but you should pull them all together in one master build system so you can run a simple command on the commandline and have you debug or production application. The specific tool to use depends on your language of choice - Ruby => [Rake](http://rake.rubyforge.org/), Python -> Write your own, **NodeJS** as a build tool (i like this option the most) -> [Jake](https://github.com/jcoglan/jake)
Beyond that just be aware if something feels clunky or slow (either tooling or framework) and refactor. | I would like to recommend using javascript in a functional style which can be helped by abstractions like [coffeescript](http://jashkenas.github.com/coffee-script/) and [underscore.js](http://documentcloud.github.com/underscore/).
Also minimising the cross module interaction and relying on an event driven code is a great way to keep your entire project organized. I defiantly like the way that [backbone.js](http://documentcloud.github.com/backbone/) handles the module-view weak coupling by having view's bind the change events on modules.
Functional event based code is great for macro structure. I would also advice coupling javascript to the DOM. (Again [backbone.js](http://documentcloud.github.com/backbone/) has a great example of how the model is completely dom independant and even the views aren't dependant on the dom. For all you care the views could be shooting data down a WebSocket)
I'm personally also a fan of having one central file manager rather then having a complicated require/include structure on every page. Load javascript modules from your central loader based on a page by page feature detection. (See here for an [example](https://stackoverflow.com/questions/5083409/pattern-for-javascript-module-pattern-and-sub-module-initialization/5083571#5083571) of a central file manager).
I would also like to advocate the growing possibility of good re-use through [node.js](http://nodejs.org/). There are quite a few people working on porting browser code verbatim to node.js or copying node.js code verbatim to the browser. (see [YUI3 running on nodejs](http://www.yuiblog.com/blog/2010/09/29/video-glass-node/), [node.js in the browser](https://github.com/Marak/gemini.js), [commonJS in the browser](https://github.com/Raynos/BrowserCJS) Admittedly most of these are WIP and not stable.) |
71,084,990 | I have this question and I haven't found specific documentation to confirm the behavior and am unaware of how to manually check this myself.
Consider I have table A with b\_id foreign key to table B. If I run an update on a row in table A, does mysql always run the foreign key constraint check on table B even if A's b\_id goes unchanged or isn't passed in the update statement? such as `(select 1 from B where id = ?)`
Example:
`UPDATE A set A.name = "x", A.b_id = 1 where A.id = 1` I know this runs the foreign key check on B
`UPDATE A set A.name = "x" where A.id = 1` But does this also run the foreign key check even though b\_id goes unchanged since it was not passed?
`UPDATE A set A.name = "x" A.b_id = A.b_id where A.id = 1` And what about this? b\_id gets passed in with same existing value. Does the fk check run?
Any supporting documentation or help would be appreciated, as well as tips on how I can test this sort of behavior myself since using EXPLAIN doesn't help.
Edit: this is for INNODB engine and mysql 8.0 | 2022/02/11 | [
"https://Stackoverflow.com/questions/71084990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3509128/"
] | Foreign key integrity is checked always when the server detects that the data is changed by fact and needs in save to the disk. It is checked after all BEFORE UPDATE triggers execution (rather than data type check which is performed each time, before and after each separate trigger).
The reason is simple. Server does not store any flag which marks does the value is changed - it is more expensive than direct compare before real, physical, UPDATE execution. The value changing is not tracked. Server does not know does the value to be saved during the update is provided by the query text or, for example, is provided by one of the BEFORE UPDATE triggers in the trigger chain.
[small DEMO](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=94451d3db69ecf964d682c81ad0e565a) | When you add a foreign key constraint, [MySQL requires an index](https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html):
>
> MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created.
>
>
>
To clarify, this is an index in the referencing table (in your example A), not the referenced table (in your example B). The index in table B you have to provide yourself, otherwise you will get an error message.
Given this index, the answer to your question can be summarized to:
**The foreign key constraint will be verified (e.g. the check if the row exists in the referenced table) whenever this index will be modified.**
Since it may not be completely obvious when this happens, some examples: for a sample table of
```
CREATE TABLE A (id int primary key, b_id int, c int,
FOREIGN KEY (b_id) REFERENCES B(id))
```
the foreign key (e.g. if the value exists in the referenced table B) is checked for (assuming that such a row exists):
```
update A set id = 2 where id = 1
```
as it modifies the primary key, which is part of every index, so that hidden index gets modified, thus the verification will be executed, and
```
update A set b_id = 3 where b_id = 2
```
as it modifies the column b\_id, which is part of the hidden index, so that hidden index gets modified.
It does NOT get checked for
```
update A set id = 2 where id = 2
update A set b_id = 3 where b_id = 3
update A set b_id = b_id
```
as those do not modify the index content (because nothing changes).
Notably
```
update A set c = 2 where c = 3
```
also does not modify the index (as c is not part of the index), so the foreign key constraint is not verified even though the row itself changes.
To make things a bit more complicated, you can use your own index:
```
CREATE TABLE A (id int primary key, b_id int, c int,
INDEX b_c (b_id, c),
FOREIGN KEY (b_id) REFERENCES B(id))
```
If you do that, MySQL can use this index for your foreign key and doesn't have to add its own hidden index. The effects of the updates mentioned above will not change, except for
```
update A set c = 2 where c = 3
```
as now, c is a column of the index that MySQL uses for the foreign key constraint, abd this update requires a modification of the index content - and thus triggers a verification. This is actually a verification that logically would not be required - it just happens because of how MySQL implemented it. So if you really want to prevent every unnecessary check, you could add an index on just column `b_id` yourself, then MySQL won't use the index on `(b_id, c)`. But that would be extreme micro-optimization and you really should not do it just for this.
Please note that, while this may be an interesting technical detail to know, it should not have any impact on what you actually do with the database. You should not write your queries differently with that knowledge. If you need to update a row, you have to update the row. Also, adding an index just to prevent a check will most certainly not help. Also, since the behaviour is not specified, it can also change at any time (e.g. by you if you find and implement a better solution). |
4,919,437 | Does `dbms_output.put_line` decrease the performance in `plsql` code? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4919437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606147/"
] | I use a log table instead of dbms\_output. Make sure to setup as autonomous transaction, something like (modify for your needs of course):
```
create or replace package body somePackage as
...
procedure ins_log(
i_msg in varchar2,
i_msg_type in varchar2,
i_msg_code in number default 0,
i_msg_context in varchar2 default null
) IS PRAGMA AUTONOMOUS_TRANSACTION;
begin
insert into myLogTable
(
created_date,
msg,
msg_type,
msg_code,
msg_context
)
values
(
sysdate,
i_msg,
i_msg_type,
i_msg_code,
i_msg_context
);
commit;
end ins_log;
...
end;
```
Make sure you create your log table of course. In your code, if you're doing many operations in a loop, you may want to only log once per x num operations, something like:
```
create or replace myProcedure as
cursor some_cursor is
select * from someTable;
v_ctr pls_integer := 0;
begin
for rec in some_cursor
loop
v_ctr := v_ctr + 1;
-- do something interesting
if (mod(v_ctr, 1000) = 0) then
somePackage.ins_log('Inserted ' || v_ctr || ' records',
'Log',
i_msg_context=>'myProcedure');
end if;
end loop;
commit;
exception
when others then
somePackage.ins_log(SQLERRM, 'Err', i_msg_context=>'myProcedure');
rollback;
raise;
end;
```
Note that the autonomous transaction will ensure that your log stmt gets inserted, even if an error occurs and you rollback everything else (since its a separate transaction).
Hope this helps...much better than dbms\_output ;) | It depends on the ratio of how many times you call `dbms_output.put_line` versus what else you do in PL/SQL. |
4,919,437 | Does `dbms_output.put_line` decrease the performance in `plsql` code? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4919437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606147/"
] | Yes, it's another piece of code that needs to be executed, but unless the output is actually turned on, I think the overhead is quite minimal.
Here's an AskTom question with more details: [Is there a performance impact for dbms\_output.put\_line statements left in packages?](http://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:1468572900346293780) | You can look into [conditional compilation](http://www.oracle-base.com/articles/10g/ConditionalCompilation_10gR2.php) so that the DBMS\_OUTPUT.PUT\_LINE are only in the pre-parsed code if the procedure is compiled with the appropriate option.
One question is, has DBMS\_OUTPUT.ENABLE been called.
If so, any value in a DBMS\_OUTPUT.PUT\_LINE will be recorded in the session's memory structure. If you continue pushing stuff in there and never taking it out (which might be the case with some application server connections) you might find that after a few days you have a LOT of stuff in memory. |
4,919,437 | Does `dbms_output.put_line` decrease the performance in `plsql` code? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4919437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606147/"
] | Yes, it's another piece of code that needs to be executed, but unless the output is actually turned on, I think the overhead is quite minimal.
Here's an AskTom question with more details: [Is there a performance impact for dbms\_output.put\_line statements left in packages?](http://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:1468572900346293780) | Using DMBS\_OUTPUT might also be the cause of the following error:
ORA-04036: PGA memory used by the instance exceeds PGA\_AGGREGATE\_LIMIT |
4,919,437 | Does `dbms_output.put_line` decrease the performance in `plsql` code? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4919437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606147/"
] | You can look into [conditional compilation](http://www.oracle-base.com/articles/10g/ConditionalCompilation_10gR2.php) so that the DBMS\_OUTPUT.PUT\_LINE are only in the pre-parsed code if the procedure is compiled with the appropriate option.
One question is, has DBMS\_OUTPUT.ENABLE been called.
If so, any value in a DBMS\_OUTPUT.PUT\_LINE will be recorded in the session's memory structure. If you continue pushing stuff in there and never taking it out (which might be the case with some application server connections) you might find that after a few days you have a LOT of stuff in memory. | It depends on the ratio of how many times you call `dbms_output.put_line` versus what else you do in PL/SQL. |
4,919,437 | Does `dbms_output.put_line` decrease the performance in `plsql` code? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4919437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606147/"
] | *Every* extra line of code decreases the performance of code. After all, it is an extra instruction to be executed, which at least consumes some CPU. So yes, dbms\_output.put\_line decreases the performance.
The real question is: does the benefit of this extra line of code outweigh the performance penalty? Only you can answer that question.
Regards,
Rob. | I use a log table instead of dbms\_output. Make sure to setup as autonomous transaction, something like (modify for your needs of course):
```
create or replace package body somePackage as
...
procedure ins_log(
i_msg in varchar2,
i_msg_type in varchar2,
i_msg_code in number default 0,
i_msg_context in varchar2 default null
) IS PRAGMA AUTONOMOUS_TRANSACTION;
begin
insert into myLogTable
(
created_date,
msg,
msg_type,
msg_code,
msg_context
)
values
(
sysdate,
i_msg,
i_msg_type,
i_msg_code,
i_msg_context
);
commit;
end ins_log;
...
end;
```
Make sure you create your log table of course. In your code, if you're doing many operations in a loop, you may want to only log once per x num operations, something like:
```
create or replace myProcedure as
cursor some_cursor is
select * from someTable;
v_ctr pls_integer := 0;
begin
for rec in some_cursor
loop
v_ctr := v_ctr + 1;
-- do something interesting
if (mod(v_ctr, 1000) = 0) then
somePackage.ins_log('Inserted ' || v_ctr || ' records',
'Log',
i_msg_context=>'myProcedure');
end if;
end loop;
commit;
exception
when others then
somePackage.ins_log(SQLERRM, 'Err', i_msg_context=>'myProcedure');
rollback;
raise;
end;
```
Note that the autonomous transaction will ensure that your log stmt gets inserted, even if an error occurs and you rollback everything else (since its a separate transaction).
Hope this helps...much better than dbms\_output ;) |
4,919,437 | Does `dbms_output.put_line` decrease the performance in `plsql` code? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4919437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606147/"
] | Yes, it's another piece of code that needs to be executed, but unless the output is actually turned on, I think the overhead is quite minimal.
Here's an AskTom question with more details: [Is there a performance impact for dbms\_output.put\_line statements left in packages?](http://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:1468572900346293780) | It depends on the ratio of how many times you call `dbms_output.put_line` versus what else you do in PL/SQL. |
4,919,437 | Does `dbms_output.put_line` decrease the performance in `plsql` code? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4919437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606147/"
] | You can look into [conditional compilation](http://www.oracle-base.com/articles/10g/ConditionalCompilation_10gR2.php) so that the DBMS\_OUTPUT.PUT\_LINE are only in the pre-parsed code if the procedure is compiled with the appropriate option.
One question is, has DBMS\_OUTPUT.ENABLE been called.
If so, any value in a DBMS\_OUTPUT.PUT\_LINE will be recorded in the session's memory structure. If you continue pushing stuff in there and never taking it out (which might be the case with some application server connections) you might find that after a few days you have a LOT of stuff in memory. | Using DMBS\_OUTPUT might also be the cause of the following error:
ORA-04036: PGA memory used by the instance exceeds PGA\_AGGREGATE\_LIMIT |
4,919,437 | Does `dbms_output.put_line` decrease the performance in `plsql` code? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4919437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606147/"
] | I use a log table instead of dbms\_output. Make sure to setup as autonomous transaction, something like (modify for your needs of course):
```
create or replace package body somePackage as
...
procedure ins_log(
i_msg in varchar2,
i_msg_type in varchar2,
i_msg_code in number default 0,
i_msg_context in varchar2 default null
) IS PRAGMA AUTONOMOUS_TRANSACTION;
begin
insert into myLogTable
(
created_date,
msg,
msg_type,
msg_code,
msg_context
)
values
(
sysdate,
i_msg,
i_msg_type,
i_msg_code,
i_msg_context
);
commit;
end ins_log;
...
end;
```
Make sure you create your log table of course. In your code, if you're doing many operations in a loop, you may want to only log once per x num operations, something like:
```
create or replace myProcedure as
cursor some_cursor is
select * from someTable;
v_ctr pls_integer := 0;
begin
for rec in some_cursor
loop
v_ctr := v_ctr + 1;
-- do something interesting
if (mod(v_ctr, 1000) = 0) then
somePackage.ins_log('Inserted ' || v_ctr || ' records',
'Log',
i_msg_context=>'myProcedure');
end if;
end loop;
commit;
exception
when others then
somePackage.ins_log(SQLERRM, 'Err', i_msg_context=>'myProcedure');
rollback;
raise;
end;
```
Note that the autonomous transaction will ensure that your log stmt gets inserted, even if an error occurs and you rollback everything else (since its a separate transaction).
Hope this helps...much better than dbms\_output ;) | Using DMBS\_OUTPUT might also be the cause of the following error:
ORA-04036: PGA memory used by the instance exceeds PGA\_AGGREGATE\_LIMIT |
4,919,437 | Does `dbms_output.put_line` decrease the performance in `plsql` code? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4919437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606147/"
] | *Every* extra line of code decreases the performance of code. After all, it is an extra instruction to be executed, which at least consumes some CPU. So yes, dbms\_output.put\_line decreases the performance.
The real question is: does the benefit of this extra line of code outweigh the performance penalty? Only you can answer that question.
Regards,
Rob. | Using DMBS\_OUTPUT might also be the cause of the following error:
ORA-04036: PGA memory used by the instance exceeds PGA\_AGGREGATE\_LIMIT |
4,919,437 | Does `dbms_output.put_line` decrease the performance in `plsql` code? | 2011/02/07 | [
"https://Stackoverflow.com/questions/4919437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606147/"
] | Yes, it's another piece of code that needs to be executed, but unless the output is actually turned on, I think the overhead is quite minimal.
Here's an AskTom question with more details: [Is there a performance impact for dbms\_output.put\_line statements left in packages?](http://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:1468572900346293780) | I use a log table instead of dbms\_output. Make sure to setup as autonomous transaction, something like (modify for your needs of course):
```
create or replace package body somePackage as
...
procedure ins_log(
i_msg in varchar2,
i_msg_type in varchar2,
i_msg_code in number default 0,
i_msg_context in varchar2 default null
) IS PRAGMA AUTONOMOUS_TRANSACTION;
begin
insert into myLogTable
(
created_date,
msg,
msg_type,
msg_code,
msg_context
)
values
(
sysdate,
i_msg,
i_msg_type,
i_msg_code,
i_msg_context
);
commit;
end ins_log;
...
end;
```
Make sure you create your log table of course. In your code, if you're doing many operations in a loop, you may want to only log once per x num operations, something like:
```
create or replace myProcedure as
cursor some_cursor is
select * from someTable;
v_ctr pls_integer := 0;
begin
for rec in some_cursor
loop
v_ctr := v_ctr + 1;
-- do something interesting
if (mod(v_ctr, 1000) = 0) then
somePackage.ins_log('Inserted ' || v_ctr || ' records',
'Log',
i_msg_context=>'myProcedure');
end if;
end loop;
commit;
exception
when others then
somePackage.ins_log(SQLERRM, 'Err', i_msg_context=>'myProcedure');
rollback;
raise;
end;
```
Note that the autonomous transaction will ensure that your log stmt gets inserted, even if an error occurs and you rollback everything else (since its a separate transaction).
Hope this helps...much better than dbms\_output ;) |
72,038,470 | WHy does the value of `calendar.SelectedDate` include a time (eg.: 22-04-2022 00:00:00) when the user has picked a date?
In fact, I am interested in picking both a date and time but apparently, from what I've read, it seems like you can't pick a time from the calendar element in the program UI and I don't understand why when it also returns time in the value of `Selected.Date`
Is there an option to extend the calendar element to also include a timer-picker that isn't too complicated?
Code that that that returns returns `dd-mm-yyyy 00:00:00`
```
{
post.date = calendar.SelectedDate.ToString();
DateLabel.Content = $"Date and time for post: {post.date}";
}
``` | 2022/04/28 | [
"https://Stackoverflow.com/questions/72038470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18750341/"
] | WPF calendar has the default DateTime property. Neither only Date nor only Time it has `Nullable<DateTime>` default property, so it always along with Time. You would avoid it by setting below code
```
post.date = calendar.SelectedDate.Value.Date.ToShortDateString();
``` | >
> WHy does the value of calendar.SelectedDate include a time (eg.: 22-04-2022 00:00:00) when the user has picked a date?
>
>
>
Simply because there is no date-only data type available in .NET and the `Calendar` control uses the `DateTime` type to store the selected date. That's why.
>
> it seems like you can't pick a time from the calendar element in the program UI
>
>
>
Correct.
>
> Is there an option to extend the calendar element to also include a timer-picker that isn't too complicated?
>
>
>
No. |
72,038,470 | WHy does the value of `calendar.SelectedDate` include a time (eg.: 22-04-2022 00:00:00) when the user has picked a date?
In fact, I am interested in picking both a date and time but apparently, from what I've read, it seems like you can't pick a time from the calendar element in the program UI and I don't understand why when it also returns time in the value of `Selected.Date`
Is there an option to extend the calendar element to also include a timer-picker that isn't too complicated?
Code that that that returns returns `dd-mm-yyyy 00:00:00`
```
{
post.date = calendar.SelectedDate.ToString();
DateLabel.Content = $"Date and time for post: {post.date}";
}
``` | 2022/04/28 | [
"https://Stackoverflow.com/questions/72038470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18750341/"
] | DateTime.toString() support formatting the date and time and this can be use to get only date not time as shown in the below code.
```
post.date = calendar.sele.ToString("dd-MMM-yyyy");
DateLabel.Content = $"Date and time for post: {post.date}";
``` | >
> WHy does the value of calendar.SelectedDate include a time (eg.: 22-04-2022 00:00:00) when the user has picked a date?
>
>
>
Simply because there is no date-only data type available in .NET and the `Calendar` control uses the `DateTime` type to store the selected date. That's why.
>
> it seems like you can't pick a time from the calendar element in the program UI
>
>
>
Correct.
>
> Is there an option to extend the calendar element to also include a timer-picker that isn't too complicated?
>
>
>
No. |
46,117,380 | I have an express app that I start in terminal with following command to enable debug logs in it:
```
DEBUG=custom:* npm start (on Ubuntu)
SET DEBUG=custom:* & npm start (on Windows)
```
On production server, I start app with PM2 using following command:
```
pm2 start bin/www -i 0
```
But this does not enable the `debug` logs in my code, so the debug statements are not added to the logs, only `console.error()` are added to the log files. How can I pass the `DEBUG=custom:*` option while starting my app with PM2? | 2017/09/08 | [
"https://Stackoverflow.com/questions/46117380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3801947/"
] | You can parse it yourself with a function, here's an example:
```
function getTextWithInputValues(id) {
var element = document.getElementById(id);
if (!element) {
return null;
}
var elementText = element.innerHTML; // Get the entire text from your element
var elementInputs = element.getElementsByTagName('input'); // fetch all inputs from your element
// replace all input fields with their respective values
Object.getOwnPropertyNames(elementInputs).forEach(
(input) => {
var inputText = elementInputs[input].outerHTML;
if (elementText.search(inputText) > 0) {
elementText = elementText.replace(inputText, elementInputs[input].value);
}
}
);
return elementText;
}
```
You can test it right here by opening a console, paste this code in, then type in something in the search box on the top of the page (don't click search, just type in something), then when you call the function in the console like `getTextWithInputValues('search')` it will output something like
```
<svg ......</svg>
your-text-here
<button .....</button>
```
Hope this helps. | Even though you asked for `REGEX`, I don't believe it is by any means needed.
This will return the data in an array. With the first index being the body text, and each input field value thereafter.
```
var values = [];
values.push($('#body').text());
var inputs = $('#body input');
for(var i = 0; i < $(inputs).length; i++)
{
var currentElement = $(inputs)[i];
values.push($(currentElement).val());
}
console.log(values);
``` |
25,349,941 | I'm struggling for about 3 hours for now to fasten my Project Euler #12 code. I achieved to save a few seconds for the case that numbers has over 130 divisors, my first program went to 2.33 seconds now it does it in 1.169 seconds. However I never had the patience to wait for the 500 divisors number. How can I fasten my code? I tried the case to get the divisors from n and n+1 but it just slowed my program even more... Here is my code.
```
static bool isPrime(int num) {
if (num % 2 == 0 && num != 2)
return false;
else
for (int i = num; i < Math.Sqrt(num) + 1; i++) {
if (num % i == 0)
return false;
}
return true;
}
static void Main(string[] args) {
Stopwatch time = new Stopwatch();
time.Start();
int trianglenumber = 0;
int divizori = 0;
for (int i = 3; i < Int32.MaxValue; i+=2) {
if (isPrime(i) != false) {
int tempnumber = 0;
tempnumber = (i * (1 + i)) / 2;
for (int k = 1; k < tempnumber + 1; k++) {
if (tempnumber % k == 0) {
divizori++;
}
}
if (500 < divizori) {
trianglenumber = tempnumber;
break;
}
divizori = 0;
}
}
time.Stop();
double timp = time.ElapsedMilliseconds ;
Console.WriteLine(trianglenumber);
Console.Write("Runtime: " + timp/1000 + " seconds");
Console.ReadKey();
}
``` | 2014/08/17 | [
"https://Stackoverflow.com/questions/25349941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3899440/"
] | The **big** slow down is in your isPrime() method.
Take a look at counting factors by prime factorization. You'll see that counting 500 factors is MUCH quicker this way.
<http://www.mathsisfun.com/prime-factorization.html>
Also, how you're getting your triangular numbers should be much simpler.
```
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
```
Notice the difference between each sequential set of numbers....
1 + **2** = 3
3 + **3** = 6
6 + **4** = 10
10+ **5** = 15
15+ **6** = 21
and so on...take a look at that middle number.
Just for reference, my version of this using the prime factorization method takes roughly 6ms to find the answer....pretty quick. | Some Python functions around this question. It uses [Counters](https://docs.python.org/2/library/collections.html#collections.Counter), the perfect
high level tool to do that. Hope this can help you to find the keys enhancements.
```
from collections import Counter
def factors(n):
divisor=2
while divisor*divisor<=n:
if n%divisor==0:
return Counter({divisor:1})+factors(n//divisor)
divisor += 1
return Counter({n:1}) # prime number
def nbdiv(factors):
p=1
for factor in factors : p *= factors[factor]+1
return p
def nbdivtri(n):
a,b=n,n+1
if a%2==0 : a//=2
else: b//=2
return nbdiv(factors(a)+factors(b))
``` |
25,349,941 | I'm struggling for about 3 hours for now to fasten my Project Euler #12 code. I achieved to save a few seconds for the case that numbers has over 130 divisors, my first program went to 2.33 seconds now it does it in 1.169 seconds. However I never had the patience to wait for the 500 divisors number. How can I fasten my code? I tried the case to get the divisors from n and n+1 but it just slowed my program even more... Here is my code.
```
static bool isPrime(int num) {
if (num % 2 == 0 && num != 2)
return false;
else
for (int i = num; i < Math.Sqrt(num) + 1; i++) {
if (num % i == 0)
return false;
}
return true;
}
static void Main(string[] args) {
Stopwatch time = new Stopwatch();
time.Start();
int trianglenumber = 0;
int divizori = 0;
for (int i = 3; i < Int32.MaxValue; i+=2) {
if (isPrime(i) != false) {
int tempnumber = 0;
tempnumber = (i * (1 + i)) / 2;
for (int k = 1; k < tempnumber + 1; k++) {
if (tempnumber % k == 0) {
divizori++;
}
}
if (500 < divizori) {
trianglenumber = tempnumber;
break;
}
divizori = 0;
}
}
time.Stop();
double timp = time.ElapsedMilliseconds ;
Console.WriteLine(trianglenumber);
Console.Write("Runtime: " + timp/1000 + " seconds");
Console.ReadKey();
}
``` | 2014/08/17 | [
"https://Stackoverflow.com/questions/25349941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3899440/"
] | The **big** slow down is in your isPrime() method.
Take a look at counting factors by prime factorization. You'll see that counting 500 factors is MUCH quicker this way.
<http://www.mathsisfun.com/prime-factorization.html>
Also, how you're getting your triangular numbers should be much simpler.
```
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
```
Notice the difference between each sequential set of numbers....
1 + **2** = 3
3 + **3** = 6
6 + **4** = 10
10+ **5** = 15
15+ **6** = 21
and so on...take a look at that middle number.
Just for reference, my version of this using the prime factorization method takes roughly 6ms to find the answer....pretty quick. | I solved this question using a Greedy algorithm less than 0.187 ms.
```
static void Main(string[] args)
{
// 76576500
long age = 10000;
double alpha = 1.5;
double betta = 0.1;
Random ran = new Random();
long mmm = long.MaxValue;
double RR = 0;
var a = DateTime.Now;
for (int i = 0; i < 5000; i++)
{
long N = age * (age + 1) / 2;
long count = 0;
for (int j = 2; N!=1; j++)
{
int c = 0;
while (N % j == 0)
{
N /= j;
c++;
}
count = (count + 1) * (c + 1) - 1;
}
double r = ran.Next() % 11;
r = 1 / (Math.Pow(r, alpha) + 1);
long R = (long)r + 1;
if (count >= 500)
{
alpha *= 1 + 0.001;
RR = RR * betta - (1-betta) * R;
N = age * (age + 1) / 2;
if (N < mmm)
{
mmm = N;
Console.WriteLine(mmm);
}
}
else
{
alpha *= 1 - 0.001;
RR = RR * betta + (1 - betta) * R;
}
age += (long)RR;
}
var b = DateTime.Now - a;
Console.WriteLine("R=" + mmm + " " + b);
string sss = Console.ReadLine();
}
``` |
932,278 | Let say
$$f(x) := \left\{\begin{array}{l l}x+1 & \text{ if } -2\leq x<0 \\ x-1 & \text{ if }0\leq x\leq 2\end{array}\right.$$
How can we find out $f\circ f$? | 2014/09/15 | [
"https://math.stackexchange.com/questions/932278",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/176196/"
] | **Hint:** First, verify that $f(x) \subset [-2,2]$ to be sure that the composition $f \circ f$ is well defined. Then you should carefully separate the cases. Here's an example for the first steps:
If $-2 \leq x < 0$ then $f(x) = x+1$ and so $f(x) < 0$ for $-2 \leq x < -1$, it follows that $f\circ f(x) = ((x+1)+1)$ for $-2 \leq x < -1$. Now if $-2 \leq x < 0$ then $f(x) = x+1$ and so $f(x) \geq 0$ for $-1 \leq x < 0$ thus ... Can you continue from here?
**EDIT:** To be more precise, let $y = f(x)$, then
$$f \circ f(x) = f(y) = \left\{\begin{array}{l l}y+1 & \text{ if } -2\leq y<0 \\ y-1 & \text{ if }0\leq y\leq 2\end{array}\right.=\left\{\begin{array}{l l}f(x)+1 & \text{ if } -2\leq f(x)<0 \\ f(x)-1 & \text{ if }0\leq f(x)\leq 2\end{array}\right.$$
So we have to separate the cases when $-2\leq f(x)<0$ and $0\leq f(x)\leq 2$. By definition of $f$ we know that $f(x) < 0$ for every $x \in [-2,-1)$ and $x \in [0,1)$. In particular this implies that if $x \in [-2,-1)$, then $f(x) = x+1 < 0$ and thus
$$f \circ f(x) = f(x)+1 = (x+1)+1 = x+2.$$
Stays to study the case $x \in [0,1)$ and $f(x) \geq 0$. | Hint: The first thing to do is to write down the domain and codomain of your function. Here we have:
\begin{equation}
f:[-2,2]\longrightarrow[-1,1]
\end{equation}
Next, since $[-1,1]\subset[-2,2]$, it is OK to compose $f$ with itself. Try to figure out yourself what $f\circ f$ does. |
66,144,093 | This happens in Android Studio Beta. Used to work in the other builds as I recall. Now, I either have to generate a new key every time I generate the apk or manually enter my password due to this error. My password is ASCII. Simple characters A thru Z and a thru z. It takes the key just fine, but the next time I try to build this is what I get.
Digging back one error up in the output I see this:
Execution failed for task ':app:packageRelease'.
>
> A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable
> com.android.ide.common.signing.KeytoolException: Failed to read key key0 from store "C:\AndroidRelated\KeyStoreForCompanyA\KeyStore.jks": keystore password was incorrect
>
>
>
I have it remember my password from build to build though.
Note that if I change this manually to what I know is correct, then it will build. Just a bug in Android Studio Beta maybe or is this overridden somewhere other than the Generate Signed Bundle or SDK dialog? | 2021/02/10 | [
"https://Stackoverflow.com/questions/66144093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443654/"
] | **Solved**!
Step;
1. Clean your project
2. Generate signed yours bundle/.apk file
3. Uncheck the "Remember password"
4. Manually put your password at "Key store password" and "Key password"
5. Click Next and you Done!.
*Android studio update bring this bug.* | I faced the same problem. Android Studio saves passwords in a bad format.
I solved it by typing the password manually again. |
66,144,093 | This happens in Android Studio Beta. Used to work in the other builds as I recall. Now, I either have to generate a new key every time I generate the apk or manually enter my password due to this error. My password is ASCII. Simple characters A thru Z and a thru z. It takes the key just fine, but the next time I try to build this is what I get.
Digging back one error up in the output I see this:
Execution failed for task ':app:packageRelease'.
>
> A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable
> com.android.ide.common.signing.KeytoolException: Failed to read key key0 from store "C:\AndroidRelated\KeyStoreForCompanyA\KeyStore.jks": keystore password was incorrect
>
>
>
I have it remember my password from build to build though.
Note that if I change this manually to what I know is correct, then it will build. Just a bug in Android Studio Beta maybe or is this overridden somewhere other than the Generate Signed Bundle or SDK dialog? | 2021/02/10 | [
"https://Stackoverflow.com/questions/66144093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443654/"
] | It is a bug in Android Studio 4.2.+
You have to manually type password each time you generate signed APK! | I faced the same problem. Android Studio saves passwords in a bad format.
I solved it by typing the password manually again. |
66,144,093 | This happens in Android Studio Beta. Used to work in the other builds as I recall. Now, I either have to generate a new key every time I generate the apk or manually enter my password due to this error. My password is ASCII. Simple characters A thru Z and a thru z. It takes the key just fine, but the next time I try to build this is what I get.
Digging back one error up in the output I see this:
Execution failed for task ':app:packageRelease'.
>
> A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable
> com.android.ide.common.signing.KeytoolException: Failed to read key key0 from store "C:\AndroidRelated\KeyStoreForCompanyA\KeyStore.jks": keystore password was incorrect
>
>
>
I have it remember my password from build to build though.
Note that if I change this manually to what I know is correct, then it will build. Just a bug in Android Studio Beta maybe or is this overridden somewhere other than the Generate Signed Bundle or SDK dialog? | 2021/02/10 | [
"https://Stackoverflow.com/questions/66144093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443654/"
] | **Solved**!
Step;
1. Clean your project
2. Generate signed yours bundle/.apk file
3. Uncheck the "Remember password"
4. Manually put your password at "Key store password" and "Key password"
5. Click Next and you Done!.
*Android studio update bring this bug.* | It is a bug in Android Studio 4.2.+
You have to manually type password each time you generate signed APK! |
66,144,093 | This happens in Android Studio Beta. Used to work in the other builds as I recall. Now, I either have to generate a new key every time I generate the apk or manually enter my password due to this error. My password is ASCII. Simple characters A thru Z and a thru z. It takes the key just fine, but the next time I try to build this is what I get.
Digging back one error up in the output I see this:
Execution failed for task ':app:packageRelease'.
>
> A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable
> com.android.ide.common.signing.KeytoolException: Failed to read key key0 from store "C:\AndroidRelated\KeyStoreForCompanyA\KeyStore.jks": keystore password was incorrect
>
>
>
I have it remember my password from build to build though.
Note that if I change this manually to what I know is correct, then it will build. Just a bug in Android Studio Beta maybe or is this overridden somewhere other than the Generate Signed Bundle or SDK dialog? | 2021/02/10 | [
"https://Stackoverflow.com/questions/66144093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443654/"
] | **Solved**!
Step;
1. Clean your project
2. Generate signed yours bundle/.apk file
3. Uncheck the "Remember password"
4. Manually put your password at "Key store password" and "Key password"
5. Click Next and you Done!.
*Android studio update bring this bug.* | Android Studio tries to use the ASCII which is generated as you give your passwords but as it tries to re generate it based on your system language and datetime it can differ in some charachters. So, in some special cases it is better to use your keyboard to type your password.

As you see it makes different passwords in each part. It works correctly in some cases also but totally in act of preventing the trouble it is better to retype manually. |
66,144,093 | This happens in Android Studio Beta. Used to work in the other builds as I recall. Now, I either have to generate a new key every time I generate the apk or manually enter my password due to this error. My password is ASCII. Simple characters A thru Z and a thru z. It takes the key just fine, but the next time I try to build this is what I get.
Digging back one error up in the output I see this:
Execution failed for task ':app:packageRelease'.
>
> A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable
> com.android.ide.common.signing.KeytoolException: Failed to read key key0 from store "C:\AndroidRelated\KeyStoreForCompanyA\KeyStore.jks": keystore password was incorrect
>
>
>
I have it remember my password from build to build though.
Note that if I change this manually to what I know is correct, then it will build. Just a bug in Android Studio Beta maybe or is this overridden somewhere other than the Generate Signed Bundle or SDK dialog? | 2021/02/10 | [
"https://Stackoverflow.com/questions/66144093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443654/"
] | **Solved**!
Step;
1. Clean your project
2. Generate signed yours bundle/.apk file
3. Uncheck the "Remember password"
4. Manually put your password at "Key store password" and "Key password"
5. Click Next and you Done!.
*Android studio update bring this bug.* | You can resolve it quickly by **deleting the keystore file and create a new one** from the Build -> Generate signed bundle/APK -> APK -> create new options.
[](https://i.stack.imgur.com/78EnQ.png) |
66,144,093 | This happens in Android Studio Beta. Used to work in the other builds as I recall. Now, I either have to generate a new key every time I generate the apk or manually enter my password due to this error. My password is ASCII. Simple characters A thru Z and a thru z. It takes the key just fine, but the next time I try to build this is what I get.
Digging back one error up in the output I see this:
Execution failed for task ':app:packageRelease'.
>
> A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable
> com.android.ide.common.signing.KeytoolException: Failed to read key key0 from store "C:\AndroidRelated\KeyStoreForCompanyA\KeyStore.jks": keystore password was incorrect
>
>
>
I have it remember my password from build to build though.
Note that if I change this manually to what I know is correct, then it will build. Just a bug in Android Studio Beta maybe or is this overridden somewhere other than the Generate Signed Bundle or SDK dialog? | 2021/02/10 | [
"https://Stackoverflow.com/questions/66144093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443654/"
] | It is a bug in Android Studio 4.2.+
You have to manually type password each time you generate signed APK! | Android Studio tries to use the ASCII which is generated as you give your passwords but as it tries to re generate it based on your system language and datetime it can differ in some charachters. So, in some special cases it is better to use your keyboard to type your password.

As you see it makes different passwords in each part. It works correctly in some cases also but totally in act of preventing the trouble it is better to retype manually. |
66,144,093 | This happens in Android Studio Beta. Used to work in the other builds as I recall. Now, I either have to generate a new key every time I generate the apk or manually enter my password due to this error. My password is ASCII. Simple characters A thru Z and a thru z. It takes the key just fine, but the next time I try to build this is what I get.
Digging back one error up in the output I see this:
Execution failed for task ':app:packageRelease'.
>
> A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable
> com.android.ide.common.signing.KeytoolException: Failed to read key key0 from store "C:\AndroidRelated\KeyStoreForCompanyA\KeyStore.jks": keystore password was incorrect
>
>
>
I have it remember my password from build to build though.
Note that if I change this manually to what I know is correct, then it will build. Just a bug in Android Studio Beta maybe or is this overridden somewhere other than the Generate Signed Bundle or SDK dialog? | 2021/02/10 | [
"https://Stackoverflow.com/questions/66144093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443654/"
] | It is a bug in Android Studio 4.2.+
You have to manually type password each time you generate signed APK! | You can resolve it quickly by **deleting the keystore file and create a new one** from the Build -> Generate signed bundle/APK -> APK -> create new options.
[](https://i.stack.imgur.com/78EnQ.png) |
661,104 | I have a Java applet consisting of a wizard-like form with three steps. At the final step, the user can click a "finish" button. I want that button to cause the web browser to navigate to a specific URL.
**Question:** Is there a way to cause the browser to navigate to a specific URL, in such a way that it will work across all modern browsers? My specific browser requirements are FF3+, IE7+, Safari 3+, and Opera 9+. I am using Java 1.5. | 2009/03/19 | [
"https://Stackoverflow.com/questions/661104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2405/"
] | You could initiate the wizard from within JavaScript and have the applet return the execution flow to the JavaScript caller on clicking the 'Finish' button. Once you are in JavaScript you could then navigate to a new location, either by doing a form post or by doing changing the window.location property.
In the worst case, you could examine the use of [LiveConnect](http://java.sun.com/products/plugin/1.3/docs/jsobject.html), but I would touch it with a 10 foot pole.
---
**Update on LiveConnect**
The original LiveConnect seems to be limited by nature to browsers running on Windows, and will probably work only on NN and IE. [Some of those bugs have been fixed recently](https://developer.mozilla.org/en/LiveConnect), but browser compatibility will continue to be an issue. | If you're using Java 6 and above, see the [Desktop](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/) API. That'll drive a browser. However I don't know if the applet security model will interfere with this.
Other than that, I've used [BrowserLauncher2](http://browserlaunch2.sourceforge.net/) with success. Similar caveats apply. |
661,104 | I have a Java applet consisting of a wizard-like form with three steps. At the final step, the user can click a "finish" button. I want that button to cause the web browser to navigate to a specific URL.
**Question:** Is there a way to cause the browser to navigate to a specific URL, in such a way that it will work across all modern browsers? My specific browser requirements are FF3+, IE7+, Safari 3+, and Opera 9+. I am using Java 1.5. | 2009/03/19 | [
"https://Stackoverflow.com/questions/661104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2405/"
] | From the applet you can simply get the applet context and call [showDocument(url)](http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL)).
This will navigate away from the current page to the specified URL:
```
getAppletContext().showDocument(url);
```
Additionally you can pass a [target](http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL,%20java.lang.String)) parameter.
To visit a relative URL you can use:
```
URL url = new URL(getCodeBase().getProtocol(),
getCodeBase().getHost(),
getCodeBase().getPort(),
"/next.html");
getAppletContext().showDocument(url);
```
These work in every major browser since Java version 1.1. | You could initiate the wizard from within JavaScript and have the applet return the execution flow to the JavaScript caller on clicking the 'Finish' button. Once you are in JavaScript you could then navigate to a new location, either by doing a form post or by doing changing the window.location property.
In the worst case, you could examine the use of [LiveConnect](http://java.sun.com/products/plugin/1.3/docs/jsobject.html), but I would touch it with a 10 foot pole.
---
**Update on LiveConnect**
The original LiveConnect seems to be limited by nature to browsers running on Windows, and will probably work only on NN and IE. [Some of those bugs have been fixed recently](https://developer.mozilla.org/en/LiveConnect), but browser compatibility will continue to be an issue. |
661,104 | I have a Java applet consisting of a wizard-like form with three steps. At the final step, the user can click a "finish" button. I want that button to cause the web browser to navigate to a specific URL.
**Question:** Is there a way to cause the browser to navigate to a specific URL, in such a way that it will work across all modern browsers? My specific browser requirements are FF3+, IE7+, Safari 3+, and Opera 9+. I am using Java 1.5. | 2009/03/19 | [
"https://Stackoverflow.com/questions/661104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2405/"
] | You could initiate the wizard from within JavaScript and have the applet return the execution flow to the JavaScript caller on clicking the 'Finish' button. Once you are in JavaScript you could then navigate to a new location, either by doing a form post or by doing changing the window.location property.
In the worst case, you could examine the use of [LiveConnect](http://java.sun.com/products/plugin/1.3/docs/jsobject.html), but I would touch it with a 10 foot pole.
---
**Update on LiveConnect**
The original LiveConnect seems to be limited by nature to browsers running on Windows, and will probably work only on NN and IE. [Some of those bugs have been fixed recently](https://developer.mozilla.org/en/LiveConnect), but browser compatibility will continue to be an issue. | ```
String googleURL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(googleURL));
}
catch(IOException ex) {
Logger.getLogger(UI.class.getName()).log(Level.SEVERE,null, ex);
}
``` |
661,104 | I have a Java applet consisting of a wizard-like form with three steps. At the final step, the user can click a "finish" button. I want that button to cause the web browser to navigate to a specific URL.
**Question:** Is there a way to cause the browser to navigate to a specific URL, in such a way that it will work across all modern browsers? My specific browser requirements are FF3+, IE7+, Safari 3+, and Opera 9+. I am using Java 1.5. | 2009/03/19 | [
"https://Stackoverflow.com/questions/661104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2405/"
] | From the applet you can simply get the applet context and call [showDocument(url)](http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL)).
This will navigate away from the current page to the specified URL:
```
getAppletContext().showDocument(url);
```
Additionally you can pass a [target](http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL,%20java.lang.String)) parameter.
To visit a relative URL you can use:
```
URL url = new URL(getCodeBase().getProtocol(),
getCodeBase().getHost(),
getCodeBase().getPort(),
"/next.html");
getAppletContext().showDocument(url);
```
These work in every major browser since Java version 1.1. | If you're using Java 6 and above, see the [Desktop](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/) API. That'll drive a browser. However I don't know if the applet security model will interfere with this.
Other than that, I've used [BrowserLauncher2](http://browserlaunch2.sourceforge.net/) with success. Similar caveats apply. |
661,104 | I have a Java applet consisting of a wizard-like form with three steps. At the final step, the user can click a "finish" button. I want that button to cause the web browser to navigate to a specific URL.
**Question:** Is there a way to cause the browser to navigate to a specific URL, in such a way that it will work across all modern browsers? My specific browser requirements are FF3+, IE7+, Safari 3+, and Opera 9+. I am using Java 1.5. | 2009/03/19 | [
"https://Stackoverflow.com/questions/661104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2405/"
] | From the applet you can simply get the applet context and call [showDocument(url)](http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL)).
This will navigate away from the current page to the specified URL:
```
getAppletContext().showDocument(url);
```
Additionally you can pass a [target](http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL,%20java.lang.String)) parameter.
To visit a relative URL you can use:
```
URL url = new URL(getCodeBase().getProtocol(),
getCodeBase().getHost(),
getCodeBase().getPort(),
"/next.html");
getAppletContext().showDocument(url);
```
These work in every major browser since Java version 1.1. | ```
String googleURL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(googleURL));
}
catch(IOException ex) {
Logger.getLogger(UI.class.getName()).log(Level.SEVERE,null, ex);
}
``` |
44,251,180 | So after a bit of stringy business, I was able to get a large chunk of substring from a haystack of string closer to my target after searching the first occurrence of `"getflashmedia"`
```
var_dump($str) =
string(1735) "getflashmedia" src="http://www.exampleURL.com/media-name.mp4"></object>
.../*a haystack of code as string*/"
```
I want to get the URL inside `src` but this is varying in length, so I can't really use the `substr()` function | 2017/05/29 | [
"https://Stackoverflow.com/questions/44251180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4169959/"
] | Use a regular expression, I'd recommend the following: `src="(.*?)"`.
This expression matches `src="` literally, then starts capturing and stops when it finds another `"`.
```
<?php
$input = 'getflashmedia" src="http://www.exampleURL.com/media-name.mp4"></object>';
preg_match_all('/src="(.*?)"/', $input, $matches);
print_r($matches[1]);
```
Output:
```
Array
(
[0] => http://www.exampleURL.com/media-name.mp4
)
```
This will get every link, from every src attribute in the input string. If you only need the first, use `preg_match()`. | I would strongly recommend rather than using string functions or regular expressions to parse XML/HTML, you should use XML parsers. You can build a much more reliable scraper this way.
XML parsers can handle situations you may not think of when writing your string handling code.
See XML Parser: <http://php.net/manual/en/book.xml.php>
Another option is SimpleXML: <http://php.net/manual/en/simplexml.examples-basic.php>
There are a number of libraries suitable for it. |
5,469,736 | I want paste button only when I select copy option. When copy option is not selected the paste button should not come on the screen.
How can I do it? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5469736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> Where is the best place to start?
>
>
>
Here: <http://www.asp.net/mvc/mvc3> | I wrote a blog post on [Dealing with javascript or JSON results after an AJAX call with Ajax.ActionLink, unobtrusive AJAX and MVC 3](http://www.sharpedgesoftware.com/Blog/2011/02/27/dealing-with-javascript-or-json-results-after-an-ajax-call-with-ajaxactionlink-unobtrusive-ajax-and-) that might help you along. |
5,469,736 | I want paste button only when I select copy option. When copy option is not selected the paste button should not come on the screen.
How can I do it? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5469736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> Where is the best place to start?
>
>
>
Here: <http://www.asp.net/mvc/mvc3> | I always found pluralsight tutorials very helpful and they have a couple on MVC3.
<http://www.pluralsight-training.net/microsoft/olt/courses.aspx>
Alternatively check out this article by Jon Galloway which lists lots of tutorials and resources:
<http://weblogs.asp.net/jgalloway/archive/2011/03/17/asp-net-mvc-3-roundup-of-tutorials-videos-labs-and-other-assorted-training-materials.aspx>
Or David Haydens blog: <http://davidhayden.com/blog/dave/archive/2011/01/05/ASPNETMVC3TutorialsIndex.aspx>
Finally of course there is always the asp.net website: <http://www.asp.net/mvc/tutorials> |
5,469,736 | I want paste button only when I select copy option. When copy option is not selected the paste button should not come on the screen.
How can I do it? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5469736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I always found pluralsight tutorials very helpful and they have a couple on MVC3.
<http://www.pluralsight-training.net/microsoft/olt/courses.aspx>
Alternatively check out this article by Jon Galloway which lists lots of tutorials and resources:
<http://weblogs.asp.net/jgalloway/archive/2011/03/17/asp-net-mvc-3-roundup-of-tutorials-videos-labs-and-other-assorted-training-materials.aspx>
Or David Haydens blog: <http://davidhayden.com/blog/dave/archive/2011/01/05/ASPNETMVC3TutorialsIndex.aspx>
Finally of course there is always the asp.net website: <http://www.asp.net/mvc/tutorials> | I wrote a blog post on [Dealing with javascript or JSON results after an AJAX call with Ajax.ActionLink, unobtrusive AJAX and MVC 3](http://www.sharpedgesoftware.com/Blog/2011/02/27/dealing-with-javascript-or-json-results-after-an-ajax-call-with-ajaxactionlink-unobtrusive-ajax-and-) that might help you along. |
7,800,882 | I have two services IServiceA and IServiceB. The concrete implementation of IServiceB looks like this:
```
public class ServiceB : IServiceB {
public ServiceB(string path, IServiceA serviceA) { ... }
}
```
So I need to pass in a string and a ServiceA.
I'm kinda stuck how I would do that. I have this right now:
```
var path = _config.Path;
container.RegisterType<IServiceA, ServiceA>();
container.RegisterType<IServiceB, ServiceB>(
new InjectionConstructor(path, container.Resolve<IServiceA>());
```
This is obviously wrong as I'm actually instantiating a ServiceA and registering a single Instance with all ServiceB's.
How can I tell Unity to always resolve a "fresh" ServiceA? I tried just removing the IServiceA from RegisterType, and that throws an exception telling me there is no `ctor(string)`, which is correct since it's a `ctor(string,IServiceA)`. | 2011/10/17 | [
"https://Stackoverflow.com/questions/7800882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | It's not particularly well documented, but this appears to work:
```
container.RegisterType<IServiceA, ServiceA>();
container.RegisterType<IServiceB, ServiceB>(
new InjectionConstructor(path, new ResolvedParameter<IServiceA>()));
```
I would recommend testing it before using it in production. | I believe you also can do:
```
container.RegisterType<IServiceA, ServiceA>();
container.RegisterType<IServiceB, ServiceB>(
new InjectionConstructor(path, typeof(IServiceA)));
``` |
15,868 | I have designed a hybrid(keywords and data in same excel sheet) framework using `WebDriver`+`Java`+`TestNG`+`Maven`. I am using `PageFactory`, `Singleton Pattern` . I am using different type of HTML locators in my framework like `id`, `css`, `xpath`. I run tests on UNIX environment.
I was told that using id instead of `xpath` is faster. But how do we measure it, because when I use `xpath` and when I use `id` in both cases test gives output in same time.
Apart from avoid using `xpath`, what are other points to take care of to make project improve lot in case of speedy execution. | 2015/11/30 | [
"https://sqa.stackexchange.com/questions/15868",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/7741/"
] | This may not be a full answer to your question but I think it fits to the topic:
I was wondering about the "id is faster than xpath" and start searching. [This SO-Question/Answer](https://stackoverflow.com/questions/16788310/what-is-the-difference-between-css-selector-xpath-which-is-betteraccording-t) gives an answer which sounds quite logical.
But then I found these two Blogs from *Elemental Selenium*:
* [XPATH vs CSS](http://elementalselenium.com/tips/32-xpath-vs-css)
* [Css Vs. X Path, Under a Microscope](http://elementalselenium.com/tips/33-xpath-vs-css-revisited)
which shows that XPATH is faster than CSS. In the second one the author describes that he used the `benchmark` lib from ruby for his measurements.
>
> For benchmarking I used the library that's available in Ruby's standard lib called 'benchmark'
>
>
>
But as you see the numbers of his comparion you see they don't diverge so much, so I think it's better to use CSS because of the compatibility as not all browsers implementing XPATH the same way. (And yes that's not part of your question) | A typical way to measure the length of a short operation is to measure the total time required to perform the operation many times, divided by the number of times you performed it. How many times? It depends on the operation; I usually start with a small number and keep doubling it, or multiplying by ten, until the answer has as much precision as I need.
There are innumerable ways to make software faster but you did not provide enough details to recommend anything specific. |
15,868 | I have designed a hybrid(keywords and data in same excel sheet) framework using `WebDriver`+`Java`+`TestNG`+`Maven`. I am using `PageFactory`, `Singleton Pattern` . I am using different type of HTML locators in my framework like `id`, `css`, `xpath`. I run tests on UNIX environment.
I was told that using id instead of `xpath` is faster. But how do we measure it, because when I use `xpath` and when I use `id` in both cases test gives output in same time.
Apart from avoid using `xpath`, what are other points to take care of to make project improve lot in case of speedy execution. | 2015/11/30 | [
"https://sqa.stackexchange.com/questions/15868",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/7741/"
] | I see two possible intepretations of your question here. The first is "How can I improve the speed of how elements are found on a page?". Another is "How can I improve execution speed of my suite of tests?".
The first question has some answers already. You've found that `xpath` vs `id` doesn't provide much speedup, so you're almost at the end of the road there.
The second question has more answers. Remember that if you're using WebDriver for end-to-end test automation, there's many, *many* things that affect your tests, such as
* Browser rendering of HTML
* Browser JS compilation and execution
* Internet connection speed
* CSS Styling
* DOM Generation and updating
* Screen resolution
* Application load time
* Browser navigation
* HTML structure
* Server-side application logic
* Client-side application logic
These may all affect how stable your tests are, and in turn how well they run.
To get better run-time performance, I'd suggest the following:
* **Make sure your network connections/Internet connections are reliable and as fast as possible.** Latency causes your apps to run more slowly which in turn causes tests to run more slowly.
* **Use physical or virtual machines with good hardware specs.** Running on low-powered machines (in terms of RAM or CPU) may cause flakiness in your web app which in turn causes flaky tests.
* **Run your tests in parallel as much as possible.** Divide large suites into smaller suites that can be run independently at the same time.
* **Avoid writing low-value tests.** End-to-end tests are inherently long-running tests, and so tests that don't contribute much to understanding your application waste run-time.
* **Write deterministic tests.** Tests that don't require a lot of overhead in terms of setup and teardown run quicker and more reliably.
In my experience these are effective ways to get your test run-time down. | A typical way to measure the length of a short operation is to measure the total time required to perform the operation many times, divided by the number of times you performed it. How many times? It depends on the operation; I usually start with a small number and keep doubling it, or multiplying by ten, until the answer has as much precision as I need.
There are innumerable ways to make software faster but you did not provide enough details to recommend anything specific. |
59,081,148 | First a question:
I am a complete newbie. Is it correct that postgresql installs with some default passwords without asking to change it during installation? What are those passwords? I am just playing with an app and if I know the default passwords, everything will be okay.
As you could tell I don't have the default passwords. Somewhere I read that postgres user allows login with no password. Do I then leave the password field in the app config file empty?
I used the following command from the postgresql command line:
```
ALTER ROLE postgres WITH PASSWORD 'new_password';
```
I get the following error:
```
ALTER: command not found.
```
Could you tell me what is going on?
I have postgresql 11.6 & 12.1. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59081148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4732120/"
] | If you have an object to log, I recommend just pass it directly to `console.log()`. `JSON.stringify()` might be adding carriage returns, which could be interpreted as multiple lines to log.
```
console.log({key1: 'val1', key2: 'val2'})
```
Just make sure that the object doesn't contain references to other very complex objects (especially self-referential objects), otherwise it could cause problems with evaluating the final string at runtime. | Neither console.log(data) nor console.log(JSON.stringify(data)) worked for me.
Using the sdk logger worked for me:
```
import * as functions from 'firebase-functions';
functions.logger.log(data);
```
As described here:
<https://firebase.google.com/docs/functions/writing-and-viewing-logs#logger-sdk> |
59,081,148 | First a question:
I am a complete newbie. Is it correct that postgresql installs with some default passwords without asking to change it during installation? What are those passwords? I am just playing with an app and if I know the default passwords, everything will be okay.
As you could tell I don't have the default passwords. Somewhere I read that postgres user allows login with no password. Do I then leave the password field in the app config file empty?
I used the following command from the postgresql command line:
```
ALTER ROLE postgres WITH PASSWORD 'new_password';
```
I get the following error:
```
ALTER: command not found.
```
Could you tell me what is going on?
I have postgresql 11.6 & 12.1. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59081148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4732120/"
] | If you have an object to log, I recommend just pass it directly to `console.log()`. `JSON.stringify()` might be adding carriage returns, which could be interpreted as multiple lines to log.
```
console.log({key1: 'val1', key2: 'val2'})
```
Just make sure that the object doesn't contain references to other very complex objects (especially self-referential objects), otherwise it could cause problems with evaluating the final string at runtime. | If you put
```
require('firebase-functions/lib/logger/compat');
```
at the top of your functions code with the latest version of the sdk
logs should come in 1 single line
src: <https://github.com/firebase/firebase-functions/issues/612#issuecomment-646652675> |
59,081,148 | First a question:
I am a complete newbie. Is it correct that postgresql installs with some default passwords without asking to change it during installation? What are those passwords? I am just playing with an app and if I know the default passwords, everything will be okay.
As you could tell I don't have the default passwords. Somewhere I read that postgres user allows login with no password. Do I then leave the password field in the app config file empty?
I used the following command from the postgresql command line:
```
ALTER ROLE postgres WITH PASSWORD 'new_password';
```
I get the following error:
```
ALTER: command not found.
```
Could you tell me what is going on?
I have postgresql 11.6 & 12.1. | 2019/11/28 | [
"https://Stackoverflow.com/questions/59081148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4732120/"
] | Neither console.log(data) nor console.log(JSON.stringify(data)) worked for me.
Using the sdk logger worked for me:
```
import * as functions from 'firebase-functions';
functions.logger.log(data);
```
As described here:
<https://firebase.google.com/docs/functions/writing-and-viewing-logs#logger-sdk> | If you put
```
require('firebase-functions/lib/logger/compat');
```
at the top of your functions code with the latest version of the sdk
logs should come in 1 single line
src: <https://github.com/firebase/firebase-functions/issues/612#issuecomment-646652675> |
14,850,855 | **CODE :**
**.htaccess:**
```
RewriteEngine On
RewriteRule ^(.*)/*$ base.php?request=$1 [NC,L]
```
**base.php**
```
<?php
echo "this is base.php <br/> and Get Vaiables <br> ";
print_r($_GET);
?>
```
*for the request:*
```
localhost/blahblahproject/hello
```
**EXPECTED RESULT:**
>
> this is base.php
>
> and Get Vaiables
>
> Array ( [request] => hello )
>
>
>
**Current RESULT:**
>
> this is base.php
>
> and Get Vaiables
>
> Array ( [request] => base.php )
>
>
> | 2013/02/13 | [
"https://Stackoverflow.com/questions/14850855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067797/"
] | Change your .htaccess rule to this:
```
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/?$ /base.php?request=$1 [QSA,L]
``` | `.htaccess` only redirects url to your get parameter. To retrieve the url value, use `parse_url` or similar command.
I have a function like this to do the job:
```
/**
* Sets current request url
*/
private function setUrl() {
$path = parse_url( $_SERVER[ 'REQUEST_URI' ], PHP_URL_PATH );
$pathTrimmed = trim( $path, '/' );
$pathTokens = explode( '/', $pathTrimmed );
if ( substr( $path, -1 ) !== '/' ) {
array_pop( $pathTokens );
}
$url = end( $pathTokens );
$this -> url = $url;
}
``` |
14,850,855 | **CODE :**
**.htaccess:**
```
RewriteEngine On
RewriteRule ^(.*)/*$ base.php?request=$1 [NC,L]
```
**base.php**
```
<?php
echo "this is base.php <br/> and Get Vaiables <br> ";
print_r($_GET);
?>
```
*for the request:*
```
localhost/blahblahproject/hello
```
**EXPECTED RESULT:**
>
> this is base.php
>
> and Get Vaiables
>
> Array ( [request] => hello )
>
>
>
**Current RESULT:**
>
> this is base.php
>
> and Get Vaiables
>
> Array ( [request] => base.php )
>
>
> | 2013/02/13 | [
"https://Stackoverflow.com/questions/14850855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067797/"
] | Change your .htaccess rule to this:
```
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/?$ /base.php?request=$1 [QSA,L]
``` | If you are interested in the string after the last "/", change your .htaccess file to:
```
RewriteEngine On
RewriteRule ^.*/(.*)$ base.php?request=$1 [NC,L]
``` |
6,537,541 | I've followed the Google app script tutorial [here](http://www.youtube.com/user/GoogleDocsCommunity#p/c/0/5VmEPo6Rkq4) which is a very simple script with two functions. `showDialog` (which presents a dialog box with a text field and submit button ) and `respondToSubmit(e)` which handles the submit button and adds the entered data to the spreadsheet.
It works fine.
What doesn't seem to work is the debugger on the callback. So I place a breakpoint in both functons and start the `showDialog` function. The debugger kicks in and stops execution at the breakpoint. I click continue so I can interact with the newly opened dialog box. However when I click the submit button the debugger does not start again. The `respondtoSubmit(e)` function is executed. The debugger just does not stop on the breakpoint(s).
Is there a problem with debugging callbacks like this or can you only debug one function at a time? | 2011/06/30 | [
"https://Stackoverflow.com/questions/6537541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/516286/"
] | As of right now, the debugger has some unexpected behaviours. Mostly, it seems to only respect breakpoints during calls from the script editor, so to debug your event handler you must call it from the debugger, not the UI. If you need to peek into variables such as the event object passed to the function, for example, try adding this line to your handler where you'd normally put a breakpoint:
`Logger.log(Utilities.jsonStringify(e));`
Then view the log from the script editor after execution. | It seems to me that the Logger does not work either, unless run from the script editor. I did manage `Browser.msgbox(Utilities.jsonStringify(e))` which had brought the (expected) result:
`{"parameter":{"clientY":"45","clientX":"37","eventType":"click","ctrl":"false","meta":"false","source":"u12053277590","button":"1","alt":"false","myTextBox":"babi","screenY":"381","screenX":"598","shift":"false","y":"13","x":"33"}}` |
6,537,541 | I've followed the Google app script tutorial [here](http://www.youtube.com/user/GoogleDocsCommunity#p/c/0/5VmEPo6Rkq4) which is a very simple script with two functions. `showDialog` (which presents a dialog box with a text field and submit button ) and `respondToSubmit(e)` which handles the submit button and adds the entered data to the spreadsheet.
It works fine.
What doesn't seem to work is the debugger on the callback. So I place a breakpoint in both functons and start the `showDialog` function. The debugger kicks in and stops execution at the breakpoint. I click continue so I can interact with the newly opened dialog box. However when I click the submit button the debugger does not start again. The `respondtoSubmit(e)` function is executed. The debugger just does not stop on the breakpoint(s).
Is there a problem with debugging callbacks like this or can you only debug one function at a time? | 2011/06/30 | [
"https://Stackoverflow.com/questions/6537541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/516286/"
] | For reference Utilities.jsonStringify(e) is depricated, use JSON.stringify() and JSON.parse() instead. | It seems to me that the Logger does not work either, unless run from the script editor. I did manage `Browser.msgbox(Utilities.jsonStringify(e))` which had brought the (expected) result:
`{"parameter":{"clientY":"45","clientX":"37","eventType":"click","ctrl":"false","meta":"false","source":"u12053277590","button":"1","alt":"false","myTextBox":"babi","screenY":"381","screenX":"598","shift":"false","y":"13","x":"33"}}` |
7,333,873 | I am buidling an app in CakePHP. I have 2 models:
- Project
- User
The Project model has various belongsTo relations to the user model, one for the creator, one for the last editor and one for the manager. This works fine.
Then I add a virtual field to the User model, called 'name', which is CONCAT(first\_name, ' ', last\_name). It combines the first name and last name into a general name field, which is used througout the app.
After this, I get SQL errors saying that the first\_name column is ambiguous. This is because in the query, the alias for Creator, Manager, etc is not used in the CONCAT field.
Any ideas on how to avoid this? | 2011/09/07 | [
"https://Stackoverflow.com/questions/7333873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/565907/"
] | Showing the exact queries should help resolve this problem. But if you are joining 2 tables, and they both have a column with the same name. you have to reference the column with TableName.ColumnName, like this.
```
Select Table1.Column1 AS someColumn, Table2.Column1 AS SomeOtherColumn
FROM Table1
INNER JOIN Table2
ON Table1.ID = Table2.Table1ID
WHERE Table1.ID = 3
```
You can shorten this up by giving your tables aliases, As follows.
```
Select T1.Column1 AS someColumn, T2.Column1 AS SomeOtherColumn
FROM Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.ID = T2.Table1ID
WHERE T1.ID = 3
``` | Try specifying what table the first\_name column is from. Something like this:
```
CONCAT(table1.first_name,'',table1.last_name)
``` |
7,333,873 | I am buidling an app in CakePHP. I have 2 models:
- Project
- User
The Project model has various belongsTo relations to the user model, one for the creator, one for the last editor and one for the manager. This works fine.
Then I add a virtual field to the User model, called 'name', which is CONCAT(first\_name, ' ', last\_name). It combines the first name and last name into a general name field, which is used througout the app.
After this, I get SQL errors saying that the first\_name column is ambiguous. This is because in the query, the alias for Creator, Manager, etc is not used in the CONCAT field.
Any ideas on how to avoid this? | 2011/09/07 | [
"https://Stackoverflow.com/questions/7333873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/565907/"
] | I found the solution: <http://book.cakephp.org/view/1632/Virtual-fields-and-model-aliases> | Try specifying what table the first\_name column is from. Something like this:
```
CONCAT(table1.first_name,'',table1.last_name)
``` |
31,541,814 | There are topics online that are discussing this problem however, I couldn't find any tidy explanation of the problem or any solid answers for the question. What I am trying to achieve is connecting Laravel 5.1 to MySQL Database of MAMP.
---
In my ***config>app.php:***
```
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => 'localhost:8889',
'database' => 'test',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
'prefix' => '',
'strict' => false,
],
```
In my ***.env:***
```
DB_HOST=localhost
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=root
```
I also have ***.env.example:*** (which I believe has no functionality)
```
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
```
I also have `create_users_table.php` and `create_password_resets_table.php` in my ***database>migrations*** (even though I did not run any migration:make)
---
MAMP is directing and running the server successfully as it loads the project on localhost.
---
Here is my MAMP settings:
[](https://imgur.com/T3KczgP)
[](https://imgur.com/wbySSkJ)
And the `test` database is created (with tables in it which I have previously created and used in my other projects, not Laravel.)
[](https://imgur.com/4V2r913)
---
Even though everything seems correct to me, when trying to submit Auth form, I am getting this error:
>
> ### PDOException in Connector.php line 50:
> could not find driver
>
>
> 1. in Connector.php line 50
> 2. at PDO->\_\_construct ('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', 'root', 'root', array('0', '2', '0', false, false)) in Connector.php line 50
> 3. at Connector->createConnection('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', array('driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8\_unicode\_ci', 'unix\_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, 'name' => 'mysql'), array('0', '2', '0', false, false)) in MySqlConnector.php line 22
>
>
> and so on...
>
>
> | 2015/07/21 | [
"https://Stackoverflow.com/questions/31541814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4705339/"
] | It was pretty simple for me, I added :8889 to the localhost in the .env file.
DB\_HOST=localhost:8889
This is because in the MAMP preferences, :8889 is the default port. | **Found my answer. Here is a way to fix it:**
* Start MAMP
* On the top left, go to "MAMP" -> "Preferences"
* Go to the "PHP" tab
* Tick PHP 5.5.17 (or whatever you have) instead of the one which is ticked by default (5.6.1 -> 5.5.17 with he latest version of MAMP) |
31,541,814 | There are topics online that are discussing this problem however, I couldn't find any tidy explanation of the problem or any solid answers for the question. What I am trying to achieve is connecting Laravel 5.1 to MySQL Database of MAMP.
---
In my ***config>app.php:***
```
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => 'localhost:8889',
'database' => 'test',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
'prefix' => '',
'strict' => false,
],
```
In my ***.env:***
```
DB_HOST=localhost
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=root
```
I also have ***.env.example:*** (which I believe has no functionality)
```
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
```
I also have `create_users_table.php` and `create_password_resets_table.php` in my ***database>migrations*** (even though I did not run any migration:make)
---
MAMP is directing and running the server successfully as it loads the project on localhost.
---
Here is my MAMP settings:
[](https://imgur.com/T3KczgP)
[](https://imgur.com/wbySSkJ)
And the `test` database is created (with tables in it which I have previously created and used in my other projects, not Laravel.)
[](https://imgur.com/4V2r913)
---
Even though everything seems correct to me, when trying to submit Auth form, I am getting this error:
>
> ### PDOException in Connector.php line 50:
> could not find driver
>
>
> 1. in Connector.php line 50
> 2. at PDO->\_\_construct ('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', 'root', 'root', array('0', '2', '0', false, false)) in Connector.php line 50
> 3. at Connector->createConnection('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', array('driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8\_unicode\_ci', 'unix\_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, 'name' => 'mysql'), array('0', '2', '0', false, false)) in MySqlConnector.php line 22
>
>
> and so on...
>
>
> | 2015/07/21 | [
"https://Stackoverflow.com/questions/31541814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4705339/"
] | The most important thing for me was defining the UNIX socket. Because I have another MYSQL on my machine - Laravel was trying to connect to a database in that MYSQL process.
Defining the UNIX for the MAMP database to be used worked perfectly. Try adding this to your MYSQL configuration in database.php
```
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
``` | **Found my answer. Here is a way to fix it:**
* Start MAMP
* On the top left, go to "MAMP" -> "Preferences"
* Go to the "PHP" tab
* Tick PHP 5.5.17 (or whatever you have) instead of the one which is ticked by default (5.6.1 -> 5.5.17 with he latest version of MAMP) |
31,541,814 | There are topics online that are discussing this problem however, I couldn't find any tidy explanation of the problem or any solid answers for the question. What I am trying to achieve is connecting Laravel 5.1 to MySQL Database of MAMP.
---
In my ***config>app.php:***
```
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => 'localhost:8889',
'database' => 'test',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
'prefix' => '',
'strict' => false,
],
```
In my ***.env:***
```
DB_HOST=localhost
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=root
```
I also have ***.env.example:*** (which I believe has no functionality)
```
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
```
I also have `create_users_table.php` and `create_password_resets_table.php` in my ***database>migrations*** (even though I did not run any migration:make)
---
MAMP is directing and running the server successfully as it loads the project on localhost.
---
Here is my MAMP settings:
[](https://imgur.com/T3KczgP)
[](https://imgur.com/wbySSkJ)
And the `test` database is created (with tables in it which I have previously created and used in my other projects, not Laravel.)
[](https://imgur.com/4V2r913)
---
Even though everything seems correct to me, when trying to submit Auth form, I am getting this error:
>
> ### PDOException in Connector.php line 50:
> could not find driver
>
>
> 1. in Connector.php line 50
> 2. at PDO->\_\_construct ('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', 'root', 'root', array('0', '2', '0', false, false)) in Connector.php line 50
> 3. at Connector->createConnection('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', array('driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8\_unicode\_ci', 'unix\_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, 'name' => 'mysql'), array('0', '2', '0', false, false)) in MySqlConnector.php line 22
>
>
> and so on...
>
>
> | 2015/07/21 | [
"https://Stackoverflow.com/questions/31541814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4705339/"
] | On mac or unix you have to include the socket path in the configuration database.php file
i.e `'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',` | **Found my answer. Here is a way to fix it:**
* Start MAMP
* On the top left, go to "MAMP" -> "Preferences"
* Go to the "PHP" tab
* Tick PHP 5.5.17 (or whatever you have) instead of the one which is ticked by default (5.6.1 -> 5.5.17 with he latest version of MAMP) |
31,541,814 | There are topics online that are discussing this problem however, I couldn't find any tidy explanation of the problem or any solid answers for the question. What I am trying to achieve is connecting Laravel 5.1 to MySQL Database of MAMP.
---
In my ***config>app.php:***
```
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => 'localhost:8889',
'database' => 'test',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
'prefix' => '',
'strict' => false,
],
```
In my ***.env:***
```
DB_HOST=localhost
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=root
```
I also have ***.env.example:*** (which I believe has no functionality)
```
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
```
I also have `create_users_table.php` and `create_password_resets_table.php` in my ***database>migrations*** (even though I did not run any migration:make)
---
MAMP is directing and running the server successfully as it loads the project on localhost.
---
Here is my MAMP settings:
[](https://imgur.com/T3KczgP)
[](https://imgur.com/wbySSkJ)
And the `test` database is created (with tables in it which I have previously created and used in my other projects, not Laravel.)
[](https://imgur.com/4V2r913)
---
Even though everything seems correct to me, when trying to submit Auth form, I am getting this error:
>
> ### PDOException in Connector.php line 50:
> could not find driver
>
>
> 1. in Connector.php line 50
> 2. at PDO->\_\_construct ('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', 'root', 'root', array('0', '2', '0', false, false)) in Connector.php line 50
> 3. at Connector->createConnection('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', array('driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8\_unicode\_ci', 'unix\_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, 'name' => 'mysql'), array('0', '2', '0', false, false)) in MySqlConnector.php line 22
>
>
> and so on...
>
>
> | 2015/07/21 | [
"https://Stackoverflow.com/questions/31541814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4705339/"
] | It was pretty simple for me, I added :8889 to the localhost in the .env file.
DB\_HOST=localhost:8889
This is because in the MAMP preferences, :8889 is the default port. | The most important thing for me was defining the UNIX socket. Because I have another MYSQL on my machine - Laravel was trying to connect to a database in that MYSQL process.
Defining the UNIX for the MAMP database to be used worked perfectly. Try adding this to your MYSQL configuration in database.php
```
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
``` |
31,541,814 | There are topics online that are discussing this problem however, I couldn't find any tidy explanation of the problem or any solid answers for the question. What I am trying to achieve is connecting Laravel 5.1 to MySQL Database of MAMP.
---
In my ***config>app.php:***
```
'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
'driver' => 'mysql',
'host' => 'localhost:8889',
'database' => 'test',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
'prefix' => '',
'strict' => false,
],
```
In my ***.env:***
```
DB_HOST=localhost
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=root
```
I also have ***.env.example:*** (which I believe has no functionality)
```
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
```
I also have `create_users_table.php` and `create_password_resets_table.php` in my ***database>migrations*** (even though I did not run any migration:make)
---
MAMP is directing and running the server successfully as it loads the project on localhost.
---
Here is my MAMP settings:
[](https://imgur.com/T3KczgP)
[](https://imgur.com/wbySSkJ)
And the `test` database is created (with tables in it which I have previously created and used in my other projects, not Laravel.)
[](https://imgur.com/4V2r913)
---
Even though everything seems correct to me, when trying to submit Auth form, I am getting this error:
>
> ### PDOException in Connector.php line 50:
> could not find driver
>
>
> 1. in Connector.php line 50
> 2. at PDO->\_\_construct ('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', 'root', 'root', array('0', '2', '0', false, false)) in Connector.php line 50
> 3. at Connector->createConnection('mysql:unix\_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=test', array('driver' => 'mysql', 'host' => 'localhost:8889', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8\_unicode\_ci', 'unix\_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock', 'prefix' => '', 'strict' => false, 'name' => 'mysql'), array('0', '2', '0', false, false)) in MySqlConnector.php line 22
>
>
> and so on...
>
>
> | 2015/07/21 | [
"https://Stackoverflow.com/questions/31541814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4705339/"
] | It was pretty simple for me, I added :8889 to the localhost in the .env file.
DB\_HOST=localhost:8889
This is because in the MAMP preferences, :8889 is the default port. | As far as I am concerned it doesn't make any sense to set in **database.php** as many of them suggested.
Since this change would be mostly required in the **development mode**. So the proper way of setting the **unix\_socket** is as below
file: **.env**
```
DB_SOCKET='/Applications/MAMP/tmp/mysql/mysql.sock'
```
By doing the above way already **.env** is included in **.gitignore** and won't create any other problem while your project is remotely deployed.
>
> NOTE: I have tested this setting in Laravel 5.7 and above versions
>
>
> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.