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
|
---|---|---|---|---|---|
57,554,043 | In my head section of my `form.layout.blade.php` I have the following:
```
<head>
<script src="/js/main.js"></script>
<head>
```
This is layout file is loaded before all pages are loaded. Is there a way to *not* load `main.js` for a specific route? | 2019/08/19 | [
"https://Stackoverflow.com/questions/57554043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5272159/"
] | you can use if statement like this. main.js will not load on this page
```
@if(!Request::is('subpage/url'))
<script src="/js/main.js"></script>
@endif
``` | The workaround I used for not loading scripts on all sites, is that I put script paths in variables in controllers, something like this:
```
public function show($id){
$scripts[] = '/js/main.js';
view()->share('scripts', $scripts);
return view('view', $someData);
}
```
This allows me to use this script only on a page I really need it, like this:
```
@if(isset($scripts))
@foreach($scripts as $key => $value)
<script src="{{mix($value)}}"></script>
@endforeach
@endif
```
Hope that this can lead you in right direction. |
57,554,043 | In my head section of my `form.layout.blade.php` I have the following:
```
<head>
<script src="/js/main.js"></script>
<head>
```
This is layout file is loaded before all pages are loaded. Is there a way to *not* load `main.js` for a specific route? | 2019/08/19 | [
"https://Stackoverflow.com/questions/57554043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5272159/"
] | you can use if statement like this. main.js will not load on this page
```
@if(!Request::is('subpage/url'))
<script src="/js/main.js"></script>
@endif
``` | You can use if statements
```
@if(!in_array(Route::currentRouteName(), ['route.name', ...]))
<script src="/js/main.js"></script>
@endif
``` |
1,886,096 | ```
L->|
A -> B ^ |
|__> C -> D-> G->X--| |
K |_> T | |_>Z
|___________|
```
I hope this small drawing helps convey what I'm trying to do.
I have a list of 7,000 locations, each with an undefined, but small number of doors. Each door is a bridge between both locations.
Referencing the diagram above, how would I go about finding the quickest route through the doors to get from A to Z?
I don't need full on source, just psuedo code would be fine.
Obviously you can take A -> B ->C -> D -> G -> X -> L -> Z,
but the shortest route is A -> B -> C -> K -> X -> Z. | 2009/12/11 | [
"https://Stackoverflow.com/questions/1886096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88770/"
] | Represent your locations as nodes and the doors as edges in a graph. Then apply some rather standard [shortest path algorithm(s)](http://en.wikipedia.org/wiki/Shortest_path_problem) and you're done. | Look up [Pathfinding](http://en.wikipedia.org/wiki/Pathfinding) algorithms on Wikipedia. You basically build up a series of nodes and connections between them, and the algorithm works through them finding a way from the start to a goal. |
1,886,096 | ```
L->|
A -> B ^ |
|__> C -> D-> G->X--| |
K |_> T | |_>Z
|___________|
```
I hope this small drawing helps convey what I'm trying to do.
I have a list of 7,000 locations, each with an undefined, but small number of doors. Each door is a bridge between both locations.
Referencing the diagram above, how would I go about finding the quickest route through the doors to get from A to Z?
I don't need full on source, just psuedo code would be fine.
Obviously you can take A -> B ->C -> D -> G -> X -> L -> Z,
but the shortest route is A -> B -> C -> K -> X -> Z. | 2009/12/11 | [
"https://Stackoverflow.com/questions/1886096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88770/"
] | Represent your locations as nodes and the doors as edges in a graph. Then apply some rather standard [shortest path algorithm(s)](http://en.wikipedia.org/wiki/Shortest_path_problem) and you're done. | You can suppose that each room is a node and each door is a node and the problem will become finding shortest path in graph which you can find with [Dijkstra's algorithm](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) for example |
1,772,475 | I'm running a LAMP box with PHP running as fcgid. APC is installed and working well. However, each PHP process gets its own cache. This is a problem, because it would make far more sense to have 10 PHP processes with 300MB shared APC cache than 10 PHP processes, each with a redundant 30MB unshared APC cache.
There was a prior thread on this topic 8 months ago ([How to share APC cache between several PHP processes when running under FastCGI?](https://stackoverflow.com/questions/598444/how-to-share-apc-cache-between-several-php-processes-when-running-under-fastcgi)) and I am wondering if there have been any developments in this realm since then. | 2009/11/20 | [
"https://Stackoverflow.com/questions/1772475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199475/"
] | As far as I know it's still not possible to use shared memory cache with any PHP cacher amongst multiple processes... anyway, unless you're under extremely heavy load you should be fine with separate caches, I suppose, since they'll be filled pretty quickly. And hey, RAM is cheap nowadays! | It turns out that this is still not possible if you are truly using different processes: <http://pecl.php.net/bugs/bug.php?id=11988> (updated 11/13/2009 by the author of the relevant portion of APC). |
1,772,475 | I'm running a LAMP box with PHP running as fcgid. APC is installed and working well. However, each PHP process gets its own cache. This is a problem, because it would make far more sense to have 10 PHP processes with 300MB shared APC cache than 10 PHP processes, each with a redundant 30MB unshared APC cache.
There was a prior thread on this topic 8 months ago ([How to share APC cache between several PHP processes when running under FastCGI?](https://stackoverflow.com/questions/598444/how-to-share-apc-cache-between-several-php-processes-when-running-under-fastcgi)) and I am wondering if there have been any developments in this realm since then. | 2009/11/20 | [
"https://Stackoverflow.com/questions/1772475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199475/"
] | As far as I know it's still not possible to use shared memory cache with any PHP cacher amongst multiple processes... anyway, unless you're under extremely heavy load you should be fine with separate caches, I suppose, since they'll be filled pretty quickly. And hey, RAM is cheap nowadays! | I was reading about it just minutes ago in the bug tracking of PHP <https://bugs.php.net/bug.php?id=57825> it's fixed but you must use spawnfcgi or php-fpm <http://php-fpm.org/>
Quoted from Ramus
>
> It works fine if you use spawnfcgi or php-fpm. Any process manager
> that launches a parent process and spawns child processes from that
> will work fine.
>
>
> |
1,772,475 | I'm running a LAMP box with PHP running as fcgid. APC is installed and working well. However, each PHP process gets its own cache. This is a problem, because it would make far more sense to have 10 PHP processes with 300MB shared APC cache than 10 PHP processes, each with a redundant 30MB unshared APC cache.
There was a prior thread on this topic 8 months ago ([How to share APC cache between several PHP processes when running under FastCGI?](https://stackoverflow.com/questions/598444/how-to-share-apc-cache-between-several-php-processes-when-running-under-fastcgi)) and I am wondering if there have been any developments in this realm since then. | 2009/11/20 | [
"https://Stackoverflow.com/questions/1772475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199475/"
] | I was reading about it just minutes ago in the bug tracking of PHP <https://bugs.php.net/bug.php?id=57825> it's fixed but you must use spawnfcgi or php-fpm <http://php-fpm.org/>
Quoted from Ramus
>
> It works fine if you use spawnfcgi or php-fpm. Any process manager
> that launches a parent process and spawns child processes from that
> will work fine.
>
>
> | It turns out that this is still not possible if you are truly using different processes: <http://pecl.php.net/bugs/bug.php?id=11988> (updated 11/13/2009 by the author of the relevant portion of APC). |
2,465,656 | is this a valid JQuery usage pattern to :
```
<script type="text/javascript">
$("body").prepend('<input type="hidden" id="error" value="show">');
</script>
```
That is using Jquery to manipulate / insert HTML Tags **when the Document has NOT YET been loaded** (by not using document.ready for the inserting into the DOM)?
(Normally I only use document.ready, but in this case I need to insert some Information into the DOM that then is present, when document.ready is called. This is some kind of "happens-before" relations ship I want to achieve so that I am shure when document.ready is called the inserted Form field is available in the document, as I depend on that information.
Thank you very much
jens | 2010/03/17 | [
"https://Stackoverflow.com/questions/2465656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/293513/"
] | Yes, you can do that, but:
* You have to place the script somewhere after the closing tag of the element that you add elements to. That means that the body element is not a good candidate to prepend anything to.
* Make sure that the HTML code is valid. If you are using XHTML you should self close the input element.
Consider using the object creation model instead of innerHTML model:
```
$("#someElement").prepend(
$('<input/>').attr({ 'type': 'hidden', 'id': 'error' 'value': 'show' })
);
```
This will create the element as a DOM object instead of using innerHTML to parse the HTML code. | IE may fail loading such HTML - it has problems when someone modifies not fully rendered elements. I think the right choice would be placing such code just after tag. |
2,465,656 | is this a valid JQuery usage pattern to :
```
<script type="text/javascript">
$("body").prepend('<input type="hidden" id="error" value="show">');
</script>
```
That is using Jquery to manipulate / insert HTML Tags **when the Document has NOT YET been loaded** (by not using document.ready for the inserting into the DOM)?
(Normally I only use document.ready, but in this case I need to insert some Information into the DOM that then is present, when document.ready is called. This is some kind of "happens-before" relations ship I want to achieve so that I am shure when document.ready is called the inserted Form field is available in the document, as I depend on that information.
Thank you very much
jens | 2010/03/17 | [
"https://Stackoverflow.com/questions/2465656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/293513/"
] | You can but it won't consistently work, as Andrew Bezzub says IE will be the problem (surprise, surprise)
Hard to tell the master plan but for your example could you just not just put this immediately after the `<body>` opening tag:
```
document.write('<input type="hidden" id="error" value="show">');
``` | IE may fail loading such HTML - it has problems when someone modifies not fully rendered elements. I think the right choice would be placing such code just after tag. |
50,790 | The following theorem has been mentioned (and partially proved) in the book Functions of Bounded Variation and Free Discontinuity Problems by Luigi Ambrosio et. al.
Let $\mu,\nu$ be positive measures on $(X,\mathcal{E})$. Assume that they are equal on a collection of sets $\mathcal{G}$ which is closed under finite intersections. Also assume that there are sets $X\_h \in \mathcal{G}$ such that $\displaystyle{X= \bigcup\_{h=1}^\infty X\_h}$ and that $\mu(X\_h) = \nu(X\_h) < \infty$ for all $h$. Then $\mu, \nu$ are equal
on the $\sigma$-algebra generated by $\mathcal{G}$.
The authors prove the theorem for the case where $\mu,\nu$ are positive finite measures and $\mu(X) = \nu(X)$ and say that the general case follows easily.
However, this is not at all straight forward for me. I have tried to prove this
but cannot reach a valid proof. Here is my attempt at a proof:
Let $G\_h = \{g \cap X\_h | g \in G\}$. Then clearly from using the finite case
of the theorem, we have that $\mu,\nu$ coincide on every $\sigma (G\_h)$. My
problem now is to show that this implies that they agree on $\sigma(G)$. All my
attempts in this direction have been futile.
I feel that the solution should be relatively easy (as the authors themselves point out). Any help in the proof is greatly appreciated.
Thanks,
Phanindra | 2011/07/11 | [
"https://math.stackexchange.com/questions/50790",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/13199/"
] | The collection of $A \in \mathcal{E}$ such that $\mu(A \cap X\_h) = \nu(A \cap X\_h)$ for all $h$ forms a $\sigma$-algebra containing $\sigma(G)$. | Note that if $\nu$ is a $\sigma$-finite non negative measure then on a $\sigma$-algebra $G$ then every finite nonnegative measurable function $f$ defines the $\sigma$-finite measure $\mu:=f.\nu$. We can take $f$ to be a characteristic function. This is because, if $f$ is integrable then it defines a set function $\mu(A)= \int\_A f d\nu$.
In general, statements involving $\sigma$-finite "situations" can always be reduced to the finite case (see Bogachev section 2.6). |
24,630,720 | Is there any equivalent of strict mocks in python? Some mechanism to report unintended call of mocked methods (action.step2() in this example), just like this in GoogleMock framework.
```
class Action:
def step1(self, arg):
return False
def step2(self, arg):
return False
def algorithm(action):
action.step1('111')
action.step2('222')
return True
class TestAlgorithm(unittest.TestCase):
def test_algorithm(self):
actionMock = mock.create_autospec(Action)
self.assertTrue(algorithm(actionMock))
actionMock.step1.assert_called_once_with('111')
``` | 2014/07/08 | [
"https://Stackoverflow.com/questions/24630720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407981/"
] | Looks like it's not supported out of the box. However there are at least two approaches on how to achieve the same result.
Passing list of allowed members
-------------------------------
According to mock documentation
>
> *spec*: This can be either a **list of strings** or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). **Accessing any attribute not in this list will raise an AttributeError**.
>
>
>
So, in order to fail your test example just replace
```
actionMock = mock.create_autospec(Action)
```
to
```
actionMock = mock.Mock(spec=['step1'])
```
Such an approach have certain drawbacks compared to passing class or instance as `spec` argument, as you have to pass all the allowed methods and than set up expectations on them, effectively registering them twice. Also, if you need to restrict a subset of methods you have to pass list of all methods execept those. This can be achieved as follows:
```
all_members = dir(Action) # according to docs this is what's happening behind the scenes
all_members.remove('step2') # remove all unwanted methods
actionMock = mock.Mock(spec=all_members)
```
Setting exceptions on restricted methods
----------------------------------------
Alternative approach would be to excplicitly set failures on methods you don't want to be called:
```
def test_algorithm(self):
actionMock = mock.create_autospec(Action)
actionMock.step2.side_effect = AttributeError("Called step2") # <<< like this
self.assertTrue(algorithm(actionMock))
actionMock.step1.assert_called_once_with('111')
```
This have some limitations as well: you've got to set errors as well as expectations.
As a final note, one radical solution to the problem would be to patch `mock` to add `strict` parameter to `Mock` constructor and send a pull request. Than either it would be accepted or `mock` maintainers will point out on how to achieve that. :) | Yes, this is possible using the `spec=` and `autospec=` arguments. See the [mock documentation on Autospeccing](http://www.voidspace.org.uk/python/mock/helpers.html#auto-speccing) for more information. In your example it would become:
```
action_mock = mock.Mock(spec=Action)
```
or:
```
action_mock = mock.Mock('Action', autospec=True)
``` |
24,630,720 | Is there any equivalent of strict mocks in python? Some mechanism to report unintended call of mocked methods (action.step2() in this example), just like this in GoogleMock framework.
```
class Action:
def step1(self, arg):
return False
def step2(self, arg):
return False
def algorithm(action):
action.step1('111')
action.step2('222')
return True
class TestAlgorithm(unittest.TestCase):
def test_algorithm(self):
actionMock = mock.create_autospec(Action)
self.assertTrue(algorithm(actionMock))
actionMock.step1.assert_called_once_with('111')
``` | 2014/07/08 | [
"https://Stackoverflow.com/questions/24630720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407981/"
] | Looks like it's not supported out of the box. However there are at least two approaches on how to achieve the same result.
Passing list of allowed members
-------------------------------
According to mock documentation
>
> *spec*: This can be either a **list of strings** or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). **Accessing any attribute not in this list will raise an AttributeError**.
>
>
>
So, in order to fail your test example just replace
```
actionMock = mock.create_autospec(Action)
```
to
```
actionMock = mock.Mock(spec=['step1'])
```
Such an approach have certain drawbacks compared to passing class or instance as `spec` argument, as you have to pass all the allowed methods and than set up expectations on them, effectively registering them twice. Also, if you need to restrict a subset of methods you have to pass list of all methods execept those. This can be achieved as follows:
```
all_members = dir(Action) # according to docs this is what's happening behind the scenes
all_members.remove('step2') # remove all unwanted methods
actionMock = mock.Mock(spec=all_members)
```
Setting exceptions on restricted methods
----------------------------------------
Alternative approach would be to excplicitly set failures on methods you don't want to be called:
```
def test_algorithm(self):
actionMock = mock.create_autospec(Action)
actionMock.step2.side_effect = AttributeError("Called step2") # <<< like this
self.assertTrue(algorithm(actionMock))
actionMock.step1.assert_called_once_with('111')
```
This have some limitations as well: you've got to set errors as well as expectations.
As a final note, one radical solution to the problem would be to patch `mock` to add `strict` parameter to `Mock` constructor and send a pull request. Than either it would be accepted or `mock` maintainers will point out on how to achieve that. :) | Another possibility:
Checking call\_count individually on restricted methods
-------------------------------------------------------
Ensure that `call_count` is zero on methods that should not be called.
```
class TestAlgorithm(unittest.TestCase):
def test_algorithm(self):
actionMock = mock.create_autospec(Action)
self.assertTrue(algorithm(actionMock))
actionMock.step1.assert_called_once_with('111')
self.assertEqual(actionMock.step2.call_count, 0) # <<< like this
```
The drawback is that you have to check all unexpected calls one by one. |
20,531,272 | In my php program, I have to insert variables into one of my sql tables. Every time I go to test this out though, the values don't get posted to the table. Is there something wrong with these statements? or is the problem bigger than these 2 lines
```
$sqli = mySQLi_connect("localhost","root","root","myProject");
mysqli_query("insert into purchases (id, productID, quantity) values ($id, $productID, $quantity)");
``` | 2013/12/11 | [
"https://Stackoverflow.com/questions/20531272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3093085/"
] | Look at [my white paper on Drools Design Patterns](http://www.google.at/url?q=http://www.redhat.com/rhecm/rest-rhecm/jcr/repository/collaboration/sites%2520content/live/redhat/web-cabinet/home/resourcelibrary/whitepapers/brms-design-patterns/rh%3apdfFile.pdf) especially the section on Data Validation.
The section explains a strategy that circumvents the straightforward creation of one Drools rule per rule in the requirements. Simply put, you use data to describe these rules, insert the data as facts, along with the facts representing actual data, and write rules relating the descriptions to the data. You might say that the rules "interpret" the descriptions against the data.
There are adavantages and disadvantages to this approach, but it ought to be considered before launching into handwritten or spreadsheet rules. | Look into **Drools decision tables**, which make it easier for someone to input those 1000 rules. |
24,768,747 | I don't quite understand how escape the character works in .awk scripts.
I have this line in the file I want to read:
```
#Name Surname City Company State Probability Units Price Amount
```
If I just write:
```
awk < test.txt '/\#/ {print $1}'
```
in the command line, then everything is fine and the output is #Name.
However, if I try to do the same inside an .awk file the following way:
```
/\#/ {print $1};
```
I get no output for this. Also, gEdit won't recognize "\" as an escape character inside .awk for some reason.
Why is this happening and is there a workaround? | 2014/07/15 | [
"https://Stackoverflow.com/questions/24768747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3614293/"
] | Join your queries with a `UNION`. The way you've got it now, it'll return two results sets.
```
SELECT [col1], [col2] FROM Contact
UNION ALL
SELECT [col1], [col2] FROM Numar_contact
```
As DJ KRAZE pointed out in a comment, it might not be a bad idea to wrap this in a sproc or a TVF. But this will work too.
**Edit:**
I just learned via comments that the two tables are actually unrelated. In light of that, I'd be tempted to use two `SqlCommand`s with two, distinct `foreach` loops. But if you're sold on this way,
```
SELECT id_contact, nume_contact, prenume_contact FROM Contact
UNION ALL
SELECT id_contact, numar, NULL FROM Numar_contact
```
This will align the data from the two tables, but where the second table doesn't have a `[prenume_contact]` it will select `NULL`. I might have mixed up the column positions here, since I don't really understand what those names are meant to represent.
**Edit 2:**
```
string connString = @"database=Agenda_db; Data Source=Marian-PC\SQLEXPRESS; Persist Security Info=false; Integrated Security=SSPI";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Contact", conn))
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
listBox1.Items.Add(rdr[0].ToString() + " " + rdr[1].ToString() + " " + rdr[2].ToString());
}
}
using (SqlCommand cmd2 = new SqlCommand("SELECT * FROM Numar_contact", conn))
using (SqlDataReader rdr2 = cmd.ExecuteReader())
{
while (rdr2.Read())
{
listBox1.Items.Add(rdr2[0].ToString() + " " + rdr2[1].ToString());
}
}
}
catch { }
}
```
**Edit 3, thanks to insight from Scott Chamberlain:**
On the other hand, you might want to perform a [`JOIN`](http://technet.microsoft.com/en-us/library/ms191517(v=sql.105).aspx) of some kind, most commonly an `INNER JOIN`. Note that this is an entirely different operation from any we've talked about before.
```
SELECT Contact.id_contact, Contact.nume_contact, Contact.prenume_contact, Numar_contact.numar
FROM Contact
INNER JOIN Numar_contact on Contact.id_contact = Numar_contact.id_contact
```
This will tie the two tables together, returning a record for each contact-numar\_contact. Again, this is definitely *not* the same as doing a `UNION`. Make sure you're aware of the difference before you pick which you want.
Use this if your second table contains data that relates many-to-one to the first table. | Thanks to [your comment](https://stackoverflow.com/questions/24768745/doesnt-work-th-sqlcommand-with-multiple-queries#comment38434382_24768774), what you are wanting to do is [JOIN](http://technet.microsoft.com/en-us/library/ms191517(v=sql.105).aspx) the tables.
```sql
SELECT Contact.id_contact, nume_contact, prenume_contact, numar
FROM Contact
INNER JOIN Numar_contact on Contact.id_contact = Numar_contact.id_contact
```
That will combine the two tables in to four columns where id\_contact matches in both tables.
You may want a `INNER JOIN` or a `LEFT JOIN` depending on if you want rows to show up only when there is a item in the 2nd table or show up anyway and just make the 4th column `DBNull.Value`. |
24,768,747 | I don't quite understand how escape the character works in .awk scripts.
I have this line in the file I want to read:
```
#Name Surname City Company State Probability Units Price Amount
```
If I just write:
```
awk < test.txt '/\#/ {print $1}'
```
in the command line, then everything is fine and the output is #Name.
However, if I try to do the same inside an .awk file the following way:
```
/\#/ {print $1};
```
I get no output for this. Also, gEdit won't recognize "\" as an escape character inside .awk for some reason.
Why is this happening and is there a workaround? | 2014/07/15 | [
"https://Stackoverflow.com/questions/24768747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3614293/"
] | Join your queries with a `UNION`. The way you've got it now, it'll return two results sets.
```
SELECT [col1], [col2] FROM Contact
UNION ALL
SELECT [col1], [col2] FROM Numar_contact
```
As DJ KRAZE pointed out in a comment, it might not be a bad idea to wrap this in a sproc or a TVF. But this will work too.
**Edit:**
I just learned via comments that the two tables are actually unrelated. In light of that, I'd be tempted to use two `SqlCommand`s with two, distinct `foreach` loops. But if you're sold on this way,
```
SELECT id_contact, nume_contact, prenume_contact FROM Contact
UNION ALL
SELECT id_contact, numar, NULL FROM Numar_contact
```
This will align the data from the two tables, but where the second table doesn't have a `[prenume_contact]` it will select `NULL`. I might have mixed up the column positions here, since I don't really understand what those names are meant to represent.
**Edit 2:**
```
string connString = @"database=Agenda_db; Data Source=Marian-PC\SQLEXPRESS; Persist Security Info=false; Integrated Security=SSPI";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Contact", conn))
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
listBox1.Items.Add(rdr[0].ToString() + " " + rdr[1].ToString() + " " + rdr[2].ToString());
}
}
using (SqlCommand cmd2 = new SqlCommand("SELECT * FROM Numar_contact", conn))
using (SqlDataReader rdr2 = cmd.ExecuteReader())
{
while (rdr2.Read())
{
listBox1.Items.Add(rdr2[0].ToString() + " " + rdr2[1].ToString());
}
}
}
catch { }
}
```
**Edit 3, thanks to insight from Scott Chamberlain:**
On the other hand, you might want to perform a [`JOIN`](http://technet.microsoft.com/en-us/library/ms191517(v=sql.105).aspx) of some kind, most commonly an `INNER JOIN`. Note that this is an entirely different operation from any we've talked about before.
```
SELECT Contact.id_contact, Contact.nume_contact, Contact.prenume_contact, Numar_contact.numar
FROM Contact
INNER JOIN Numar_contact on Contact.id_contact = Numar_contact.id_contact
```
This will tie the two tables together, returning a record for each contact-numar\_contact. Again, this is definitely *not* the same as doing a `UNION`. Make sure you're aware of the difference before you pick which you want.
Use this if your second table contains data that relates many-to-one to the first table. | Yes you can.
Here is [an example from the MSDN](http://support.microsoft.com/kb/311274) I've modified to use your code - you need to move the reader to the [Next ResultSet](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.nextresult(v=vs.110).aspx)
```
string connString = @"database=Agenda_db; Data Source=Marian-PC\SQLEXPRESS; Persist Security Info=false; Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connString);
SqlCommand myCommand = new SqlCommand("SELECT * FROM Contact; SELECT * FROM Numar_contact", conn);
SqlDataReader myReader ;
int RecordCount=0;
try
{
myConnection.Open();
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
//Write logic to process data for the first result.
RecordCount = RecordCount + 1;
}
MessageBox.Show("Total number of Contacts: " + RecordCount.ToString());
bool moreResults = myReader.NextResult(); // <<<<<<<<<<< MOVE TO NEXT RESULTSET
RecordCount = 0;
while (moreResults && myReader.Read())
{
//Write logic to process data for the second result.
RecordCount = RecordCount + 1;
}
MessageBox.Show("Total number from Numar_contacts: " + RecordCount.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close(); // Could be replaced with using statement too
}
``` |
48,302,244 | I can transpose a square matrix, but now I'd like to transpose a non square matrix (in my code 3\*2) with user input.
Other sources recommended me to create a new matrix first, which I have done. I manage to make the matrix, but when transposing, it stops from the 4th value.
I have looked at other topics but I can't find the error. Here is my code so far, can someone tell me where I went wrong?
Thanks!
```
//const
const int ROWS = 3;
const int COLS = 2;
//first matrix
int[,] matrix1 = new int[ROWS, COLS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
Console.Write("Enter num: ");
matrix1[i, j] = int.Parse(Console.ReadLine());
}
}
//output
Console.WriteLine("Eerste matrix: ");
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
Console.Write(matrix1[i, j] + " ");
}
Console.WriteLine(" ");
}
//transposed matrix
Console.WriteLine("Tweede matrix: ");
int[,] matrix2 = new int[COLS, ROWS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
matrix2[j, i] = matrix1[j, i];
Console.Write(matrix2[j, i] + " ");
}
Console.WriteLine(" ");
}
```
This is what I get when running the program:
```
//output
Enter num: 1
Enter num: 2
Enter num: 3
Enter num: 4
Enter num: 5
Enter num: 6
first matrix:
1 2
3 4
5 6
transposed matrix:
1 3
2 4
//--->> Only went up to 4th value?
``` | 2018/01/17 | [
"https://Stackoverflow.com/questions/48302244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9229665/"
] | So, at the beginning you load a matrix with fields : "i,j" => "row, column"
On the last step, you try accessing the matrix with a "j,i" => "column, row" order.
You're inverting the i,j indexes.-
Let me help you by just changing the variable names :
//const
```
const int ROWS = 3;
const int COLS = 2;
//first matrix
int[,] matrix1 = new int[ROWS, COLS];
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column ++)
{
Console.Write("Enter num: ");
matrix1[row, column] = int.Parse(Console.ReadLine());
}
}
```
//output
```
Console.WriteLine("Eerste matrix: ");
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column++)
{`enter code here`
Console.Write(matrix1[row, column] + " ");
}
Console.WriteLine(" ");
}
```
//transposed matrix
```
Console.WriteLine("Tweede matrix: ");
int[,] matrix2 = new int[COLS, ROWS];
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column++)
{
matrix2[column, row] = matrix1[row, column];
Console.Write(matrix2[column, row] + " ");
}
Console.WriteLine(" ");
}
```
// EDIT : actually noticed the sample didn't traspose it properly. fixed it. | Replace
```
matrix2[j, i] = matrix1[j, i];
```
with
```
matrix2[j, i] = matrix1[i, j];
```
This way a row number of matrix1 becomes a column number for matrix2 - i.e. the matrix gets transposed. |
48,302,244 | I can transpose a square matrix, but now I'd like to transpose a non square matrix (in my code 3\*2) with user input.
Other sources recommended me to create a new matrix first, which I have done. I manage to make the matrix, but when transposing, it stops from the 4th value.
I have looked at other topics but I can't find the error. Here is my code so far, can someone tell me where I went wrong?
Thanks!
```
//const
const int ROWS = 3;
const int COLS = 2;
//first matrix
int[,] matrix1 = new int[ROWS, COLS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
Console.Write("Enter num: ");
matrix1[i, j] = int.Parse(Console.ReadLine());
}
}
//output
Console.WriteLine("Eerste matrix: ");
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
Console.Write(matrix1[i, j] + " ");
}
Console.WriteLine(" ");
}
//transposed matrix
Console.WriteLine("Tweede matrix: ");
int[,] matrix2 = new int[COLS, ROWS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
matrix2[j, i] = matrix1[j, i];
Console.Write(matrix2[j, i] + " ");
}
Console.WriteLine(" ");
}
```
This is what I get when running the program:
```
//output
Enter num: 1
Enter num: 2
Enter num: 3
Enter num: 4
Enter num: 5
Enter num: 6
first matrix:
1 2
3 4
5 6
transposed matrix:
1 3
2 4
//--->> Only went up to 4th value?
``` | 2018/01/17 | [
"https://Stackoverflow.com/questions/48302244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9229665/"
] | So, at the beginning you load a matrix with fields : "i,j" => "row, column"
On the last step, you try accessing the matrix with a "j,i" => "column, row" order.
You're inverting the i,j indexes.-
Let me help you by just changing the variable names :
//const
```
const int ROWS = 3;
const int COLS = 2;
//first matrix
int[,] matrix1 = new int[ROWS, COLS];
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column ++)
{
Console.Write("Enter num: ");
matrix1[row, column] = int.Parse(Console.ReadLine());
}
}
```
//output
```
Console.WriteLine("Eerste matrix: ");
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column++)
{`enter code here`
Console.Write(matrix1[row, column] + " ");
}
Console.WriteLine(" ");
}
```
//transposed matrix
```
Console.WriteLine("Tweede matrix: ");
int[,] matrix2 = new int[COLS, ROWS];
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column++)
{
matrix2[column, row] = matrix1[row, column];
Console.Write(matrix2[column, row] + " ");
}
Console.WriteLine(" ");
}
```
// EDIT : actually noticed the sample didn't traspose it properly. fixed it. | If you combine the other two answers, you will have a complete picture:
This line is wrong and will give you an `IndexOutOfRangeException`:
```
matrix2[j, i] = matrix1[j, i];
```
In order to transpose you need to flip the indices:
```
matrix2[j, i] = matrix1[i, j];
```
Another problem is that when you print the matrix, you switch rows and columns.
It's easier to just extract the code for each functionality into a separate method.
Also, using the names i and j can be confusing. They look alike and they don't convey their meaning. When working with matrices, I like to use r and c (or row and column)
```
void PrintMatrix(int[,] m)
{
int rows = m.GetLength(0);
int columns = m.GetLength(1);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
Console.Write(m[r, c] + " ");
}
Console.WriteLine();
}
}
int[,] TransposeMatrix(int[,] m)
{
int rows = m.GetLength(0);
int columns = m.GetLength(1);
int[,] transposed = new int[columns, rows];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
transposed[c, r] = m[r, c];
}
}
return transposed;
}
```
Then the last part of your code becomes simply:
```
PrintMatrix(matrix1);
Console.WriteLine();
int[,] matrix2 = TransposeMatrix(matrix1);
PrintMatrix(matrix2);
``` |
65,235,190 | I am thinking of setting up a bitnami mongodb replicaset in K8s, as explained [here](https://github.com/bitnami/charts/tree/master/bitnami/mongodb#architecture).
However, as a note they mention this while upgrading:
>
> Note: An update takes your MongoDB replicaset offline if the Arbiter is enabled and the number of MongoDB replicas is two. Helm applies updates to the statefulsets for the MongoDB instance and the Arbiter at the same time so you loose two out of three quorum votes.
>
>
>
I am not sure what does it actually mean "taking the replicaset offline":
1. Is it that the whole mongo service goes offline/down and therefore there is downtime on the service when performing helm upgrades?
2. Is it that, while performing the upgrade, the replicaset will have only one mongodb server working, while both, the other mongo db server and arbiter, are offline and being upgraded?. In this case, it will not imply downtime, just that momentarily, there is just one server available (instead of two), so similar to a standalone setup. | 2020/12/10 | [
"https://Stackoverflow.com/questions/65235190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848107/"
] | Bitnami developer here
>
> Is it that, while performing the upgrade, the replicaset will have
> only one mongodb server working, while both, the other mongo db server
> and arbiter, are offline and being upgraded?
>
>
>
That will depend on how many replicas you have. If you install the chart with 2 replicas + 1 arbiter, yes it means that. However, if you install the chart with 4 replicas + 1 arbiter, you'll have only 1 replica and the arbiter being restarted simultaneously, having the other 3 replicas up.
>
> In this case, it will not imply downtime, just that momentarily, there
> is just one server available (instead of two), so similar to a
> standalone setup.
>
>
>
As it's mentioned in the previous response, it does imply a small downtime indeed if the minimum quorum of alive replicas it's not meet. | I don't know what Helm is or what it does or why it takes down two nodes at a time, but:
>
> I this case, it will not imply downtime, just that momentarily, there is just one server available (instead of two), so similar to a standalone setup.
>
>
>
A standalone accepts writes whenever it's up. A replica set node accepts writes only if it is the primary node, and to have a primary node a majority of nodes must be up. Therefore if only one out of three nodes of a replica set is up, there cannot be a primary, and no node will accept writes.
With one out of three nodes available, if this node is data-bearing, you can still issue reads using secondary-allowing read preferences (primary preferred or secondary or secondary preferred), but primary reads won't work and writes won't work. |
8,968,133 | I have added a view to a layout which occupies a part of my screen. To this layout I want to add another layout which will be transparent. On this layout there should be only two lines which will scroll over the background layout. This I am doing so that my background layout is not invalidated and only the foreground is invalidated.
How can I add another layout which will be transparent? | 2012/01/23 | [
"https://Stackoverflow.com/questions/8968133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463039/"
] | Use `FrameLayout` as a parent layout and stack it up with as many layouts as you want. Thats one part of the answer. To make a layer (a layout in this case) transparent, set the alpha value in its background (a color) to 0. For instance `android:background="#00777777"` sets a background which is translucent with a dull gray.
You get the idea. | Use fram layout, which will allow you to add two views on each other. |
229,878 | This is part of a series of questions.
*Context*: a friend of mine is writing a novel about a rogue planet around the mass of Mars passing by the solar system before continuing its journey in interstellar space (it must not be captured by the Sun). Given sufficient heads-ups, Earth sends a research mission to land on it, study it for as long as possible, and return.
We would like Earthians to have as much time as possible on the rogue planet.
**How slow and close could a Mars-like planet pass near the Solar System to be plausible and not cause catastrophic Earth orbit perturbation?**
I am guessing that there is no theoretical lower speed limit, as it can barely have the escape velocity of its birth system, then be slowed down by more stars behind it that in front of it. (right?) Or maybe a theoretical limit is the solar system escape velocity, which is around 700km/s, as even an almost stale object relative to the solar system will fall at that speed? | 2022/05/12 | [
"https://worldbuilding.stackexchange.com/questions/229878",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/76461/"
] | "Passing through the solar system" I guess means in this case "passing through the inner solar system". If it only passes the Kuiper belt or the Oort cloud, there would be no serious perturbations (no "showering the inner solar system" or the like").
When passing through the inner solar system there will be no perturbation either, unless it passes close to a planet, which is not likely. The trajectory of the object will in most cases be highly inclined to the plane of the solar system which diminishes the probability of a close encounter.
The escape velocity depends on the distance from the Sun. The value of 700 km/s refers to escape velocity from the surface of the Sun. At Earth's orbit it is something around 42 km/s.
An interstellar object will typically enter the solar system with a delta-v of 20-30 km/s, but the value can be much larger - 200 km/s and more - or smaller. As it approaches the Sun it will accelerate due to the Sun's gravity and pass by in a hyperbolic trajectory. How fast it is at any point is the (vectorial) sum of its initial velocity and its acceleration by the Sun. Its maximum velocity will therefore depend on how close it gets to the Sun - the closer it gets the faster it will become. Unless its initial delta-v was close to zero it will almost always have escape velocity. The capture of interstellar objects by the Sun is possible but certainly very rare.
**How close could a Mars-like planet pass near the Solar System to be plausible and not cause catastrophic Earth orbit perturbation?**
As close as you like. | Considering that the solar system is a multi-body system, we are sure it is a chaotic system in the long run. For the solar system, its [Lyapunov time](https://en.wikipedia.org/wiki/Lyapunov_time) is 5 million years.
This means that the effect of any perturbation on the system cannot really be reliably predicted past 5 million years. Plus what are you going to do with the Oort cloud bodies disturbed by the passage of the planet and that will likely end up showering the inner solar system?
For sure any body which can shoot through the solar system will need to have at least the sun escape velocity.
The additional problem is that landing on something moving that fast is going to be tricky: first you need to reach that velocity to be able to land, and then slow down to get back on Earth. Considering that the Apollo mission had to struggle being in the range of 11 km/s, you can see the challenge you are up to. |
229,878 | This is part of a series of questions.
*Context*: a friend of mine is writing a novel about a rogue planet around the mass of Mars passing by the solar system before continuing its journey in interstellar space (it must not be captured by the Sun). Given sufficient heads-ups, Earth sends a research mission to land on it, study it for as long as possible, and return.
We would like Earthians to have as much time as possible on the rogue planet.
**How slow and close could a Mars-like planet pass near the Solar System to be plausible and not cause catastrophic Earth orbit perturbation?**
I am guessing that there is no theoretical lower speed limit, as it can barely have the escape velocity of its birth system, then be slowed down by more stars behind it that in front of it. (right?) Or maybe a theoretical limit is the solar system escape velocity, which is around 700km/s, as even an almost stale object relative to the solar system will fall at that speed? | 2022/05/12 | [
"https://worldbuilding.stackexchange.com/questions/229878",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/76461/"
] | **Numbers**
I concur with Avun Jahei's answer, but feel that it's worth quantifying the minimum non-catastrophic close approach distance.
This object has a mass comparable to Mars - 6.9 x 1023 kg
Earth's moon has a mass of 7.35 x 1022 kg and orbits at an average distance of 3.8 x 108 m.
For the purposes of calculating effects, let's assume that the rogue planet is exactly 10 times more massive than Earth's moon.
If the rogue planet passed by travelling on a trajectory perpendicular to the ecliptic and just outside lunar orbital distance then it would not be catastrophic for Earth's *orbit* - one never-repeated pass would be insufficient to have much effect - but it would be disastrous for Earth *civilisation* - massive tidal waves and energetic disruption to weather patterns, possible perturbation of the moon's orbit and so on. Quite apart from being freakishly unlikely that an approach would be that close - as Douglas Adams famously said, "Space is big" - this is probably not what you are looking for.
Fortunately, gravity works on an inverse square relationship. If we say that the rogue passed by with closest approach being 10 x lunar orbit away then it's tidal effects experienced on Earth will only be one-tenth that of the moon. The object is 10 times more massive, but the gravitational attraction is 100 times weaker at that distance (about 12-13 light-seconds). These effects would be somewhat noticeable, for example unusually high/low tides, but not catastrophic.
Increase the distance of closest approach by another order of magnitude and make closest approach about two light minutes away - still freakishly close for an interstellar object - and the effects from a single close encounter will be 0.1% as strong as lunar tidal effects. Scientists will be able to measure the effect and amateur telescopes will get a good look at it, but there will be no perceptible difference for people or other lifeforms on Earth. | Considering that the solar system is a multi-body system, we are sure it is a chaotic system in the long run. For the solar system, its [Lyapunov time](https://en.wikipedia.org/wiki/Lyapunov_time) is 5 million years.
This means that the effect of any perturbation on the system cannot really be reliably predicted past 5 million years. Plus what are you going to do with the Oort cloud bodies disturbed by the passage of the planet and that will likely end up showering the inner solar system?
For sure any body which can shoot through the solar system will need to have at least the sun escape velocity.
The additional problem is that landing on something moving that fast is going to be tricky: first you need to reach that velocity to be able to land, and then slow down to get back on Earth. Considering that the Apollo mission had to struggle being in the range of 11 km/s, you can see the challenge you are up to. |
29,457,315 | I have 3 tables, like so:
```
release (release_id, name, ...)
medium (medium_id, release_id, name, ...)
track (track_id, medium_id, title, ...)
```
Having only the release\_id, i want to be able delete both the track and the medium associated with that release\_id in one shot using one query.
Is it possible? If yes, can I get a rough template, I'll figure out the rest.
Do I need multiple delete queries? | 2015/04/05 | [
"https://Stackoverflow.com/questions/29457315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/888139/"
] | Strictly speaking, yes, you need three separate delete statements.
However, if you always want the associated rows deleted from the other two tables when you delete a row from the 'release' table, you can use foreign keys and an ON DELETE CASCADE constraint on the 'release' table.
See, e.g. <http://www.mysqltutorial.org/mysql-on-delete-cascade/> | In the first line you define from which tables you want to delete in the join
```
delete r, m, t
from release r
left join medium m on m.release_id = r.release_id
left join track t on t.medium_id = m.medium_id
where r.release_id = 123
``` |
29,457,315 | I have 3 tables, like so:
```
release (release_id, name, ...)
medium (medium_id, release_id, name, ...)
track (track_id, medium_id, title, ...)
```
Having only the release\_id, i want to be able delete both the track and the medium associated with that release\_id in one shot using one query.
Is it possible? If yes, can I get a rough template, I'll figure out the rest.
Do I need multiple delete queries? | 2015/04/05 | [
"https://Stackoverflow.com/questions/29457315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/888139/"
] | Yes you can do this in one statement by referencing multiple tables in the delete statement:
```
DELETE FROM `release`, medium, track
USING `release`, medium, track
WHERE `release`.release_id = medium.release_id
AND medium.medium_id = track.medium_id
AND `release`.release_id = 1;
```
[Sample SQL Fiddle](http://www.sqlfiddle.com/#!9/f68a6/1)
If this is something that should always happen you might want to have a look at the `on delete cascade` option for foreign keys. See the docs for more information: [13.1.14.2 Using FOREIGN KEY Constraints](http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html) | In the first line you define from which tables you want to delete in the join
```
delete r, m, t
from release r
left join medium m on m.release_id = r.release_id
left join track t on t.medium_id = m.medium_id
where r.release_id = 123
``` |
61,338,861 | I'm trying to increment an index in a loop for but my program does not work. I have a simple array with 10 elements and I want to sum all elements of this array. I'm having problem, because I consider two loop, first I want to calculate the five first elements and than the five last, but my counter i\_i does not change in the program, the code is
```
import numpy as np
from matplotlib.pylab import *
x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]
i_i = 0
i_j = 5
sum_t = 0.0
for i in range(2):
for ii in range(i_j):
sum_t += x[i]
i_i += 5
i_j += 5
print(sum_t)
```
The valeu of the sum must be 55, but I'm have problem with the index i\_i. Any suggestion is welcome to make the program work in this way. | 2020/04/21 | [
"https://Stackoverflow.com/questions/61338861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6457422/"
] | You used the wrong variable in the second loop, it is `ii`, not `i`. Secondly the last loop must go from `i_i` to `i_j` so your range is also wrong:
```
import numpy as np
from matplotlib.pylab import *
x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]
i_i = 0
i_j = 5
sum_t = 0.0
for i in range(2):
for ii in range(i_i, i_j):
sum_t += x[ii]
i_i += 5
i_j += 5
print(sum_t)
``` | I'm not sure what you hope to achieve by summing in two halves, but this works:
```
x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]
i_i = 0
i_j = 5
sum_t = 0.0
for i in range(2):
for ii in range(i_j):
sum_t += x[ii + i_i]
i_i += 5
print(sum_t)
```
`i_j` means that you want to sum 5 elements each time. `i_i` tells the loop how far forward to start in `x`.
I'm sure that `float(sum(x))` gives the same answer. |
61,338,861 | I'm trying to increment an index in a loop for but my program does not work. I have a simple array with 10 elements and I want to sum all elements of this array. I'm having problem, because I consider two loop, first I want to calculate the five first elements and than the five last, but my counter i\_i does not change in the program, the code is
```
import numpy as np
from matplotlib.pylab import *
x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]
i_i = 0
i_j = 5
sum_t = 0.0
for i in range(2):
for ii in range(i_j):
sum_t += x[i]
i_i += 5
i_j += 5
print(sum_t)
```
The valeu of the sum must be 55, but I'm have problem with the index i\_i. Any suggestion is welcome to make the program work in this way. | 2020/04/21 | [
"https://Stackoverflow.com/questions/61338861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6457422/"
] | You used the wrong variable in the second loop, it is `ii`, not `i`. Secondly the last loop must go from `i_i` to `i_j` so your range is also wrong:
```
import numpy as np
from matplotlib.pylab import *
x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]
i_i = 0
i_j = 5
sum_t = 0.0
for i in range(2):
for ii in range(i_i, i_j):
sum_t += x[ii]
i_i += 5
i_j += 5
print(sum_t)
``` | You forgot to use the i\_i index and in the second for you were using i instead of ii.
```py
x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]
i_i = 0
i_j = 5
sum_t = 0.0
for i in range(2):
for ii in range(i_i, i_j):
sum_t += x[ii]
i_i += 5
i_j += 5
print (i_j)
print(sum_t)
```
But I would just use this:
```
print(sum(x))
``` |
61,338,861 | I'm trying to increment an index in a loop for but my program does not work. I have a simple array with 10 elements and I want to sum all elements of this array. I'm having problem, because I consider two loop, first I want to calculate the five first elements and than the five last, but my counter i\_i does not change in the program, the code is
```
import numpy as np
from matplotlib.pylab import *
x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]
i_i = 0
i_j = 5
sum_t = 0.0
for i in range(2):
for ii in range(i_j):
sum_t += x[i]
i_i += 5
i_j += 5
print(sum_t)
```
The valeu of the sum must be 55, but I'm have problem with the index i\_i. Any suggestion is welcome to make the program work in this way. | 2020/04/21 | [
"https://Stackoverflow.com/questions/61338861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6457422/"
] | You used the wrong variable in the second loop, it is `ii`, not `i`. Secondly the last loop must go from `i_i` to `i_j` so your range is also wrong:
```
import numpy as np
from matplotlib.pylab import *
x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]
i_i = 0
i_j = 5
sum_t = 0.0
for i in range(2):
for ii in range(i_i, i_j):
sum_t += x[ii]
i_i += 5
i_j += 5
print(sum_t)
``` | Here are the reasons why above code does not work as expected
1) Wrong index variable in the sum.Have to use x[ii] instead of x[i]
2) Range of the second for loop, first execution it has to start from index 0 and in the next execution, the starting index should be 5.
```
x = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]
i_i = 0
i_j = 5
sum_t = 0.0
for i in range(2):
for ii in range(i_i,i_j):
sum_t += x[ii]
i_i += 5
i_j += 5
print(sum_t)
``` |
8,147,696 | I can't find this information online or in the documentation, does anyone know what versions of Android and iOS the AIR 3.0 captive runtime is compatible with? I'm assuming there is some restriction there, but short of actually compiling a program and trying it on iPhone for example, which I don't have, how can I tell which OS versions are supported?
I know that you can compile an Adobe AIR 2.7(?) application to target say Android 2.2, but what about the captive runtime with AIR 3.0? Also I don't see anywhere to find out the iOS version restriction with AIR, as you have to pay $100 to Apple to even get the SDK which would allow me to make an iOS project in the first place. | 2011/11/16 | [
"https://Stackoverflow.com/questions/8147696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997477/"
] | System requirements using captive runtime are the same as without - in other words, quoting from the [reqs page](http://www.adobe.com/products/air/tech-specs.html):
* Android™ 2.2, 2.3, 3.0, 3.1, and 3.2
* iPod touch (3rd generation) 32 GB and 64 GB model, iPod touch 4, iPhone 3GS, iPhone 4, iPad, iPad 2
* iOS 4 and above
Incidentally, note that captive runtime is not a new option for iOS - it's how AIR has always worked there, since iOS doesn't allow using a separate runtime. So really, captive runtime is a matter of doing on Android (or elsewhere) what's been done on iOS all along. | I would suppose captive runtime apps work on all the devices which originally support AIR. Captive runtime just packages the AIR packages (which would otherwise be separately installed) into your application so that a separate download is not required.
As for iOS, I believe the compiler creates native iOS code (because Apple will disallow all apps which run on 3rd party frameworks), so the app should work on all versions of iOS supported by your sdk. |
28,762,226 | i need sql query for report from table item per day(fix day1-day31 as column) of the month when i input **month and year**.
This is my table (item)
ID | NAME | DATE
---------------------------------------------------
1 | ITEM A | 2015-2-25 13:37:49
2 | ITEM A | 2015-2-25 14:37:49
3 | ITEM A | 2015-2-26 13:30:55
4 | ITEM B | 2015-2-26 15:37:49
5 | ITEM B | 2015-2-26 17:57:49
6 | ITEM C | 2015-2-27 13:00:33
---
(input month=02 and year=2015)
What I need to achieve with a view is the following:
NAME | 1| 2| 3|…|25|26|27|28|29|30|31|Total
------------------------------------------------------
ITEM A| 0| 0| 0|…| 2 | 1 | 0 | 0 | 0 | 0 | 0 | 3
ITEM B| 0| 0| 0|…| 0 | 2 | 0 | 0 | 0 | 0 | 0 | 2
ITEM C| 0| 0| 0|…| 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1
---
Any ideas would be very much appreciated.
Thanks in advance.
Sorry this is my first post. | 2015/02/27 | [
"https://Stackoverflow.com/questions/28762226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4613455/"
] | You can do this using a PIVOT in your query
```
SELECT name,
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9],
[10],
[11],
[12],
[13],
[14],
[15],
[16],
[17],
[18],
[19],
[20],
[21],
[22],
[23],
[24],
[25],
[26],
[27],
[28],
[29],
[30],
[31],
([1] + [2] + [3] + [4] + [5] + [6] + [7] + [8] + [9] + [10] + [11] + [12] + [13] + [14] + [15] + [16] + [17] + [18] + [19] + [20] + [21] + [22] + [23] + [24] + [25] + [26] + [27] + [28] + [29] + [30] + [31]) as total
FROM
(
SELECT Name,
id,
Datepart(day, [date]) day
FROM item
WHERE MONTH([date]) = 2 AND YEAR([date]) = 2015
) x
PIVOT
(
count(id)
FOR day IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31])
) p
``` | This will do it for you. First test data:
```
CREATE TABLE data ([ID] int, [Name] varchar(30), [Date] datetime)
INSERT INTO data ([ID], [Name], [Date])
SELECT 1,'ITEM A','2015-2-25 13:37:49'
UNION ALL SELECT 2,'ITEM A','2015-2-25 14:37:49'
UNION ALL SELECT 3,'ITEM A','2015-2-26 13:30:55'
UNION ALL SELECT 4,'ITEM B','2015-2-26 15:37:49'
UNION ALL SELECT 5,'ITEM B','2015-2-26 17:57:49'
UNION ALL SELECT 6,'ITEM C','2015-2-27 13:00:33'
```
Then the query. Note you can use any data range, so if you want a full month just calculate that and put it in the @startDate and @endDate
```
DECLARE @startDate DATETIME='25-Feb-2015'
DECLARE @endDate DATETIME='28-Feb-2015'
DECLARE @numberOfDays INT = DATEDIFF(DAY, @startDate, @endDate)
declare @dayColumns TABLE (delta int, colName varchar(12))
-- Produce 1 row for each day in the report. Note that this is limited by the
-- number of objects in sysobjects (which is about 2000 so its a high limit)
-- Each row contains a delta date offset, @startDate+delta gives each date to report
-- which is converted to a valid SQL column name in the format colYYYYMMDD
INSERT INTO @dayColumns (delta, colName)
SELECT delta, 'col'+CONVERT(varchar(12),DATEADD(day,delta,@startDate),112) as colName from (
select (ROW_NUMBER() OVER (ORDER BY sysobjects.id))-1 as delta FROM sysobjects
) daysAhead
WHERE delta<=@numberOfDays
-- Create a comma seperated list of columns to report
DECLARE @cols AS NVARCHAR(MAX)= ''
SELECT @cols=CASE WHEN @cols='' THEN @cols ELSE @cols+',' END + colName FROM @dayColumns ORDER BY delta
DECLARE @totalCount AS NVARCHAR(MAX)= ''
SELECT @totalCount=CASE WHEN @totalCount='' THEN '' ELSE @totalCount+' + ' END + 'ISNULL(' + colName +',0)' FROM @dayColumns ORDER BY delta
-- Produce a SQL statement which outputs a variable number of pivoted columns
DECLARE @query AS NVARCHAR(MAX)
SELECT @query=
'declare @days TABLE (reportDay date, colName varchar(12))
INSERT INTO @days (reportDay, colName)
SELECT DATEADD(day,Delta,'''+CONVERT(varchar(22),@startDate,121)+'''), ''col''+CONVERT(varchar(12),DATEADD(day,delta,'''+CONVERT(varchar(22),@startDate,121)+'''),112) as colName from (
select (ROW_NUMBER() OVER (ORDER BY sysobjects.id))-1 as Delta FROM sysobjects
) daysAhead
WHERE Delta<='+CAST(@numberOfDays as varchar(10))+'
SELECT pivoted.*,'+@totalCount+' as total FROM (
SELECT * FROM (
select data.Name, d.colName, 1 as numRows
from @days d
LEFT OUTER JOIN data ON CAST(data.[Date] as DATE)=d.reportDay
) as s
PIVOT (
SUM(numRows) FOR colName in ('+@cols+')
) as pa
) as pivoted
WHERE Name is not null'
-- Run the query
EXEC (@query)
```
Output is:
```
Name col20150225 col20150226 col20150227 col20150228 total
------------------------------ ----------- ----------- ----------- ----------- -----------
ITEM A 2 1 NULL NULL 3
ITEM B NULL 2 NULL NULL 2
ITEM C NULL NULL 1 NULL 1
```
You can determine the date of each column by parsing the column header in your presentation code (it's format is colYYYYMMDD). |
28,762,226 | i need sql query for report from table item per day(fix day1-day31 as column) of the month when i input **month and year**.
This is my table (item)
ID | NAME | DATE
---------------------------------------------------
1 | ITEM A | 2015-2-25 13:37:49
2 | ITEM A | 2015-2-25 14:37:49
3 | ITEM A | 2015-2-26 13:30:55
4 | ITEM B | 2015-2-26 15:37:49
5 | ITEM B | 2015-2-26 17:57:49
6 | ITEM C | 2015-2-27 13:00:33
---
(input month=02 and year=2015)
What I need to achieve with a view is the following:
NAME | 1| 2| 3|…|25|26|27|28|29|30|31|Total
------------------------------------------------------
ITEM A| 0| 0| 0|…| 2 | 1 | 0 | 0 | 0 | 0 | 0 | 3
ITEM B| 0| 0| 0|…| 0 | 2 | 0 | 0 | 0 | 0 | 0 | 2
ITEM C| 0| 0| 0|…| 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1
---
Any ideas would be very much appreciated.
Thanks in advance.
Sorry this is my first post. | 2015/02/27 | [
"https://Stackoverflow.com/questions/28762226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4613455/"
] | This will do it for you. First test data:
```
CREATE TABLE data ([ID] int, [Name] varchar(30), [Date] datetime)
INSERT INTO data ([ID], [Name], [Date])
SELECT 1,'ITEM A','2015-2-25 13:37:49'
UNION ALL SELECT 2,'ITEM A','2015-2-25 14:37:49'
UNION ALL SELECT 3,'ITEM A','2015-2-26 13:30:55'
UNION ALL SELECT 4,'ITEM B','2015-2-26 15:37:49'
UNION ALL SELECT 5,'ITEM B','2015-2-26 17:57:49'
UNION ALL SELECT 6,'ITEM C','2015-2-27 13:00:33'
```
Then the query. Note you can use any data range, so if you want a full month just calculate that and put it in the @startDate and @endDate
```
DECLARE @startDate DATETIME='25-Feb-2015'
DECLARE @endDate DATETIME='28-Feb-2015'
DECLARE @numberOfDays INT = DATEDIFF(DAY, @startDate, @endDate)
declare @dayColumns TABLE (delta int, colName varchar(12))
-- Produce 1 row for each day in the report. Note that this is limited by the
-- number of objects in sysobjects (which is about 2000 so its a high limit)
-- Each row contains a delta date offset, @startDate+delta gives each date to report
-- which is converted to a valid SQL column name in the format colYYYYMMDD
INSERT INTO @dayColumns (delta, colName)
SELECT delta, 'col'+CONVERT(varchar(12),DATEADD(day,delta,@startDate),112) as colName from (
select (ROW_NUMBER() OVER (ORDER BY sysobjects.id))-1 as delta FROM sysobjects
) daysAhead
WHERE delta<=@numberOfDays
-- Create a comma seperated list of columns to report
DECLARE @cols AS NVARCHAR(MAX)= ''
SELECT @cols=CASE WHEN @cols='' THEN @cols ELSE @cols+',' END + colName FROM @dayColumns ORDER BY delta
DECLARE @totalCount AS NVARCHAR(MAX)= ''
SELECT @totalCount=CASE WHEN @totalCount='' THEN '' ELSE @totalCount+' + ' END + 'ISNULL(' + colName +',0)' FROM @dayColumns ORDER BY delta
-- Produce a SQL statement which outputs a variable number of pivoted columns
DECLARE @query AS NVARCHAR(MAX)
SELECT @query=
'declare @days TABLE (reportDay date, colName varchar(12))
INSERT INTO @days (reportDay, colName)
SELECT DATEADD(day,Delta,'''+CONVERT(varchar(22),@startDate,121)+'''), ''col''+CONVERT(varchar(12),DATEADD(day,delta,'''+CONVERT(varchar(22),@startDate,121)+'''),112) as colName from (
select (ROW_NUMBER() OVER (ORDER BY sysobjects.id))-1 as Delta FROM sysobjects
) daysAhead
WHERE Delta<='+CAST(@numberOfDays as varchar(10))+'
SELECT pivoted.*,'+@totalCount+' as total FROM (
SELECT * FROM (
select data.Name, d.colName, 1 as numRows
from @days d
LEFT OUTER JOIN data ON CAST(data.[Date] as DATE)=d.reportDay
) as s
PIVOT (
SUM(numRows) FOR colName in ('+@cols+')
) as pa
) as pivoted
WHERE Name is not null'
-- Run the query
EXEC (@query)
```
Output is:
```
Name col20150225 col20150226 col20150227 col20150228 total
------------------------------ ----------- ----------- ----------- ----------- -----------
ITEM A 2 1 NULL NULL 3
ITEM B NULL 2 NULL NULL 2
ITEM C NULL NULL 1 NULL 1
```
You can determine the date of each column by parsing the column header in your presentation code (it's format is colYYYYMMDD). | ```
select convert(varchar,PaymentDate,103) AS date,
DatePart(MONTH,PaymentDate) as month,
CAST(SUM(Total_Amount) as INT) as Revenue
from Tbl_Name
where YEAR(PaymentDate) = YEAR(CURRENT_TIMESTAMP)
AND MONTH(PaymentDate) = MONTH(CURRENT_TIMESTAMP)
GROUP BY convert(varchar,PaymentDate,103),
DatePart(MONTH,PaymentDate)
order by date;
``` |
28,762,226 | i need sql query for report from table item per day(fix day1-day31 as column) of the month when i input **month and year**.
This is my table (item)
ID | NAME | DATE
---------------------------------------------------
1 | ITEM A | 2015-2-25 13:37:49
2 | ITEM A | 2015-2-25 14:37:49
3 | ITEM A | 2015-2-26 13:30:55
4 | ITEM B | 2015-2-26 15:37:49
5 | ITEM B | 2015-2-26 17:57:49
6 | ITEM C | 2015-2-27 13:00:33
---
(input month=02 and year=2015)
What I need to achieve with a view is the following:
NAME | 1| 2| 3|…|25|26|27|28|29|30|31|Total
------------------------------------------------------
ITEM A| 0| 0| 0|…| 2 | 1 | 0 | 0 | 0 | 0 | 0 | 3
ITEM B| 0| 0| 0|…| 0 | 2 | 0 | 0 | 0 | 0 | 0 | 2
ITEM C| 0| 0| 0|…| 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1
---
Any ideas would be very much appreciated.
Thanks in advance.
Sorry this is my first post. | 2015/02/27 | [
"https://Stackoverflow.com/questions/28762226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4613455/"
] | You can do this using a PIVOT in your query
```
SELECT name,
[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9],
[10],
[11],
[12],
[13],
[14],
[15],
[16],
[17],
[18],
[19],
[20],
[21],
[22],
[23],
[24],
[25],
[26],
[27],
[28],
[29],
[30],
[31],
([1] + [2] + [3] + [4] + [5] + [6] + [7] + [8] + [9] + [10] + [11] + [12] + [13] + [14] + [15] + [16] + [17] + [18] + [19] + [20] + [21] + [22] + [23] + [24] + [25] + [26] + [27] + [28] + [29] + [30] + [31]) as total
FROM
(
SELECT Name,
id,
Datepart(day, [date]) day
FROM item
WHERE MONTH([date]) = 2 AND YEAR([date]) = 2015
) x
PIVOT
(
count(id)
FOR day IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31])
) p
``` | ```
select convert(varchar,PaymentDate,103) AS date,
DatePart(MONTH,PaymentDate) as month,
CAST(SUM(Total_Amount) as INT) as Revenue
from Tbl_Name
where YEAR(PaymentDate) = YEAR(CURRENT_TIMESTAMP)
AND MONTH(PaymentDate) = MONTH(CURRENT_TIMESTAMP)
GROUP BY convert(varchar,PaymentDate,103),
DatePart(MONTH,PaymentDate)
order by date;
``` |
13,695,522 | I am having trouble trying to loop through a multidimensional array using PHP. When I use the `print_r()` function, here is my output:
```
Array ( [0] => Array ( [fname] => [sname] => [address] => [address2] => [city] => [state] => Select State [zip] => [county] => United States [phone] => [fax] => [email] => [use_email] => on )
```
I have tried several techniques but none seem to work. Any help is appreciated! | 2012/12/04 | [
"https://Stackoverflow.com/questions/13695522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317740/"
] | easiest would just use a foreach statement:
```
foreach($yourarray as $array_element) {
$address = $array_element['address'];
$fname = $array_element['fname'];
...
}
``` | It looks like there is one more dimension before what you want to loop through. Try this.
```
foreach($array[0] as $key => $value) {
echo $key, ': ', $value;
}
``` |
13,695,522 | I am having trouble trying to loop through a multidimensional array using PHP. When I use the `print_r()` function, here is my output:
```
Array ( [0] => Array ( [fname] => [sname] => [address] => [address2] => [city] => [state] => Select State [zip] => [county] => United States [phone] => [fax] => [email] => [use_email] => on )
```
I have tried several techniques but none seem to work. Any help is appreciated! | 2012/12/04 | [
"https://Stackoverflow.com/questions/13695522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317740/"
] | you can do this by
```
foreach($array as $value) {
foreach($value as $val) {
echo $val;
}
}
``` | It looks like there is one more dimension before what you want to loop through. Try this.
```
foreach($array[0] as $key => $value) {
echo $key, ': ', $value;
}
``` |
13,695,522 | I am having trouble trying to loop through a multidimensional array using PHP. When I use the `print_r()` function, here is my output:
```
Array ( [0] => Array ( [fname] => [sname] => [address] => [address2] => [city] => [state] => Select State [zip] => [county] => United States [phone] => [fax] => [email] => [use_email] => on )
```
I have tried several techniques but none seem to work. Any help is appreciated! | 2012/12/04 | [
"https://Stackoverflow.com/questions/13695522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317740/"
] | Your code is:
```
$set = array( 0 => array ( 'fname' => '',
'sname' => '',
'address' => '',
'address2' => '',
'city' => '',
'state' => 'Select State',
'zip' => '',
'county' => 'United States',
'phone' => '',
'fax' => '',
'email' => '',
'use_email' => 'on')
);
$subArray = $set[0]; // <-- key line
foreach($subArray as $k => $v) {
printf("key: %s, value: %s\n", $k, $v);
}
```
Output:
```
key: fname, value:
key: sname, value:
key: address, value:
key: address2, value:
key: city, value:
key: state, value: Select State
key: zip, value:
key: county, value: United States
key: phone, value:
key: fax, value:
key: email, value:
key: use_email, value: on
```
You need to access the indexed array properly. | It looks like there is one more dimension before what you want to loop through. Try this.
```
foreach($array[0] as $key => $value) {
echo $key, ': ', $value;
}
``` |
13,695,522 | I am having trouble trying to loop through a multidimensional array using PHP. When I use the `print_r()` function, here is my output:
```
Array ( [0] => Array ( [fname] => [sname] => [address] => [address2] => [city] => [state] => Select State [zip] => [county] => United States [phone] => [fax] => [email] => [use_email] => on )
```
I have tried several techniques but none seem to work. Any help is appreciated! | 2012/12/04 | [
"https://Stackoverflow.com/questions/13695522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317740/"
] | easiest would just use a foreach statement:
```
foreach($yourarray as $array_element) {
$address = $array_element['address'];
$fname = $array_element['fname'];
...
}
``` | you can do this by
```
foreach($array as $value) {
foreach($value as $val) {
echo $val;
}
}
``` |
13,695,522 | I am having trouble trying to loop through a multidimensional array using PHP. When I use the `print_r()` function, here is my output:
```
Array ( [0] => Array ( [fname] => [sname] => [address] => [address2] => [city] => [state] => Select State [zip] => [county] => United States [phone] => [fax] => [email] => [use_email] => on )
```
I have tried several techniques but none seem to work. Any help is appreciated! | 2012/12/04 | [
"https://Stackoverflow.com/questions/13695522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317740/"
] | easiest would just use a foreach statement:
```
foreach($yourarray as $array_element) {
$address = $array_element['address'];
$fname = $array_element['fname'];
...
}
``` | Your code is:
```
$set = array( 0 => array ( 'fname' => '',
'sname' => '',
'address' => '',
'address2' => '',
'city' => '',
'state' => 'Select State',
'zip' => '',
'county' => 'United States',
'phone' => '',
'fax' => '',
'email' => '',
'use_email' => 'on')
);
$subArray = $set[0]; // <-- key line
foreach($subArray as $k => $v) {
printf("key: %s, value: %s\n", $k, $v);
}
```
Output:
```
key: fname, value:
key: sname, value:
key: address, value:
key: address2, value:
key: city, value:
key: state, value: Select State
key: zip, value:
key: county, value: United States
key: phone, value:
key: fax, value:
key: email, value:
key: use_email, value: on
```
You need to access the indexed array properly. |
4,274,388 | ```
string = "Jack and Jill went up the hill to fetch a pail of water. Jack fell down and broke his crown. And Jill came tumbling after. "
d = string.match(/(jack|jill)/i) # -> MatchData "Jill" 1:"Jill"
d.size # -> 1
```
This only match the first occurrence it seems.
`string.scan` does the job partially but it doesn't tell anything about the index of the matched pattern.
How do i get a list of all the matched instances of the pattern and their indices (positions)? | 2010/11/25 | [
"https://Stackoverflow.com/questions/4274388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/499097/"
] | You can use `.scan` and `$`` global variable, which means *The string to the left of the last successful match*, but it doesn't work inside usual `.scan`, so you need this *hack* (stolen from [this answer](https://stackoverflow.com/a/2257073/322020)):
```ruby
string = "Jack and Jill went up the hill to fetch a pail of water. Jack fell down and broke his crown. And Jill came tumbling after. "
string.to_enum(:scan, /(jack|jill)/i).map do |m,|
p [$`.size, m]
end
```
output:
```
[0, "Jack"]
[9, "Jill"]
[57, "Jack"]
[97, "Jill"]
```
**UPD:**
Note the behaviour of lookbehind – you get the index of the really matched part, not the *look* one:
```none
irb> "ab".to_enum(:scan, /ab/ ).map{ |m,| [$`.size, $~.begin(0), m] }
=> [[0, 0, "ab"]]
irb> "ab".to_enum(:scan, /(?<=a)b/).map{ |m,| [$`.size, $~.begin(0), m] }
=> [[1, 1, "b"]]
``` | Here's a modification of Nakilon's answer if you want to put just the locations of "Jack" into an array
```
location_array = Array.new
string = "Jack and Jack went up the hill to fetch a pail of Jack..."
string.to_enum(:scan,/(jack)/i).map do |m,|
location_array.push [$`.size]
end
``` |
10,458,660 | I'm trying to compare these three but it seems only `array_map` works.
```
$input = array( ' hello ','whsdf ',' lve you',' ');
$input2 = array( ' hello ','whsdf ',' lve you',' ');
$input3 = array( ' hello ','whsdf ',' lve you',' ');
$time_start = microtime(true);
$input = array_map('trim',$input);
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did array_map in $time seconds<br>";
foreach($input as $in){
echo "'$in': ".strlen($in)."<br>";
}
////////////////////////////////////////////////
$time_start = microtime(true);
array_walk($input2,'trim');
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did array_walk in $time seconds<br>";
foreach($input2 as $in){
echo "'$in': ".strlen($in)."<br>";
}
////////////////////////////////////////////////
$time_start = microtime(true);
foreach($input3 as $in){
$in = trim($in);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did foreach in $time seconds<br>";
foreach($input3 as $in){
echo "'$in': ".strlen($in)."<br>";
}
```
What Am I Doing Wrong? Here's the output:
```
Did array_map in 0.00018000602722168 seconds
'hello': 5
'whsdf': 5
'lve you': 7
'': 0
Did array_walk in 0.00014209747314453 seconds
' hello ': 10
'whsdf ': 41
' lve you': 37
' ': 30
Did foreach in 0.00012993812561035 seconds
' hello ': 10
'whsdf ': 41
' lve you': 37
' ': 30
```
It's not trimming for `array_walk` and the `foreach` loop. | 2012/05/05 | [
"https://Stackoverflow.com/questions/10458660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1099531/"
] | [`array_walk`](http://php.net/manual/en/function.array-walk.php) doesn't look at what result function gives. Instead it passes callback a reference to item value. So your code for it to work needs to be
```
function walk_trim(&$value) {
$value = trim($value);
}
```
`foreach` doesn't store changed values itself either. Change it to
```
foreach ($input3 as &$in) {
$in = trim($in);
}
```
[Read more about references](http://www.php.net/manual/en/language.references.whatdo.php). | As of **PHP 5.3** Anonymous Functions possible.
ex:
```
$arr = array('1<br/>','<a href="#">2</a>','<p>3</p>','<span>4</span>','<div>5</div>');
array_walk($arr, function(&$arg){
$arg = strip_tags($arg);
});
var_dump($arr); // 1,2,3,4,5 ;-)
```
Have fun. |
524,086 | I would appreciate if somebody could help me with the following problem
Q. Finding ~~maximum~~ minimum
$$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$ | 2013/10/13 | [
"https://math.stackexchange.com/questions/524086",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/59343/"
] | $$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$
Consider the following :
$a , \frac{1}{a}$ we know that $A.M. \geq G.M.$
$\therefore \frac{a+ \frac{1}{a}}{2} \geq \sqrt{a . \frac{1}{a}}$
$\Rightarrow \frac{a^2+1}{2a} \geq 1 $
$\Rightarrow a^2 + 1 \geq 2a $
$\Rightarrow (a-1)^2 \geq 0$
$\Rightarrow a \geq 1$
$\therefore $ the expression has only minimum value which is 1 and no maximum value.
The expression $$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$
has minimum value of 1 + 1 +1 +1 +1 +1+1 = 6 | Note that if $F(x,y,z) = \frac{x+y}{z}+\frac{x+z}{y} + \frac{y+z}{x}$, then $F(kx,ky,kz)=F(x,y,z),\ k>0$. So we will use
Lagrange multiplier method. Let $g(x,y,z)=x+y+z$. Constraint is $x+y+z=1$.
$$\nabla F = (\frac{1}{z}+\frac{1}{y} - \frac{y+z}{x^2},\frac{1}{z}+\frac{1}{x} - \frac{x+z}{y^2},\frac{1}{y}+\frac{1}{x} - \frac{x+y}{z^2} ) =\lambda \nabla g$$
So $$ \frac{x^2(z+y) -(z+y)^2}{x^2yz}=\frac{z^2(x+y) -(x+y)^2}{xyz^2}= \frac{y^2(z+x) -(z+x)^2}{xy^2z} =\lambda $$
$$ \frac{x^2(1-x) -(1-x)^2}{x^2yz}=\frac{z^2(1-z) -(1-z)^2}{xyz^2}= \frac{y^2(1-y) -(1-y)^2}{xy^2z} =\lambda $$
Note that $\lambda\neq 0$ by computation.
Hence we have $$ (xz-xyz-1)(x-z)=(xy-xyz-1)(x-y)=(yz-xyz-1)(y-z)=0$$
$x=z\neq y$ implies that $2x^3-3x^2+x-1=0$. But it has only one solution larger than $1$.
If $x,\ y,\ z$ are distinct, $xz=xy=yz$. Contradiction.
So $x=y=z$. $F(1/3,1/3,1/3)=6$ is minimum. |
524,086 | I would appreciate if somebody could help me with the following problem
Q. Finding ~~maximum~~ minimum
$$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$ | 2013/10/13 | [
"https://math.stackexchange.com/questions/524086",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/59343/"
] | $$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$
Consider the following :
$a , \frac{1}{a}$ we know that $A.M. \geq G.M.$
$\therefore \frac{a+ \frac{1}{a}}{2} \geq \sqrt{a . \frac{1}{a}}$
$\Rightarrow \frac{a^2+1}{2a} \geq 1 $
$\Rightarrow a^2 + 1 \geq 2a $
$\Rightarrow (a-1)^2 \geq 0$
$\Rightarrow a \geq 1$
$\therefore $ the expression has only minimum value which is 1 and no maximum value.
The expression $$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$
has minimum value of 1 + 1 +1 +1 +1 +1+1 = 6 | A more formal proof that there is no maximum follows from taking the first derivatives and comparing to zero, showing that if $(x\_0, y\_0, z\_0)$ is a maximum / minimum, it satisfies: $$x\_0 = y\_0 = z\_0$$
This means that you can calculate the Hessian by only doing two calculations to determine $f\_{xx}$ and $f\_{xy}$, showing that at the maximum, say $(x\_0,x\_0,x\_0)$:
$$H=\frac{2}{x\_0^2}\left(\begin{matrix} 2 & 1 & 1\\
1 & 2 & 1 \\ 1& 1 & 2 \end{matrix}\right)$$
Since $H$ is clearly positive definite, the function has no maximum. |
524,086 | I would appreciate if somebody could help me with the following problem
Q. Finding ~~maximum~~ minimum
$$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$ | 2013/10/13 | [
"https://math.stackexchange.com/questions/524086",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/59343/"
] | By letting $u = \frac xy$ , $v = \frac yz$, and $w = \frac zx$ , our expression becomes $(u + \frac1u) + (v + \frac1v) + (w + \frac1w)$ , whose minimum is thrice that of $f(t) = t + \frac1t$ , which is to be found among the roots of its first order derivative: $f'(t) = 1 - \frac1{t^2}$ , which vanishes for $t = \pm1$ . Since *t* is positive, the only viable solution thus becomes $t = 1$ , for which $f(t) = 1 + \frac11 = 2$ , which yields a minimum value of $3\cdot2 = 6$. | $$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$
Consider the following :
$a , \frac{1}{a}$ we know that $A.M. \geq G.M.$
$\therefore \frac{a+ \frac{1}{a}}{2} \geq \sqrt{a . \frac{1}{a}}$
$\Rightarrow \frac{a^2+1}{2a} \geq 1 $
$\Rightarrow a^2 + 1 \geq 2a $
$\Rightarrow (a-1)^2 \geq 0$
$\Rightarrow a \geq 1$
$\therefore $ the expression has only minimum value which is 1 and no maximum value.
The expression $$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$
has minimum value of 1 + 1 +1 +1 +1 +1+1 = 6 |
524,086 | I would appreciate if somebody could help me with the following problem
Q. Finding ~~maximum~~ minimum
$$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$ | 2013/10/13 | [
"https://math.stackexchange.com/questions/524086",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/59343/"
] | A more formal proof that there is no maximum follows from taking the first derivatives and comparing to zero, showing that if $(x\_0, y\_0, z\_0)$ is a maximum / minimum, it satisfies: $$x\_0 = y\_0 = z\_0$$
This means that you can calculate the Hessian by only doing two calculations to determine $f\_{xx}$ and $f\_{xy}$, showing that at the maximum, say $(x\_0,x\_0,x\_0)$:
$$H=\frac{2}{x\_0^2}\left(\begin{matrix} 2 & 1 & 1\\
1 & 2 & 1 \\ 1& 1 & 2 \end{matrix}\right)$$
Since $H$ is clearly positive definite, the function has no maximum. | Note that if $F(x,y,z) = \frac{x+y}{z}+\frac{x+z}{y} + \frac{y+z}{x}$, then $F(kx,ky,kz)=F(x,y,z),\ k>0$. So we will use
Lagrange multiplier method. Let $g(x,y,z)=x+y+z$. Constraint is $x+y+z=1$.
$$\nabla F = (\frac{1}{z}+\frac{1}{y} - \frac{y+z}{x^2},\frac{1}{z}+\frac{1}{x} - \frac{x+z}{y^2},\frac{1}{y}+\frac{1}{x} - \frac{x+y}{z^2} ) =\lambda \nabla g$$
So $$ \frac{x^2(z+y) -(z+y)^2}{x^2yz}=\frac{z^2(x+y) -(x+y)^2}{xyz^2}= \frac{y^2(z+x) -(z+x)^2}{xy^2z} =\lambda $$
$$ \frac{x^2(1-x) -(1-x)^2}{x^2yz}=\frac{z^2(1-z) -(1-z)^2}{xyz^2}= \frac{y^2(1-y) -(1-y)^2}{xy^2z} =\lambda $$
Note that $\lambda\neq 0$ by computation.
Hence we have $$ (xz-xyz-1)(x-z)=(xy-xyz-1)(x-y)=(yz-xyz-1)(y-z)=0$$
$x=z\neq y$ implies that $2x^3-3x^2+x-1=0$. But it has only one solution larger than $1$.
If $x,\ y,\ z$ are distinct, $xz=xy=yz$. Contradiction.
So $x=y=z$. $F(1/3,1/3,1/3)=6$ is minimum. |
524,086 | I would appreciate if somebody could help me with the following problem
Q. Finding ~~maximum~~ minimum
$$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$ | 2013/10/13 | [
"https://math.stackexchange.com/questions/524086",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/59343/"
] | By letting $u = \frac xy$ , $v = \frac yz$, and $w = \frac zx$ , our expression becomes $(u + \frac1u) + (v + \frac1v) + (w + \frac1w)$ , whose minimum is thrice that of $f(t) = t + \frac1t$ , which is to be found among the roots of its first order derivative: $f'(t) = 1 - \frac1{t^2}$ , which vanishes for $t = \pm1$ . Since *t* is positive, the only viable solution thus becomes $t = 1$ , for which $f(t) = 1 + \frac11 = 2$ , which yields a minimum value of $3\cdot2 = 6$. | Note that if $F(x,y,z) = \frac{x+y}{z}+\frac{x+z}{y} + \frac{y+z}{x}$, then $F(kx,ky,kz)=F(x,y,z),\ k>0$. So we will use
Lagrange multiplier method. Let $g(x,y,z)=x+y+z$. Constraint is $x+y+z=1$.
$$\nabla F = (\frac{1}{z}+\frac{1}{y} - \frac{y+z}{x^2},\frac{1}{z}+\frac{1}{x} - \frac{x+z}{y^2},\frac{1}{y}+\frac{1}{x} - \frac{x+y}{z^2} ) =\lambda \nabla g$$
So $$ \frac{x^2(z+y) -(z+y)^2}{x^2yz}=\frac{z^2(x+y) -(x+y)^2}{xyz^2}= \frac{y^2(z+x) -(z+x)^2}{xy^2z} =\lambda $$
$$ \frac{x^2(1-x) -(1-x)^2}{x^2yz}=\frac{z^2(1-z) -(1-z)^2}{xyz^2}= \frac{y^2(1-y) -(1-y)^2}{xy^2z} =\lambda $$
Note that $\lambda\neq 0$ by computation.
Hence we have $$ (xz-xyz-1)(x-z)=(xy-xyz-1)(x-y)=(yz-xyz-1)(y-z)=0$$
$x=z\neq y$ implies that $2x^3-3x^2+x-1=0$. But it has only one solution larger than $1$.
If $x,\ y,\ z$ are distinct, $xz=xy=yz$. Contradiction.
So $x=y=z$. $F(1/3,1/3,1/3)=6$ is minimum. |
524,086 | I would appreciate if somebody could help me with the following problem
Q. Finding ~~maximum~~ minimum
$$\frac{x+y}{z}+\frac{x+z}{y}+\frac{y+z}{x}(\text{where} ~~x,y,z>0)$$ | 2013/10/13 | [
"https://math.stackexchange.com/questions/524086",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/59343/"
] | By letting $u = \frac xy$ , $v = \frac yz$, and $w = \frac zx$ , our expression becomes $(u + \frac1u) + (v + \frac1v) + (w + \frac1w)$ , whose minimum is thrice that of $f(t) = t + \frac1t$ , which is to be found among the roots of its first order derivative: $f'(t) = 1 - \frac1{t^2}$ , which vanishes for $t = \pm1$ . Since *t* is positive, the only viable solution thus becomes $t = 1$ , for which $f(t) = 1 + \frac11 = 2$ , which yields a minimum value of $3\cdot2 = 6$. | A more formal proof that there is no maximum follows from taking the first derivatives and comparing to zero, showing that if $(x\_0, y\_0, z\_0)$ is a maximum / minimum, it satisfies: $$x\_0 = y\_0 = z\_0$$
This means that you can calculate the Hessian by only doing two calculations to determine $f\_{xx}$ and $f\_{xy}$, showing that at the maximum, say $(x\_0,x\_0,x\_0)$:
$$H=\frac{2}{x\_0^2}\left(\begin{matrix} 2 & 1 & 1\\
1 & 2 & 1 \\ 1& 1 & 2 \end{matrix}\right)$$
Since $H$ is clearly positive definite, the function has no maximum. |
7,231,649 | Let me use an example for what I'm looking for. On my phone I have a music player widget, when active and the phone times out, the player continues working (iPod style I get that).
BUT when you turn the phone back on, the player is visible and active above the unlocking slide bar.
Is this easy to do in java? giving the user access to the application above the unlock slider (before password).
Now I know we can easily put code to avoid sleep mode. But the app that I'm working on only needs to be viewed/modified every 10 or 20 minutes and keeping the phone on is a waste of battery. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7231649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/693526/"
] | This is a contentious issue:
* There are apps that do this. See [How to customize Android's LockScreen?](https://stackoverflow.com/questions/5829671/how-to-customize-androids-lockscreen) e.g. [WidgetLocker](https://play.google.com/store/apps/details?id=com.teslacoilsw.widgetlocker) - so it is not entirely impossible.
* However, Google does not recommend playing around with Android Lock Screens. Google has removed functionality for interacting with their OS lock screens (particularly as 2.2). More info on that [here](https://stackoverflow.com/a/5529805/383414).
But some useful effects can be managed. There are tricks involved.
* One trick is to replace the Android lock screen with a custom lock screen - essentially a Home Screen app that implements its own locking. I think that's how WidgetLocker works, but I'm not sure. There is a Home Screen demo app shipping with the Android SDK.
* Another trick is to use the `ACTION_SCREEN_ON` and `ACTION_SCREEN_OFF` Intent actions, coupled with `WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED` permission on your app. You can use these to change what is shown BEHIND *or* instead of the lock screen - which is very close to what the question asks (they need to view some info when the lock screen is in place).
I have an app that *displays information to the user when the lock screen is shown*, using the above techniques. Strictly speaking, it is not a custom Android lock screen, however, it creates the effect of customising the information shown when the phone is locked.
It shows info *behind the actual stock lock screen*. But you can also replace the screen that normally shows when the phone is locked.
---
**Below is a (minimal) demo app that shows how to display information when the phone is locked.** I forget where I got most of the code from, but its a mess of some demo ideas. I present it just to show what can be done - I am by no means saying this is anything like "good" production code.
When you run the app, and lock the phone, the app carries on playing the video. This screen replaces the lock screen.
It will take some work to turn this code into production code, but it may help readers.
YouTubeActivity.java:
---------------------
The important part is the last 2 lines that enable this activity to be visible when the phone is locked.
```
package com.youtube.demo;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.VideoView;
public class YouTubeActivity extends Activity
{
String SrcPath = "rtsp://v5.cache1.c.youtube.com/CjYLENy73wIaLQnhycnrJQ8qmRMYESARFEIJbXYtZ29vZ2xlSARSBXdhdGNoYPj_hYjnq6uUTQw=/0/0/0/video.3gp";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
VideoView myVideoView = (VideoView) findViewById(R.id.myvideoview);
myVideoView.setVideoURI(Uri.parse(SrcPath));
myVideoView.requestFocus();
myVideoView.start();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
}
```
main.xml:
---------
Nothing special here - just places a `VideoView` on the screen...
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView android:id="@+id/myvideoview"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
</LinearLayout>
```
AndroidManifest.xml:
--------------------
Absolutely stock manifest file - nothing interesting here.
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.youtube.demo" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".YouTubeActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
```
---
So there are **3 ways** I can think of to accomplish what the poster is looking for, or workarounds that might be useful to him:
* Do what WidgetLocker does - I don't know how exactly, and the developer is not telling.
* Change the background behind the stock lock screen.
* Overlay an activity instead of the stock lock screen (demo code provided). | There is [no API for drawing on lock screen](https://stackoverflow.com/questions/4065201/android-how-can-i-programmatically-draw-text-on-key-guard-screen-lock-screen), nor can you [replace lock screen](https://stackoverflow.com/questions/2758006/screen-lock-customization-for-android) with a custom one. SO you can not write an app for stock android phones that does this.
In order to do this you'd need to create a custom firmware or use non-standard features in rooted phones. |
35,479,494 | I'm editing a file in vim and my function looks like this:
```
function arrForeignCharacterMapping()
{
return array(
'<8a>'=>'S', '<9a>'=>'s', 'Ð'=>'Dj','<8e>'=>'Z', '<9e>'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A',
'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I',
'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U',
'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a',
'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i',
'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u',
'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', '<83>'=>'f'
);
}
```
This is roughly about translating accented characters etc into their "basic" versions. What are the `<8a>` etc though? They're single characters in vim (i.e. shown in a grey colour and the cursor "skips" over them in one movement.
I've tried googling them but it's tricky for obvious reasons. If it's "correct", can someone give me a link that correlates these codes with the unicode characters they represent?
Thanks! | 2016/02/18 | [
"https://Stackoverflow.com/questions/35479494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058739/"
] | you can google "unicode character map", its pretty common so I'm sure you will find many tools and one you would like.
this was one of the first results for me: <http://charmap.online-toolz.com/tools/character-map.php>
look at the unicode character value, as such:
[](https://i.stack.imgur.com/VjqyW.png) | not sure if you are looking for this. In vim
```
echo char2nr('ý',1)
```
will print `253` |
54,621,210 | I am trying to write a function that takes a string as input and returns a string with all vowels repeated 4 times.
*eg: `apple` becomes `aaaappleeee`*
It works for every vowel, except for *e*, in which it repeats *e* an egregious amount of times.
Python 3. I have tried playing with the replace function, changing the replacement value to `i+i+i+i`, `i*4`, `i(4)`, `(i+i)*2`, but nothing seems to help.
```
def exclamation(string):
for i in string:
if i in 'aeiou':
string = string.replace(i, i*4)
return string + '!'
```
`exclamation('excellent')` should return `eeeexceeeelleeeent!`
however, it returns:
`eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeexceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent!`
As stated, the function works fine for all other vowels, except *e*.
Thank you! | 2019/02/10 | [
"https://Stackoverflow.com/questions/54621210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10951091/"
] | You shall never modify something you're iterating over, store the modified word in a new variable. Modifing your code it would be something like
```
def exclamation(string):
new = ''
for i in string:
if i in 'aeiou':
new += i*4
else:
new += i
return new + '!'
``` | It's not that `e` is being treated differently, but rather that you're replacing each `e` with `eeee` for as many `e`s as there are in the word. If you try other words with multiples of the same vowel, you would see the same behavior there.
Instead of replacing for each vowel in the string, you should be doing each replacement once, which will effect every instance of that vowel in the string:
```
def exclamation(s):
for vowel in 'aeiou':
s = s.replace(vowel, vowel*4)
return s + '!'
print(exclamation('excellent'))
# 'eeeexceeeelleeeent!'
```
Note that this only works if the word is already lowercase (though that would be easy to fix, add capital vowels to the loop).
Another way of doing this would be to define a translation table to do all of the replacements at once:
```
trans = str.maketrans({vowel: vowel*4 for vowel in 'aeiou'})
def exclamation(s):
return s.translate(trans)
``` |
54,621,210 | I am trying to write a function that takes a string as input and returns a string with all vowels repeated 4 times.
*eg: `apple` becomes `aaaappleeee`*
It works for every vowel, except for *e*, in which it repeats *e* an egregious amount of times.
Python 3. I have tried playing with the replace function, changing the replacement value to `i+i+i+i`, `i*4`, `i(4)`, `(i+i)*2`, but nothing seems to help.
```
def exclamation(string):
for i in string:
if i in 'aeiou':
string = string.replace(i, i*4)
return string + '!'
```
`exclamation('excellent')` should return `eeeexceeeelleeeent!`
however, it returns:
`eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeexceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent!`
As stated, the function works fine for all other vowels, except *e*.
Thank you! | 2019/02/10 | [
"https://Stackoverflow.com/questions/54621210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10951091/"
] | For every vowel you’re iterating through, the loop checks the condition, replaces the content in the same string and then iterates by 1 which now is the same string but instead of the next new letter, it now has to deal with 3 more of the same vowel. For example:
Let’s talk about the string ‘excellent’. For the first vowel ‘e’, it is replaced with ‘eeee’ resulting in the string being ‘eeeexcellent’, now when the second loop begins it starts at index(1) which is still an ‘e’ and this keeps going on. **Never modify the iterable you’re iterating over.** | It's not that `e` is being treated differently, but rather that you're replacing each `e` with `eeee` for as many `e`s as there are in the word. If you try other words with multiples of the same vowel, you would see the same behavior there.
Instead of replacing for each vowel in the string, you should be doing each replacement once, which will effect every instance of that vowel in the string:
```
def exclamation(s):
for vowel in 'aeiou':
s = s.replace(vowel, vowel*4)
return s + '!'
print(exclamation('excellent'))
# 'eeeexceeeelleeeent!'
```
Note that this only works if the word is already lowercase (though that would be easy to fix, add capital vowels to the loop).
Another way of doing this would be to define a translation table to do all of the replacements at once:
```
trans = str.maketrans({vowel: vowel*4 for vowel in 'aeiou'})
def exclamation(s):
return s.translate(trans)
``` |
54,621,210 | I am trying to write a function that takes a string as input and returns a string with all vowels repeated 4 times.
*eg: `apple` becomes `aaaappleeee`*
It works for every vowel, except for *e*, in which it repeats *e* an egregious amount of times.
Python 3. I have tried playing with the replace function, changing the replacement value to `i+i+i+i`, `i*4`, `i(4)`, `(i+i)*2`, but nothing seems to help.
```
def exclamation(string):
for i in string:
if i in 'aeiou':
string = string.replace(i, i*4)
return string + '!'
```
`exclamation('excellent')` should return `eeeexceeeelleeeent!`
however, it returns:
`eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeexceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent!`
As stated, the function works fine for all other vowels, except *e*.
Thank you! | 2019/02/10 | [
"https://Stackoverflow.com/questions/54621210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10951091/"
] | You shall never modify something you're iterating over, store the modified word in a new variable. Modifing your code it would be something like
```
def exclamation(string):
new = ''
for i in string:
if i in 'aeiou':
new += i*4
else:
new += i
return new + '!'
``` | def exclamation(string):
```
result = ''
for i in string:
if i in 'aeiou':
vowel = i * 4
else:
vowel = i
result += vowel
return result + '!'
```
**The reason why replace didnt work for excellent is because we have 3 'e' in which means for each of the 'e' in the loop, replace will multiply by 4 which will definitely give you 12 'e's per one 'e' in excellent** |
54,621,210 | I am trying to write a function that takes a string as input and returns a string with all vowels repeated 4 times.
*eg: `apple` becomes `aaaappleeee`*
It works for every vowel, except for *e*, in which it repeats *e* an egregious amount of times.
Python 3. I have tried playing with the replace function, changing the replacement value to `i+i+i+i`, `i*4`, `i(4)`, `(i+i)*2`, but nothing seems to help.
```
def exclamation(string):
for i in string:
if i in 'aeiou':
string = string.replace(i, i*4)
return string + '!'
```
`exclamation('excellent')` should return `eeeexceeeelleeeent!`
however, it returns:
`eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeexceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent!`
As stated, the function works fine for all other vowels, except *e*.
Thank you! | 2019/02/10 | [
"https://Stackoverflow.com/questions/54621210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10951091/"
] | You shall never modify something you're iterating over, store the modified word in a new variable. Modifing your code it would be something like
```
def exclamation(string):
new = ''
for i in string:
if i in 'aeiou':
new += i*4
else:
new += i
return new + '!'
``` | For every vowel you’re iterating through, the loop checks the condition, replaces the content in the same string and then iterates by 1 which now is the same string but instead of the next new letter, it now has to deal with 3 more of the same vowel. For example:
Let’s talk about the string ‘excellent’. For the first vowel ‘e’, it is replaced with ‘eeee’ resulting in the string being ‘eeeexcellent’, now when the second loop begins it starts at index(1) which is still an ‘e’ and this keeps going on. **Never modify the iterable you’re iterating over.** |
54,621,210 | I am trying to write a function that takes a string as input and returns a string with all vowels repeated 4 times.
*eg: `apple` becomes `aaaappleeee`*
It works for every vowel, except for *e*, in which it repeats *e* an egregious amount of times.
Python 3. I have tried playing with the replace function, changing the replacement value to `i+i+i+i`, `i*4`, `i(4)`, `(i+i)*2`, but nothing seems to help.
```
def exclamation(string):
for i in string:
if i in 'aeiou':
string = string.replace(i, i*4)
return string + '!'
```
`exclamation('excellent')` should return `eeeexceeeelleeeent!`
however, it returns:
`eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeexceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent!`
As stated, the function works fine for all other vowels, except *e*.
Thank you! | 2019/02/10 | [
"https://Stackoverflow.com/questions/54621210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10951091/"
] | You shall never modify something you're iterating over, store the modified word in a new variable. Modifing your code it would be something like
```
def exclamation(string):
new = ''
for i in string:
if i in 'aeiou':
new += i*4
else:
new += i
return new + '!'
``` | It is happening because your loop will consider the replaced 'e's as the element of the string as well.
Here is what I am saying:
* String is excellent
* Iterate through the string and check if the letter is vowel
+ If the letter is vowel, write that vowel 4 times.
By following the above steps, we will find this result as the first iteration.
First iteration will work on the first letter which is 'e' and will replace it with 'eeee'. So at the end of the first iteration, our final string will be: **'eeeexcellent'**
Now for the second iteration, *it will consider the final string* we got after the first iteration. And for second iteration, the word to be consider will be 'e' only. So as you can see, you need to maintain the string as it is after each iteration, and save the replaced result to a new string. (it will always be a new string after all as string is not mutable)
```
def exclamation(string):
tmp = '' #taking temporary variable to store the current data
for i in string:
if i in 'aeiou':
tmp += i*4 # i*4 only if i is vowel
else:
tmp += i # keeping i as it is if it's not vowel
return tmp + '!'
```
You can also try list list comprehension which is easy to read and understand as well:
```
def exclamation(string):
newstr = [ i*4 if i in 'aeiou' else i for i in string]
return ''.join(newstr)+'!'
``` |
54,621,210 | I am trying to write a function that takes a string as input and returns a string with all vowels repeated 4 times.
*eg: `apple` becomes `aaaappleeee`*
It works for every vowel, except for *e*, in which it repeats *e* an egregious amount of times.
Python 3. I have tried playing with the replace function, changing the replacement value to `i+i+i+i`, `i*4`, `i(4)`, `(i+i)*2`, but nothing seems to help.
```
def exclamation(string):
for i in string:
if i in 'aeiou':
string = string.replace(i, i*4)
return string + '!'
```
`exclamation('excellent')` should return `eeeexceeeelleeeent!`
however, it returns:
`eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeexceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent!`
As stated, the function works fine for all other vowels, except *e*.
Thank you! | 2019/02/10 | [
"https://Stackoverflow.com/questions/54621210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10951091/"
] | For every vowel you’re iterating through, the loop checks the condition, replaces the content in the same string and then iterates by 1 which now is the same string but instead of the next new letter, it now has to deal with 3 more of the same vowel. For example:
Let’s talk about the string ‘excellent’. For the first vowel ‘e’, it is replaced with ‘eeee’ resulting in the string being ‘eeeexcellent’, now when the second loop begins it starts at index(1) which is still an ‘e’ and this keeps going on. **Never modify the iterable you’re iterating over.** | def exclamation(string):
```
result = ''
for i in string:
if i in 'aeiou':
vowel = i * 4
else:
vowel = i
result += vowel
return result + '!'
```
**The reason why replace didnt work for excellent is because we have 3 'e' in which means for each of the 'e' in the loop, replace will multiply by 4 which will definitely give you 12 'e's per one 'e' in excellent** |
54,621,210 | I am trying to write a function that takes a string as input and returns a string with all vowels repeated 4 times.
*eg: `apple` becomes `aaaappleeee`*
It works for every vowel, except for *e*, in which it repeats *e* an egregious amount of times.
Python 3. I have tried playing with the replace function, changing the replacement value to `i+i+i+i`, `i*4`, `i(4)`, `(i+i)*2`, but nothing seems to help.
```
def exclamation(string):
for i in string:
if i in 'aeiou':
string = string.replace(i, i*4)
return string + '!'
```
`exclamation('excellent')` should return `eeeexceeeelleeeent!`
however, it returns:
`eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeexceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent!`
As stated, the function works fine for all other vowels, except *e*.
Thank you! | 2019/02/10 | [
"https://Stackoverflow.com/questions/54621210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10951091/"
] | For every vowel you’re iterating through, the loop checks the condition, replaces the content in the same string and then iterates by 1 which now is the same string but instead of the next new letter, it now has to deal with 3 more of the same vowel. For example:
Let’s talk about the string ‘excellent’. For the first vowel ‘e’, it is replaced with ‘eeee’ resulting in the string being ‘eeeexcellent’, now when the second loop begins it starts at index(1) which is still an ‘e’ and this keeps going on. **Never modify the iterable you’re iterating over.** | It is happening because your loop will consider the replaced 'e's as the element of the string as well.
Here is what I am saying:
* String is excellent
* Iterate through the string and check if the letter is vowel
+ If the letter is vowel, write that vowel 4 times.
By following the above steps, we will find this result as the first iteration.
First iteration will work on the first letter which is 'e' and will replace it with 'eeee'. So at the end of the first iteration, our final string will be: **'eeeexcellent'**
Now for the second iteration, *it will consider the final string* we got after the first iteration. And for second iteration, the word to be consider will be 'e' only. So as you can see, you need to maintain the string as it is after each iteration, and save the replaced result to a new string. (it will always be a new string after all as string is not mutable)
```
def exclamation(string):
tmp = '' #taking temporary variable to store the current data
for i in string:
if i in 'aeiou':
tmp += i*4 # i*4 only if i is vowel
else:
tmp += i # keeping i as it is if it's not vowel
return tmp + '!'
```
You can also try list list comprehension which is easy to read and understand as well:
```
def exclamation(string):
newstr = [ i*4 if i in 'aeiou' else i for i in string]
return ''.join(newstr)+'!'
``` |
65,307,874 | Hello I am looking for a way to implement a hierarchical graph in JavaFX, as is the case with a company organization.
Ideally, the graph should be in a scrollable pane and the individual nodes of the graph should be able to be displayed (in a different pane) in order to get more information about an employee, etc. The whole thing runs over a database with a UUID system. I've heard of yfiles, VisFX and GraphViz, but somehow it didn't quite work with these methods, as I had imagined.
Is there any API that could help me with my problem? | 2020/12/15 | [
"https://Stackoverflow.com/questions/65307874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11895027/"
] | That depends on what you mean by "graph". If a tree view is sufficient, you can use a JavaFX Tree control to display the hierarchical graph - like a directory structure in an explorer window. If a TreeView is not sufficient, you will have to implement some control yourself.
If the information for each node in the graph can fit on a single line of one or more columns, you can also use a JavaFX TreeTableView. | I found this: [Graph Visualisation (like yFiles) in JavaFX](https://stackoverflow.com/questions/30679025/graph-visualisation-like-yfiles-in-javafx) and changed some code and finaly endet up with this:
[](https://i.stack.imgur.com/QdlVA.png)
code i changed in the main:
```
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.awt.Dimension;
import com.fxgraph.graph.CellType;
import com.fxgraph.graph.Graph;
import com.fxgraph.graph.Model;
import com.fxgraph.layout.base.Layout;
import com.fxgraph.layout.random.RandomLayout;
public class Main extends Application {
Graph graph = new Graph();
@Override
public void start(Stage primaryStage) {
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
BorderPane root = new BorderPane();
Pane rightPane = new Pane();
rightPane.setPrefWidth(width * 0.4);
rightPane.setPrefHeight(height);
Label infLbl = new Label("Infos");
infLbl.setStyle("-fx-font: 30 arial; -fx-text-fill: red; -fx-font-weight: bold;");
infLbl.setLayoutX(rightPane.getPrefWidth() * 0.1);
infLbl.setLayoutY(rightPane.getPrefHeight() * 0.1);
rightPane.getChildren().add(infLbl);
graph = new Graph();
ScrollPane scroll = graph.getScrollPane();
// scroll.setMaxWidth(width - width * 0.3);
root.setCenter(scroll);
root.setRight(rightPane);
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setWidth(width);
primaryStage.setHeight(height);
primaryStage.setScene(scene);
primaryStage.show();
addGraphComponents();
Layout layout = new RandomLayout(graph);
layout.execute();
}
private void addGraphComponents() {
Model model = graph.getModel();
graph.beginUpdate();
model.addCell("Cell A", CellType.RECTANGLE);
model.addCell("Cell B", CellType.RECTANGLE);
model.addCell("Cell C", CellType.RECTANGLE);
model.addCell("Cell D", CellType.TRIANGLE);
model.addCell("Cell E", CellType.TRIANGLE);
model.addCell("Cell F", CellType.RECTANGLE);
model.addCell("Cell G", CellType.RECTANGLE);
model.addEdge("Cell A", "Cell B");
model.addEdge("Cell A", "Cell C");
model.addEdge("Cell B", "Cell C");
model.addEdge("Cell C", "Cell D");
model.addEdge("Cell B", "Cell E");
model.addEdge("Cell D", "Cell F");
model.addEdge("Cell D", "Cell G");
graph.endUpdate();
}
public static void main(String[] args) {
launch(args);
}
}
```
and some changes in the RectangleCell class:
```
package com.fxgraph.cells;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import com.fxgraph.graph.Cell;
public class RectangleCell extends Cell {
public RectangleCell( String id) {
super( id);
Rectangle view = new Rectangle( 50,50);
view.setStroke(Color.DODGERBLUE);
view.setFill(Color.DODGERBLUE);
Label lbl = new Label(id);
//lbl.setClip(view);
lbl.setLabelFor(view);
StackPane stack = new StackPane();
stack.getChildren().addAll(view, lbl);
setView(stack);
}
}
```
maybe there is a way to add an hierarchical layout to this and can save a spot with id for the rectangle so that it could look like this (ids not shown in the final application):
[](https://i.stack.imgur.com/kdWiU.png) |
97,092 | I am in the process of building myself a fancy schmancy Raspberry Pi "laptop", and am trying to power it with a single cord/power supply. My strategy is to put together a small project box with 120VAC inputs, and the innards from a couple wall warts to provide 5VDC and 12VDC power. Before I start wiring crap together, I wanted to run my idea past some more experienced electri-gurus to make sure I'm not missing anything safety-wise. It seems like its the perfect solution in my mind, but want to make sure I'm not missing anything that I'd be expected to know if I wasn't self-taught.
My parts:
* I have an old laptop power supply that I've gutted. It's basically the cord and an empty plastic shell (2" x 3" x 5"-ish) with the male end for the plug, and the wires that were clipped from the PCB from the male cord receptacle.
* I've gutted 12VDC/2A and 5VDC/10A wall warts; I'm left with PCBs that have wires leading to the board, and barrel connectors coming off the board.
If I connect the three hots, the three neutrals and the three grounds from the PCB and power supply inputs, this will leave me with 120VAC feeding the box and getting shared by 2 PCBs that, upon testing SHOULD be putting out 12VDC, 2A and 5VDC, 10A.
Am I thinking about that right? In my mind, it's like I've got two wall warts in a power strip, minus the power strip.
Here's my power needs:
* The Raspberry Pi: 5V, 700-1000mA
* A powered USB hub: 5V, 1A (based on the 5V, 1000mA PS that came with it)
* A powered USB WiFi interface: 5V, .5A ('cause it's USB...amperage is a TOTAL guess based on no information whatsoever).
* A portable USB keyboard: 5V, .5A ('cause it's USB...amperage is a TOTAL guess based on no information whatsoever).
* A 4" LCD monitor, 12V, 0.53W (which, by my math is way under 2A).
The 12VDC barrel fits the 12V monitor, so that's set. The 5VDC output needs to have the barrel connector replaced, and as long as I'n stripping wires, I'll be adding 3 USB ports to the power supply for device charging, and plan to split the 5VDC output between the individual USBs and the cable that will supply power to the hub--the hub will supply power to all the Raspberry Pi devices, 3A. With 10A supplied, those 3 extra charging ports won't be an issue unless my phone decides to draw 7A+ for charging. Am I good with that concept as well?
Please let me know if I'm missing any fundamental safety concepts for putting this thing together, and if appropriate, an appropriate link for where I can research & read about these concepts. | 2014/01/20 | [
"https://electronics.stackexchange.com/questions/97092",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/10660/"
] | I think this is not a good idea. You should use a 120V power cord attached to a fused power entry module <http://www.digikey.com/product-search/en/connectors-interconnects/power-entry-connectors-inlets-outlets-modules/1442743>, in turn connected to the right 5V/12V AC to DC converter rated for the currents you're interested in.
Alternatively, just use a 12V wall wart with a high enough current rating and appropriate DC to DC converters or voltage regulators (linear or switching), with the whole deal fused. | Using hacked together power supplies can be dangerous if you aren't sure what you are doing.
Luckily there are tons of off the shelf power supplies thay already do exactly what you want - 5v and 12v in one supply. You will find them for many external hard drives with a 3 (5v, 12v and gnd) or sometimes 4 pin (seperate grounds) cable.
I would simply take the connector off an old external hard drive enclosure and use its power adapter as is - its already been tested by the appropriate regulatoey agencies to not be likely to burn your house down. |
97,092 | I am in the process of building myself a fancy schmancy Raspberry Pi "laptop", and am trying to power it with a single cord/power supply. My strategy is to put together a small project box with 120VAC inputs, and the innards from a couple wall warts to provide 5VDC and 12VDC power. Before I start wiring crap together, I wanted to run my idea past some more experienced electri-gurus to make sure I'm not missing anything safety-wise. It seems like its the perfect solution in my mind, but want to make sure I'm not missing anything that I'd be expected to know if I wasn't self-taught.
My parts:
* I have an old laptop power supply that I've gutted. It's basically the cord and an empty plastic shell (2" x 3" x 5"-ish) with the male end for the plug, and the wires that were clipped from the PCB from the male cord receptacle.
* I've gutted 12VDC/2A and 5VDC/10A wall warts; I'm left with PCBs that have wires leading to the board, and barrel connectors coming off the board.
If I connect the three hots, the three neutrals and the three grounds from the PCB and power supply inputs, this will leave me with 120VAC feeding the box and getting shared by 2 PCBs that, upon testing SHOULD be putting out 12VDC, 2A and 5VDC, 10A.
Am I thinking about that right? In my mind, it's like I've got two wall warts in a power strip, minus the power strip.
Here's my power needs:
* The Raspberry Pi: 5V, 700-1000mA
* A powered USB hub: 5V, 1A (based on the 5V, 1000mA PS that came with it)
* A powered USB WiFi interface: 5V, .5A ('cause it's USB...amperage is a TOTAL guess based on no information whatsoever).
* A portable USB keyboard: 5V, .5A ('cause it's USB...amperage is a TOTAL guess based on no information whatsoever).
* A 4" LCD monitor, 12V, 0.53W (which, by my math is way under 2A).
The 12VDC barrel fits the 12V monitor, so that's set. The 5VDC output needs to have the barrel connector replaced, and as long as I'n stripping wires, I'll be adding 3 USB ports to the power supply for device charging, and plan to split the 5VDC output between the individual USBs and the cable that will supply power to the hub--the hub will supply power to all the Raspberry Pi devices, 3A. With 10A supplied, those 3 extra charging ports won't be an issue unless my phone decides to draw 7A+ for charging. Am I good with that concept as well?
Please let me know if I'm missing any fundamental safety concepts for putting this thing together, and if appropriate, an appropriate link for where I can research & read about these concepts. | 2014/01/20 | [
"https://electronics.stackexchange.com/questions/97092",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/10660/"
] | Areas of concern:
1. The mains connections between the wall-wart PCBs and the mains wires going to the cord. Ideally these need to be tied together in a mechanically secure manner - soldered and taped would be fine, as would bringing them to a terminal block with ring terminals.
2. The mechanical security of the wall-wart PCBs. They cannot flop around inside the case - there must be minimum creepage and clearance between primary and secondary which cannot be guaranteed if they can bounce about freely inside the box. Any secondary circuit is not allow to approach any primary circuit else there's a shock hazard.
3. The environmental security of the new case. Wall-warts are fairly impenetrable. By cracking them open and stuffing them into another shell that *was* well-sealed, they're not so impenetrable now. What happens if you inadvertently spill water on the case?
4. Lack of safety approval. Any safety approvals on those little wall-warts are null and void as soon as you crack them open and start attaching wires to them. Should the unlikely happen and your improvised brick goes up in flames, good luck collecting any insurance money. | Using hacked together power supplies can be dangerous if you aren't sure what you are doing.
Luckily there are tons of off the shelf power supplies thay already do exactly what you want - 5v and 12v in one supply. You will find them for many external hard drives with a 3 (5v, 12v and gnd) or sometimes 4 pin (seperate grounds) cable.
I would simply take the connector off an old external hard drive enclosure and use its power adapter as is - its already been tested by the appropriate regulatoey agencies to not be likely to burn your house down. |
34,659,636 | i'm new to meteor framework
I want to fetch single from the collection
```
AccountNames = new Mongo.Collection("AccountTypeMaster");
```
I created a collection using
```
db.createCollection("AccountTypeMaster")
this.helpers({
AccountNames: () => {
return AccountNames.find({}, {fields: {name: 1}});
}
});
```
Using above query i'm unable to fetch single field "name" from collection.
I'm now sure what's wrong with my code. | 2016/01/07 | [
"https://Stackoverflow.com/questions/34659636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5220060/"
] | You need to change how you instantiate your collection. The correct Meteor syntax would be:
```
AccountNames = new Mongo.Collection("AccountTypeMaster");
```
Helpers also need to be attached to a template. Remember, helpers only run on client-side code.
```
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: function () {
return AccountNames.find({}, { fields: { name: 1 } });
}
});
}
``` | Create Client folder in your project and put client side code into that folder.[To create collection in mongodb](https://www.meteor.com/tutorials/blaze/collections)
```
Template.name.helpers({
fun: function() {
return AccountNames.find({},{name: 1}).fetch();
})
``` |
17,605,290 | I have the following 3 tables. This is just a small section of the data, I left out most rows and other columns that I'm not querying against. If it would be helpful to include the full table(s) let me know and I can figure out how to post them.
**infocoms**
```
id items_id itemtype value
1735 21 Software 0.0000
1736 22 Software 0.0000
1739 21 Peripheral 151.2500
1741 23 Peripheral 150.5000
1742 24 Peripheral 0.0000
1743 25 Peripheral 0.0000
```
**locations**
```
id name
34 Anaheim
35 Kirkland
36 Palm Springs
37 Tacoma
```
**peripherals**
```
id name locations_id
11 Logitech USB Wheel Mouse 0
12 Samsung Slate Dock 17
21 USB Scan Gun with Stand 34
23 USB Scan Gun with Stand 63
24 USB Scan Gun with Stand 45
26 USB Scan Gun with Stand 39
```
I am running the following query against these tables:
```
SELECT peripherals.name, infocoms.value, locations.name AS Branch
FROM peripherals
JOIN infocoms ON peripherals.id = infocoms.items_id
JOIN locations ON peripherals.locations_id = locations.id
WHERE (peripherals.name = 'USB Scan Gun with Stand'
AND peripherals.locations_id != '0')
GROUP BY peripherals.id ORDER BY locations.name ASC
```
I get the right number of rows returned however the value shows everything as 0.0000 instead of where there are actual amounts (151.25 and 150.50).
Any help or insight would be greatly appreciated. Thanks. | 2013/07/11 | [
"https://Stackoverflow.com/questions/17605290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2573866/"
] | Comment (because I do not have the reputation) : "value" and "name" should be encased in back-ticks (``) because they are reserved words.
But looking at your code a little closer I find that you are grouping by location.name even though many of the values are duplicated when you do an `JOIN ON peripherals.locations_id = locations.id.`
What happens afterwards is that you `GROUP` the rest of the statements by location.name giving the first result of all of the locations that do not have a location name associated to the peripherals.locations\_id
Try not using `GROUPING BY` and see what you get. In order to get the results that you want you need to either omit the JOIN ON peripherals.locations\_id = locations.id or associate every peripials.locations\_id to an appropriate locations.id | @Eugene Scray is right about GROUP BY being the reason why you see only some values.
To keep columns "ungrouped", you need to add those columns into the GROUPING clause. For example:
```
GROUP BY peripherals.id, infocom.value
``` |
17,605,290 | I have the following 3 tables. This is just a small section of the data, I left out most rows and other columns that I'm not querying against. If it would be helpful to include the full table(s) let me know and I can figure out how to post them.
**infocoms**
```
id items_id itemtype value
1735 21 Software 0.0000
1736 22 Software 0.0000
1739 21 Peripheral 151.2500
1741 23 Peripheral 150.5000
1742 24 Peripheral 0.0000
1743 25 Peripheral 0.0000
```
**locations**
```
id name
34 Anaheim
35 Kirkland
36 Palm Springs
37 Tacoma
```
**peripherals**
```
id name locations_id
11 Logitech USB Wheel Mouse 0
12 Samsung Slate Dock 17
21 USB Scan Gun with Stand 34
23 USB Scan Gun with Stand 63
24 USB Scan Gun with Stand 45
26 USB Scan Gun with Stand 39
```
I am running the following query against these tables:
```
SELECT peripherals.name, infocoms.value, locations.name AS Branch
FROM peripherals
JOIN infocoms ON peripherals.id = infocoms.items_id
JOIN locations ON peripherals.locations_id = locations.id
WHERE (peripherals.name = 'USB Scan Gun with Stand'
AND peripherals.locations_id != '0')
GROUP BY peripherals.id ORDER BY locations.name ASC
```
I get the right number of rows returned however the value shows everything as 0.0000 instead of where there are actual amounts (151.25 and 150.50).
Any help or insight would be greatly appreciated. Thanks. | 2013/07/11 | [
"https://Stackoverflow.com/questions/17605290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2573866/"
] | Comment (because I do not have the reputation) : "value" and "name" should be encased in back-ticks (``) because they are reserved words.
But looking at your code a little closer I find that you are grouping by location.name even though many of the values are duplicated when you do an `JOIN ON peripherals.locations_id = locations.id.`
What happens afterwards is that you `GROUP` the rest of the statements by location.name giving the first result of all of the locations that do not have a location name associated to the peripherals.locations\_id
Try not using `GROUPING BY` and see what you get. In order to get the results that you want you need to either omit the JOIN ON peripherals.locations\_id = locations.id or associate every peripials.locations\_id to an appropriate locations.id | In the `WHERE` clause I added `AND infocoms.itemtype = 'Peripheral'` which returned the correct number of of rows along with the appropriate value(s). |
414,465 | Is every $ \mathbb{R}P^{2n} $ bundle over the circle trivial?
Are there exactly two $ \mathbb{R}P^{2n+1} $ bundles over the circle?
This is a cross-post of (part of) my MSE question
<https://math.stackexchange.com/questions/4349052/diffeomorphisms-of-spheres-and-real-projective-spaces>
which has been up for a couple weeks and got 8 upvotes and some nice comments but no answers.
My intuition for thinking both answer are yes is that there are exactly 2 sphere bundles over the circle. The trivial one and then the non-trivial (and non-orientable) one which can be realized as the mapping torus of an orientation reversing map of the sphere. So importing that intuition to projective spaces then the orientable $ \mathbb{R}P^{2n+1} $ should have a nontrivial (and non orientable) bundle over the circle while the non orientable $ \mathbb{R}P^{2n} $ should have only the trivial bundle. For $ n=1 $ this checks out since that projective space is orientable and thus we have exactly two bundles over the circle (the trivial one=the 2 torus and the nontrivial one=the Klein bottle). | 2022/01/23 | [
"https://mathoverflow.net/questions/414465",
"https://mathoverflow.net",
"https://mathoverflow.net/users/387190/"
] | As Sam Hopkins commented, 8 vertices are enough. Let $Q$ be the pentagon from the picture and let $\pi$ be the plane containing it. Now we can define the triangle $P$ as a triangle of less diameter than the black segment and intersecting $\pi$ at two points: one point $a\_0$ in the open blue region $B$ and one point $b\_0$ in the open green region $G$. $P$ and $Q$ are not linked, and it is intuitively clear that they are interlocked, but let´s prove it in detail.
[](https://i.stack.imgur.com/c0Tuwm.png)
Suppose there is a path of triangles $P\_t=i\_t(P)$ going to infinity, such that $P\_t$ is disjoint with $Q$ for all $t\in[0,\infty)$ and $i\_t:P\to\mathbb{R}^3$ is a continuous path of isometries (continuous in the supremum norm for functions $P\to\mathbb{R}^3$) with $i\_0=Id\_P$. Let´s try to derive a contradiction.
**Lemma 1**: Let $i$ be an isometry such that $i(P)$ intersects $\pi$ at exactly two points $a,b$. Then $\forall\varepsilon>0\;\exists\delta>0$ such that for any isometry $j$ with $d(i,j)<\delta$, $j(P)$ intersects $\pi$ at two points $a',b'$, with $d(a,a')<\varepsilon$ and $d(b,b')<\varepsilon$.
Proof: First of all, if $d(i,j)$ is small enough, $j(P)$ will intersect $\pi$ in two points, because the images by $j$ of at least two vertices of the triangle will be outside $\pi$.
Now consider the function $F(x,y)=$ intersection of the line passing through $x,y$ and $\pi$, defined in an open subset of $\mathbb{R}^6$. This function is continuous in its domain.
Suppose $a$ is not a vertex of the triangle. Then it is in the edge formed by two vertices $i(v\_1),i(v\_2)$, each in one half space of $\pi$. By continuity of $F$, if $d(i,j)$ is small enough we have a point $a'=F(j(v\_1),j(v\_2))$ in $j(P)$ at distance $<\varepsilon$ of $a$.
So the lemma works when $a,b$ are not vertices of the triangle. $a$ and $b$ cannot both be vertices of the triangle, so suppose $a$ is a vertex, $a=i(v\_1)$ with $v\_1$ a vertex of $P$, and $b$ is not. Then for $d(i,j)$ small enough both $F(j(v\_1),j(v\_2))$ and $F(j(v\_1),j(v\_3))$ will be at distance $<\varepsilon$ from $a$, so the one which is in $j(P)$ will be the point $a'$. $\square$
Now that we are done with the lemma 1, we can define
$$k=\sup\{t>0;P\_s\textit{ intersects $\pi$ at two points, one in $B$ and one in $G$, }\forall s\in[0,t)\}.$$
**Lemma 2**: $k>0$, and in $[0,k)$ there are paths $a\_t$, $b\_t$ such that $\{a\_t,b\_t\}=P\_t\cap A\;\forall t<k$.
Proof: By lemma 1, there is some $\varepsilon>0$ such that $\forall t\in [0,\varepsilon)$, $P\_t\cap A$ consists on two points, one in $G$ and one in $B$, so $k>0$. Let $a\_t$ be the point in $B$ and $b\_t$ be the point in $B$. By lemma 1 again, $a\_t$ and $b\_t$ are continuous in $[0,\varepsilon)$. Now consider the maximum $\varepsilon$ such that the $a\_t$ and $b\_t$ are defined in $[0,\varepsilon)$. Then $\varepsilon=k$, because if not, by the same argument using lemma 1, $a\_t$ and $b\_t$ will be defined in a neighborhood of $\varepsilon$.$\square$
Now let´s see that $P\_k$ has to intersect $Q$, leading to a contradiction. First of all, $P\_k$ has to intersect $Q$ in at least two points, one point $a\_k\in\overline{B}$ and one point $b\_k\in\overline{D}$. To prove this, let $t\_n$ be an ascending sequence, $t\_n\to k$, such that $a\_{t\_n}$ is convergent. Call $p\_n=i\_{t\_n}^{-1}(a\_n)$, we can suppose that $p\_n$ converges to some point $p\in P$ after taking a subsequence. Finally, we can let $a\_k$ be $i\_k(p)=\lim\_n i\_{t\_n}(p\_n)$, and similarly with $b\_k$. Now we can consider two cases:
If $P\_k$ intersects $\pi$ only at $a\_k$ and $b\_k$ we cannot have $a\_k\in A$ and $b\_k\in B$: that would contradict the definition of $k$. So either $a\_k\in\partial B\setminus Q$ and $b\_k\in\overline{G}$ or $b\_k\in\partial G\setminus Q$ and $a\_k\in\overline{B}$. Both cases are impossible, because $d(\partial B\setminus Q, G)$ and $d(\partial G\setminus Q, B)$ are both bigger than the diameter of $P$.
So $P\_k$ has to intersect $\pi$ in an edge. For the last time, we will consider two cases:
If $a\_k$ and $b\_k$ are both contained in the edge, then the edge intersects $Q$, which is a contradiction.
If not, the whole $P$ has to be contained in $\pi$. Consider an edge of the triangle containing the point $a\_k$. As the edge doesn´t intersect $Q$, one of its vertices must be in $B$. There is also other vertex in $G$ (one of the vertices of the edge containing $b\_k$), so the edge joining those two vertices must intersect $Q$, a contradiction.$\\[20pt]$
P.S: I had some comments regarding whether there are $P,Q$ as in the question with $7$ total vertices but they were wrong (I had not considered one case). An argument that they do not exist is given in Del's answer. | I think that 8 might be possible, by interlocking two Star Trek symbols as shown below.
[](https://i.stack.imgur.com/RyurZ.png)
**Adendum:** This candidate may not work, as quarague points out, but I leave it as a potential "how not to" example. There are other ways to cross the two figures, while they remain unlinked, and one of these variations could be more promising. Also I think it is important to specify whether the loops have any thickness or not. Some configurations may interlock assuming there is nonzero thickness. |
414,465 | Is every $ \mathbb{R}P^{2n} $ bundle over the circle trivial?
Are there exactly two $ \mathbb{R}P^{2n+1} $ bundles over the circle?
This is a cross-post of (part of) my MSE question
<https://math.stackexchange.com/questions/4349052/diffeomorphisms-of-spheres-and-real-projective-spaces>
which has been up for a couple weeks and got 8 upvotes and some nice comments but no answers.
My intuition for thinking both answer are yes is that there are exactly 2 sphere bundles over the circle. The trivial one and then the non-trivial (and non-orientable) one which can be realized as the mapping torus of an orientation reversing map of the sphere. So importing that intuition to projective spaces then the orientable $ \mathbb{R}P^{2n+1} $ should have a nontrivial (and non orientable) bundle over the circle while the non orientable $ \mathbb{R}P^{2n} $ should have only the trivial bundle. For $ n=1 $ this checks out since that projective space is orientable and thus we have exactly two bundles over the circle (the trivial one=the 2 torus and the nontrivial one=the Klein bottle). | 2022/01/23 | [
"https://mathoverflow.net/questions/414465",
"https://mathoverflow.net",
"https://mathoverflow.net/users/387190/"
] | It is not possible with 7 (i.e., with a triangle $T$ and a quadrilateral $Q$). I write a rough proof.
First, any quadrilateral $Q$ lying in a plane $\pi$ can be partitioned in two triangles $Q\_1$ and $Q\_2$, whose common edge is a diagonal $d$ of $Q$. Now the intersection of the triangle $T$ with $\pi$ consists of two points (otherwise they are coplanar and the conclusion is trivial). Since the polygons are not linked, there are two cases: either both points lie outside $Q$, or they both lie inside $Q$.
Case 1: both lie outside. An inspection of the cases shows that we can just translate $T$ in direction parallel to one of the bisectors of the triangles $Q\_1$ or $Q\_2$ starting from one of the vertices not belonging to $d$.
Case 2: both lie inside. We will consider a modified problem: given a quadrilateral $Q$ and two initial points $x(0),y(0)$ inside it, find two continuous curves $x(t),y(t)$ such that the distance between the two is decreasing in time to 0, and they never lie in $Q$. The solution is, e.g., a linear homotopy that sends both points to the midpoint of $d$. Now we only have to realize $x(t)$ and $y(t)$ as the intersections of $T$ and the plane $\pi$. One can convince themselves that this is possible by pulling $T$ in direction orthogonal to $\pi$ while translating it. | I think that 8 might be possible, by interlocking two Star Trek symbols as shown below.
[](https://i.stack.imgur.com/RyurZ.png)
**Adendum:** This candidate may not work, as quarague points out, but I leave it as a potential "how not to" example. There are other ways to cross the two figures, while they remain unlinked, and one of these variations could be more promising. Also I think it is important to specify whether the loops have any thickness or not. Some configurations may interlock assuming there is nonzero thickness. |
414,465 | Is every $ \mathbb{R}P^{2n} $ bundle over the circle trivial?
Are there exactly two $ \mathbb{R}P^{2n+1} $ bundles over the circle?
This is a cross-post of (part of) my MSE question
<https://math.stackexchange.com/questions/4349052/diffeomorphisms-of-spheres-and-real-projective-spaces>
which has been up for a couple weeks and got 8 upvotes and some nice comments but no answers.
My intuition for thinking both answer are yes is that there are exactly 2 sphere bundles over the circle. The trivial one and then the non-trivial (and non-orientable) one which can be realized as the mapping torus of an orientation reversing map of the sphere. So importing that intuition to projective spaces then the orientable $ \mathbb{R}P^{2n+1} $ should have a nontrivial (and non orientable) bundle over the circle while the non orientable $ \mathbb{R}P^{2n} $ should have only the trivial bundle. For $ n=1 $ this checks out since that projective space is orientable and thus we have exactly two bundles over the circle (the trivial one=the 2 torus and the nontrivial one=the Klein bottle). | 2022/01/23 | [
"https://mathoverflow.net/questions/414465",
"https://mathoverflow.net",
"https://mathoverflow.net/users/387190/"
] | As Sam Hopkins commented, 8 vertices are enough. Let $Q$ be the pentagon from the picture and let $\pi$ be the plane containing it. Now we can define the triangle $P$ as a triangle of less diameter than the black segment and intersecting $\pi$ at two points: one point $a\_0$ in the open blue region $B$ and one point $b\_0$ in the open green region $G$. $P$ and $Q$ are not linked, and it is intuitively clear that they are interlocked, but let´s prove it in detail.
[](https://i.stack.imgur.com/c0Tuwm.png)
Suppose there is a path of triangles $P\_t=i\_t(P)$ going to infinity, such that $P\_t$ is disjoint with $Q$ for all $t\in[0,\infty)$ and $i\_t:P\to\mathbb{R}^3$ is a continuous path of isometries (continuous in the supremum norm for functions $P\to\mathbb{R}^3$) with $i\_0=Id\_P$. Let´s try to derive a contradiction.
**Lemma 1**: Let $i$ be an isometry such that $i(P)$ intersects $\pi$ at exactly two points $a,b$. Then $\forall\varepsilon>0\;\exists\delta>0$ such that for any isometry $j$ with $d(i,j)<\delta$, $j(P)$ intersects $\pi$ at two points $a',b'$, with $d(a,a')<\varepsilon$ and $d(b,b')<\varepsilon$.
Proof: First of all, if $d(i,j)$ is small enough, $j(P)$ will intersect $\pi$ in two points, because the images by $j$ of at least two vertices of the triangle will be outside $\pi$.
Now consider the function $F(x,y)=$ intersection of the line passing through $x,y$ and $\pi$, defined in an open subset of $\mathbb{R}^6$. This function is continuous in its domain.
Suppose $a$ is not a vertex of the triangle. Then it is in the edge formed by two vertices $i(v\_1),i(v\_2)$, each in one half space of $\pi$. By continuity of $F$, if $d(i,j)$ is small enough we have a point $a'=F(j(v\_1),j(v\_2))$ in $j(P)$ at distance $<\varepsilon$ of $a$.
So the lemma works when $a,b$ are not vertices of the triangle. $a$ and $b$ cannot both be vertices of the triangle, so suppose $a$ is a vertex, $a=i(v\_1)$ with $v\_1$ a vertex of $P$, and $b$ is not. Then for $d(i,j)$ small enough both $F(j(v\_1),j(v\_2))$ and $F(j(v\_1),j(v\_3))$ will be at distance $<\varepsilon$ from $a$, so the one which is in $j(P)$ will be the point $a'$. $\square$
Now that we are done with the lemma 1, we can define
$$k=\sup\{t>0;P\_s\textit{ intersects $\pi$ at two points, one in $B$ and one in $G$, }\forall s\in[0,t)\}.$$
**Lemma 2**: $k>0$, and in $[0,k)$ there are paths $a\_t$, $b\_t$ such that $\{a\_t,b\_t\}=P\_t\cap A\;\forall t<k$.
Proof: By lemma 1, there is some $\varepsilon>0$ such that $\forall t\in [0,\varepsilon)$, $P\_t\cap A$ consists on two points, one in $G$ and one in $B$, so $k>0$. Let $a\_t$ be the point in $B$ and $b\_t$ be the point in $B$. By lemma 1 again, $a\_t$ and $b\_t$ are continuous in $[0,\varepsilon)$. Now consider the maximum $\varepsilon$ such that the $a\_t$ and $b\_t$ are defined in $[0,\varepsilon)$. Then $\varepsilon=k$, because if not, by the same argument using lemma 1, $a\_t$ and $b\_t$ will be defined in a neighborhood of $\varepsilon$.$\square$
Now let´s see that $P\_k$ has to intersect $Q$, leading to a contradiction. First of all, $P\_k$ has to intersect $Q$ in at least two points, one point $a\_k\in\overline{B}$ and one point $b\_k\in\overline{D}$. To prove this, let $t\_n$ be an ascending sequence, $t\_n\to k$, such that $a\_{t\_n}$ is convergent. Call $p\_n=i\_{t\_n}^{-1}(a\_n)$, we can suppose that $p\_n$ converges to some point $p\in P$ after taking a subsequence. Finally, we can let $a\_k$ be $i\_k(p)=\lim\_n i\_{t\_n}(p\_n)$, and similarly with $b\_k$. Now we can consider two cases:
If $P\_k$ intersects $\pi$ only at $a\_k$ and $b\_k$ we cannot have $a\_k\in A$ and $b\_k\in B$: that would contradict the definition of $k$. So either $a\_k\in\partial B\setminus Q$ and $b\_k\in\overline{G}$ or $b\_k\in\partial G\setminus Q$ and $a\_k\in\overline{B}$. Both cases are impossible, because $d(\partial B\setminus Q, G)$ and $d(\partial G\setminus Q, B)$ are both bigger than the diameter of $P$.
So $P\_k$ has to intersect $\pi$ in an edge. For the last time, we will consider two cases:
If $a\_k$ and $b\_k$ are both contained in the edge, then the edge intersects $Q$, which is a contradiction.
If not, the whole $P$ has to be contained in $\pi$. Consider an edge of the triangle containing the point $a\_k$. As the edge doesn´t intersect $Q$, one of its vertices must be in $B$. There is also other vertex in $G$ (one of the vertices of the edge containing $b\_k$), so the edge joining those two vertices must intersect $Q$, a contradiction.$\\[20pt]$
P.S: I had some comments regarding whether there are $P,Q$ as in the question with $7$ total vertices but they were wrong (I had not considered one case). An argument that they do not exist is given in Del's answer. | Here is another example with 8 vertices: a short fat Star Trek symbol and a square in orthogonal planes.
[](https://i.stack.imgur.com/TiQQK.jpg)
Since the distance between the base points of the red figure is greater than its height, one cannot rotate the square to take it out.
**Addendum:** As Saúl Rodríguez Martín mentions, this example may not work. If we assume, however, that the links are physical, that is they have some thickness, then I think that it should work. |
414,465 | Is every $ \mathbb{R}P^{2n} $ bundle over the circle trivial?
Are there exactly two $ \mathbb{R}P^{2n+1} $ bundles over the circle?
This is a cross-post of (part of) my MSE question
<https://math.stackexchange.com/questions/4349052/diffeomorphisms-of-spheres-and-real-projective-spaces>
which has been up for a couple weeks and got 8 upvotes and some nice comments but no answers.
My intuition for thinking both answer are yes is that there are exactly 2 sphere bundles over the circle. The trivial one and then the non-trivial (and non-orientable) one which can be realized as the mapping torus of an orientation reversing map of the sphere. So importing that intuition to projective spaces then the orientable $ \mathbb{R}P^{2n+1} $ should have a nontrivial (and non orientable) bundle over the circle while the non orientable $ \mathbb{R}P^{2n} $ should have only the trivial bundle. For $ n=1 $ this checks out since that projective space is orientable and thus we have exactly two bundles over the circle (the trivial one=the 2 torus and the nontrivial one=the Klein bottle). | 2022/01/23 | [
"https://mathoverflow.net/questions/414465",
"https://mathoverflow.net",
"https://mathoverflow.net/users/387190/"
] | As Sam Hopkins commented, 8 vertices are enough. Let $Q$ be the pentagon from the picture and let $\pi$ be the plane containing it. Now we can define the triangle $P$ as a triangle of less diameter than the black segment and intersecting $\pi$ at two points: one point $a\_0$ in the open blue region $B$ and one point $b\_0$ in the open green region $G$. $P$ and $Q$ are not linked, and it is intuitively clear that they are interlocked, but let´s prove it in detail.
[](https://i.stack.imgur.com/c0Tuwm.png)
Suppose there is a path of triangles $P\_t=i\_t(P)$ going to infinity, such that $P\_t$ is disjoint with $Q$ for all $t\in[0,\infty)$ and $i\_t:P\to\mathbb{R}^3$ is a continuous path of isometries (continuous in the supremum norm for functions $P\to\mathbb{R}^3$) with $i\_0=Id\_P$. Let´s try to derive a contradiction.
**Lemma 1**: Let $i$ be an isometry such that $i(P)$ intersects $\pi$ at exactly two points $a,b$. Then $\forall\varepsilon>0\;\exists\delta>0$ such that for any isometry $j$ with $d(i,j)<\delta$, $j(P)$ intersects $\pi$ at two points $a',b'$, with $d(a,a')<\varepsilon$ and $d(b,b')<\varepsilon$.
Proof: First of all, if $d(i,j)$ is small enough, $j(P)$ will intersect $\pi$ in two points, because the images by $j$ of at least two vertices of the triangle will be outside $\pi$.
Now consider the function $F(x,y)=$ intersection of the line passing through $x,y$ and $\pi$, defined in an open subset of $\mathbb{R}^6$. This function is continuous in its domain.
Suppose $a$ is not a vertex of the triangle. Then it is in the edge formed by two vertices $i(v\_1),i(v\_2)$, each in one half space of $\pi$. By continuity of $F$, if $d(i,j)$ is small enough we have a point $a'=F(j(v\_1),j(v\_2))$ in $j(P)$ at distance $<\varepsilon$ of $a$.
So the lemma works when $a,b$ are not vertices of the triangle. $a$ and $b$ cannot both be vertices of the triangle, so suppose $a$ is a vertex, $a=i(v\_1)$ with $v\_1$ a vertex of $P$, and $b$ is not. Then for $d(i,j)$ small enough both $F(j(v\_1),j(v\_2))$ and $F(j(v\_1),j(v\_3))$ will be at distance $<\varepsilon$ from $a$, so the one which is in $j(P)$ will be the point $a'$. $\square$
Now that we are done with the lemma 1, we can define
$$k=\sup\{t>0;P\_s\textit{ intersects $\pi$ at two points, one in $B$ and one in $G$, }\forall s\in[0,t)\}.$$
**Lemma 2**: $k>0$, and in $[0,k)$ there are paths $a\_t$, $b\_t$ such that $\{a\_t,b\_t\}=P\_t\cap A\;\forall t<k$.
Proof: By lemma 1, there is some $\varepsilon>0$ such that $\forall t\in [0,\varepsilon)$, $P\_t\cap A$ consists on two points, one in $G$ and one in $B$, so $k>0$. Let $a\_t$ be the point in $B$ and $b\_t$ be the point in $B$. By lemma 1 again, $a\_t$ and $b\_t$ are continuous in $[0,\varepsilon)$. Now consider the maximum $\varepsilon$ such that the $a\_t$ and $b\_t$ are defined in $[0,\varepsilon)$. Then $\varepsilon=k$, because if not, by the same argument using lemma 1, $a\_t$ and $b\_t$ will be defined in a neighborhood of $\varepsilon$.$\square$
Now let´s see that $P\_k$ has to intersect $Q$, leading to a contradiction. First of all, $P\_k$ has to intersect $Q$ in at least two points, one point $a\_k\in\overline{B}$ and one point $b\_k\in\overline{D}$. To prove this, let $t\_n$ be an ascending sequence, $t\_n\to k$, such that $a\_{t\_n}$ is convergent. Call $p\_n=i\_{t\_n}^{-1}(a\_n)$, we can suppose that $p\_n$ converges to some point $p\in P$ after taking a subsequence. Finally, we can let $a\_k$ be $i\_k(p)=\lim\_n i\_{t\_n}(p\_n)$, and similarly with $b\_k$. Now we can consider two cases:
If $P\_k$ intersects $\pi$ only at $a\_k$ and $b\_k$ we cannot have $a\_k\in A$ and $b\_k\in B$: that would contradict the definition of $k$. So either $a\_k\in\partial B\setminus Q$ and $b\_k\in\overline{G}$ or $b\_k\in\partial G\setminus Q$ and $a\_k\in\overline{B}$. Both cases are impossible, because $d(\partial B\setminus Q, G)$ and $d(\partial G\setminus Q, B)$ are both bigger than the diameter of $P$.
So $P\_k$ has to intersect $\pi$ in an edge. For the last time, we will consider two cases:
If $a\_k$ and $b\_k$ are both contained in the edge, then the edge intersects $Q$, which is a contradiction.
If not, the whole $P$ has to be contained in $\pi$. Consider an edge of the triangle containing the point $a\_k$. As the edge doesn´t intersect $Q$, one of its vertices must be in $B$. There is also other vertex in $G$ (one of the vertices of the edge containing $b\_k$), so the edge joining those two vertices must intersect $Q$, a contradiction.$\\[20pt]$
P.S: I had some comments regarding whether there are $P,Q$ as in the question with $7$ total vertices but they were wrong (I had not considered one case). An argument that they do not exist is given in Del's answer. | It is not possible with 7 (i.e., with a triangle $T$ and a quadrilateral $Q$). I write a rough proof.
First, any quadrilateral $Q$ lying in a plane $\pi$ can be partitioned in two triangles $Q\_1$ and $Q\_2$, whose common edge is a diagonal $d$ of $Q$. Now the intersection of the triangle $T$ with $\pi$ consists of two points (otherwise they are coplanar and the conclusion is trivial). Since the polygons are not linked, there are two cases: either both points lie outside $Q$, or they both lie inside $Q$.
Case 1: both lie outside. An inspection of the cases shows that we can just translate $T$ in direction parallel to one of the bisectors of the triangles $Q\_1$ or $Q\_2$ starting from one of the vertices not belonging to $d$.
Case 2: both lie inside. We will consider a modified problem: given a quadrilateral $Q$ and two initial points $x(0),y(0)$ inside it, find two continuous curves $x(t),y(t)$ such that the distance between the two is decreasing in time to 0, and they never lie in $Q$. The solution is, e.g., a linear homotopy that sends both points to the midpoint of $d$. Now we only have to realize $x(t)$ and $y(t)$ as the intersections of $T$ and the plane $\pi$. One can convince themselves that this is possible by pulling $T$ in direction orthogonal to $\pi$ while translating it. |
414,465 | Is every $ \mathbb{R}P^{2n} $ bundle over the circle trivial?
Are there exactly two $ \mathbb{R}P^{2n+1} $ bundles over the circle?
This is a cross-post of (part of) my MSE question
<https://math.stackexchange.com/questions/4349052/diffeomorphisms-of-spheres-and-real-projective-spaces>
which has been up for a couple weeks and got 8 upvotes and some nice comments but no answers.
My intuition for thinking both answer are yes is that there are exactly 2 sphere bundles over the circle. The trivial one and then the non-trivial (and non-orientable) one which can be realized as the mapping torus of an orientation reversing map of the sphere. So importing that intuition to projective spaces then the orientable $ \mathbb{R}P^{2n+1} $ should have a nontrivial (and non orientable) bundle over the circle while the non orientable $ \mathbb{R}P^{2n} $ should have only the trivial bundle. For $ n=1 $ this checks out since that projective space is orientable and thus we have exactly two bundles over the circle (the trivial one=the 2 torus and the nontrivial one=the Klein bottle). | 2022/01/23 | [
"https://mathoverflow.net/questions/414465",
"https://mathoverflow.net",
"https://mathoverflow.net/users/387190/"
] | It is not possible with 7 (i.e., with a triangle $T$ and a quadrilateral $Q$). I write a rough proof.
First, any quadrilateral $Q$ lying in a plane $\pi$ can be partitioned in two triangles $Q\_1$ and $Q\_2$, whose common edge is a diagonal $d$ of $Q$. Now the intersection of the triangle $T$ with $\pi$ consists of two points (otherwise they are coplanar and the conclusion is trivial). Since the polygons are not linked, there are two cases: either both points lie outside $Q$, or they both lie inside $Q$.
Case 1: both lie outside. An inspection of the cases shows that we can just translate $T$ in direction parallel to one of the bisectors of the triangles $Q\_1$ or $Q\_2$ starting from one of the vertices not belonging to $d$.
Case 2: both lie inside. We will consider a modified problem: given a quadrilateral $Q$ and two initial points $x(0),y(0)$ inside it, find two continuous curves $x(t),y(t)$ such that the distance between the two is decreasing in time to 0, and they never lie in $Q$. The solution is, e.g., a linear homotopy that sends both points to the midpoint of $d$. Now we only have to realize $x(t)$ and $y(t)$ as the intersections of $T$ and the plane $\pi$. One can convince themselves that this is possible by pulling $T$ in direction orthogonal to $\pi$ while translating it. | Here is another example with 8 vertices: a short fat Star Trek symbol and a square in orthogonal planes.
[](https://i.stack.imgur.com/TiQQK.jpg)
Since the distance between the base points of the red figure is greater than its height, one cannot rotate the square to take it out.
**Addendum:** As Saúl Rodríguez Martín mentions, this example may not work. If we assume, however, that the links are physical, that is they have some thickness, then I think that it should work. |
58,252 | I am currently doing a 3-month paid internship program - it started 3 weeks ago and will be conclusive in 3 months. This company does not promise to provide me with a position afterwards.
Now I've received a full-time job offer from another company.
* If it ethical to jump ship?
* What might some possible consequences be? | 2015/11/24 | [
"https://workplace.stackexchange.com/questions/58252",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/44326/"
] | Is it a ***nice*** thing to do? **No.**
Is it a ***good*** thing to do? **Depends who you're asking.**
Make no mistake, you are screwing your boss over by quitting. However, as you yourself have said, the company you're with right now is offering no guarantees whatsoever. That job offer, on the other hand, is **a certainty**.
Here's some advice to consider when you're in one of these tricky situations:
>
> **Always keep your own interests in mind.**
>
>
>
Your current employer sure as heck will do the same, and so will every other company you will ever work for - sometimes in your detriment. Don't feel that you should have loyalty to entities which will offer you none in return (aka 99% of all companies out there)
My personal opinion is this:
>
> If you have been offered a full time position and you need it, then **go for it**.
>
>
>
The only thing I can't be certain is whether you should give 2 week's notice or not. I think it would make little difference as you've barely been there long enough to get anything done. Sticking around for another 2 weeks is probably simply going to be awkward for everyone involved. | Think of it this way, you're leaving a temp/contract position for a full-time position. That situation is pretty much what many people in temp positions look for, unless they only want to do temp/contract work. If they brought you on knowing that you would eventually leave, they weren't prepared to make an offer to keep you on longer, and you don't particularly want to stay, then it doesn't seem like an issue.
If it's not an internship that you actually want to finish, and you're getting paid more at the full-time job, then it seems like you should simply quit the way most FT people do. Give the old place notice and tell the new place when you want to start. |
3,672,853 | The problem?
```
<UI:PanelBrowser Margin="12,27,12,32"></UI:PanelBrowser>
```
WPF is ridiculous in that not manually specifying properties (Such as Width and Height) in this case causes them to have the values `Doulbe.NaN`. The problem is that I need to know this number. I'm not going to manually set a width and height in the XAML because that stops it from resizing.
Given the above piece of XAML (this object is a simple subclass of the Border control), how can I get the values of the Width and Height properties at run-time?
Edit :
Wow, I feel ridiculous. I read about `ActualWidth` and `ActualHeight`, but they were consistently returning 0 and 0 for me. The reason is that I was testing for these properties in the constructor of the Framework Element, before they were actually initialized. Hope this helps someone who runs into the same issue and testing fallacies. :) | 2010/09/09 | [
"https://Stackoverflow.com/questions/3672853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369345/"
] | Try using the [FrameworkElement.ActualWidth](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualwidth.aspx) and [ActualHeight](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualheight.aspx) properties, instead. | You can use elements' `ActualWidth` and `ActualHeight` properties to get the values of the width and height when they were drawn. |
3,672,853 | The problem?
```
<UI:PanelBrowser Margin="12,27,12,32"></UI:PanelBrowser>
```
WPF is ridiculous in that not manually specifying properties (Such as Width and Height) in this case causes them to have the values `Doulbe.NaN`. The problem is that I need to know this number. I'm not going to manually set a width and height in the XAML because that stops it from resizing.
Given the above piece of XAML (this object is a simple subclass of the Border control), how can I get the values of the Width and Height properties at run-time?
Edit :
Wow, I feel ridiculous. I read about `ActualWidth` and `ActualHeight`, but they were consistently returning 0 and 0 for me. The reason is that I was testing for these properties in the constructor of the Framework Element, before they were actually initialized. Hope this helps someone who runs into the same issue and testing fallacies. :) | 2010/09/09 | [
"https://Stackoverflow.com/questions/3672853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369345/"
] | Try using the [FrameworkElement.ActualWidth](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualwidth.aspx) and [ActualHeight](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualheight.aspx) properties, instead. | The WPF FrameworkElement class provides two DependencyProperties for that purpose: `FrameworkElement.ActualWidth` and `FrameworkElement.ActualHeight` will get the rendered width and height at run-time. |
3,672,853 | The problem?
```
<UI:PanelBrowser Margin="12,27,12,32"></UI:PanelBrowser>
```
WPF is ridiculous in that not manually specifying properties (Such as Width and Height) in this case causes them to have the values `Doulbe.NaN`. The problem is that I need to know this number. I'm not going to manually set a width and height in the XAML because that stops it from resizing.
Given the above piece of XAML (this object is a simple subclass of the Border control), how can I get the values of the Width and Height properties at run-time?
Edit :
Wow, I feel ridiculous. I read about `ActualWidth` and `ActualHeight`, but they were consistently returning 0 and 0 for me. The reason is that I was testing for these properties in the constructor of the Framework Element, before they were actually initialized. Hope this helps someone who runs into the same issue and testing fallacies. :) | 2010/09/09 | [
"https://Stackoverflow.com/questions/3672853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369345/"
] | Try using the [FrameworkElement.ActualWidth](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualwidth.aspx) and [ActualHeight](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualheight.aspx) properties, instead. | Use **VisualTreeHelper.GetDescendantBounds(Visual Reference)**, and it return Rect.
Then Check the height of the Rect.
Ex)
```
Rect bounds = VisualTreeHelper.GetDescendantBounds(element);
double height = bounds.height;
```
**OR**
Use **UIElement.Measure(Size size)**, it will assign the Size into DesiredSize.
```
myElement.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
double height = myElement.DesiredSize.Height;
``` |
3,672,853 | The problem?
```
<UI:PanelBrowser Margin="12,27,12,32"></UI:PanelBrowser>
```
WPF is ridiculous in that not manually specifying properties (Such as Width and Height) in this case causes them to have the values `Doulbe.NaN`. The problem is that I need to know this number. I'm not going to manually set a width and height in the XAML because that stops it from resizing.
Given the above piece of XAML (this object is a simple subclass of the Border control), how can I get the values of the Width and Height properties at run-time?
Edit :
Wow, I feel ridiculous. I read about `ActualWidth` and `ActualHeight`, but they were consistently returning 0 and 0 for me. The reason is that I was testing for these properties in the constructor of the Framework Element, before they were actually initialized. Hope this helps someone who runs into the same issue and testing fallacies. :) | 2010/09/09 | [
"https://Stackoverflow.com/questions/3672853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369345/"
] | The WPF FrameworkElement class provides two DependencyProperties for that purpose: `FrameworkElement.ActualWidth` and `FrameworkElement.ActualHeight` will get the rendered width and height at run-time. | You can use elements' `ActualWidth` and `ActualHeight` properties to get the values of the width and height when they were drawn. |
3,672,853 | The problem?
```
<UI:PanelBrowser Margin="12,27,12,32"></UI:PanelBrowser>
```
WPF is ridiculous in that not manually specifying properties (Such as Width and Height) in this case causes them to have the values `Doulbe.NaN`. The problem is that I need to know this number. I'm not going to manually set a width and height in the XAML because that stops it from resizing.
Given the above piece of XAML (this object is a simple subclass of the Border control), how can I get the values of the Width and Height properties at run-time?
Edit :
Wow, I feel ridiculous. I read about `ActualWidth` and `ActualHeight`, but they were consistently returning 0 and 0 for me. The reason is that I was testing for these properties in the constructor of the Framework Element, before they were actually initialized. Hope this helps someone who runs into the same issue and testing fallacies. :) | 2010/09/09 | [
"https://Stackoverflow.com/questions/3672853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369345/"
] | You can use elements' `ActualWidth` and `ActualHeight` properties to get the values of the width and height when they were drawn. | Use **VisualTreeHelper.GetDescendantBounds(Visual Reference)**, and it return Rect.
Then Check the height of the Rect.
Ex)
```
Rect bounds = VisualTreeHelper.GetDescendantBounds(element);
double height = bounds.height;
```
**OR**
Use **UIElement.Measure(Size size)**, it will assign the Size into DesiredSize.
```
myElement.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
double height = myElement.DesiredSize.Height;
``` |
3,672,853 | The problem?
```
<UI:PanelBrowser Margin="12,27,12,32"></UI:PanelBrowser>
```
WPF is ridiculous in that not manually specifying properties (Such as Width and Height) in this case causes them to have the values `Doulbe.NaN`. The problem is that I need to know this number. I'm not going to manually set a width and height in the XAML because that stops it from resizing.
Given the above piece of XAML (this object is a simple subclass of the Border control), how can I get the values of the Width and Height properties at run-time?
Edit :
Wow, I feel ridiculous. I read about `ActualWidth` and `ActualHeight`, but they were consistently returning 0 and 0 for me. The reason is that I was testing for these properties in the constructor of the Framework Element, before they were actually initialized. Hope this helps someone who runs into the same issue and testing fallacies. :) | 2010/09/09 | [
"https://Stackoverflow.com/questions/3672853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369345/"
] | The WPF FrameworkElement class provides two DependencyProperties for that purpose: `FrameworkElement.ActualWidth` and `FrameworkElement.ActualHeight` will get the rendered width and height at run-time. | Use **VisualTreeHelper.GetDescendantBounds(Visual Reference)**, and it return Rect.
Then Check the height of the Rect.
Ex)
```
Rect bounds = VisualTreeHelper.GetDescendantBounds(element);
double height = bounds.height;
```
**OR**
Use **UIElement.Measure(Size size)**, it will assign the Size into DesiredSize.
```
myElement.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
double height = myElement.DesiredSize.Height;
``` |
54,442,972 | I write my API documentation with Spring REST Docs.
Code example:
```
@Override
public void getById(String urlTemplate, PathParametersSnippet pathParametersSnippet, Object... urlVariables) throws Exception {
resultActions = mockMvc.perform(get(urlTemplate, urlVariables)
.principal(principal)
.contentType(APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
// do..
}
```
But the problem is that the result of the test is answered in one line. And understanding the structure of the returned data is very difficult.
Response example:
```
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"creator":null,"modifier":null,"modificationTime":null,"creationTime":null,"id":100,"deleted":false,"name":"Name","description":null,"report":[{"creator":"System","modifier":"System","modificationTime":"2019-01-30T14:21:50","creationTime":"2019-01-30T14:21:50","id":1,"name":"Form name","reportType":{"creator":"System","modifier":"System","modificationTime":"2019-01-30T14:21:50","creationTime":"2019-01-30T14:21:50","id":1,"deleted":false,"name":"Raport"},"unmodifiable":true}]}
Forwarded URL = null
Redirected URL = null
Cookies = []
```
Further, I generate documentation from the answer received and in the documentation also unformatted JSON
What am I doing wrong? How to enable formatting for json? | 2019/01/30 | [
"https://Stackoverflow.com/questions/54442972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10499368/"
] | If you're not in a position to configure your application to produce pretty-printed responses, you can have REST Docs do it for you prior to them being documented. This is described in the [Customizing Requests and Responses](https://docs.spring.io/spring-restdocs/docs/2.0.x/reference/html5/#customizing-requests-and-responses) section of the documentation:
>
> Preprocessing is configured by calling document with an `OperationRequestPreprocessor`, and/or an `OperationResponsePreprocessor`. Instances can be obtained using the static `preprocessRequest` and `preprocessResponse` methods on `Preprocessors`. For example:
>
>
>
> ```
> this.mockMvc.perform(get("/")).andExpect(status().isOk())
> .andDo(document("index", preprocessRequest(removeHeaders("Foo")),
> preprocessResponse(prettyPrint())));
>
> ```
>
>
In the case above the request is being preprocessed to remove a `Foo` header and the response is being preprocessed so that it appears pretty-printed. | You can try get `ResultActions` object from mockMvc and than get `MockHttpServletResponse` object. After that you can get all the values of the fields that came in response. In this case, you will not need to parse the string.
```
resultActions = mockMvc.perform(get(urlTemplate, urlVariables)
.principal(principal)
.contentType(APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
MockHttpServletResponse content = resultActions.andReturn().getResponse();
```
Also you can transform `MockHttpServletResponse` object data to json. IUf you use Jacson, than write your custom serializer for this object, add it to `MockHttpServletResponse` and register in `ObjectMapper`.
```
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MockHttpServletResponse.class, CustomSerializer.class);
mapper.registerModule(module);
String jsonResult = mapper.writeValueAsString(content);
```
`CustomSerializer` should extends `StdSerializer<MockHttpServletResponse>` and override `serialize` method. |
239,478 | I have the following tables:
[](https://i.stack.imgur.com/M6teW.png)
Each `ProductLine` will encompass many `Part`s. For this reason, it initially seemed to me that the `Part` table is a child of the `ProductLine` table. However, a part is not simply an extension of a product line, and when I asked myself if it is possible to a part to exist without a product line, the answer seems to be yes.
So I'm wondering if the above design appears to be correct or if there is a better design. In the `Part` table, `PartBase` can be thought of as the unique identifier for each part (the part number if you will.)
As a somewhat unrelated question, I have these tables set up as a one to many relationship. Since each `Part` must belong to a `ProductLine` but cannot belong to more than one, is it more correct to have this as a one-and-only-one to many relationship? Is the only difference that a `Part` must contain a not null `ProductLineNumber` in the actual database? Is that different from requiring that `ProductLineNumber` be not null?
To follow up to @HandyD's comment, as a business rule, every part must belong to exactly one product line. However, when I was thinking about a part as a physical object, it shouldn't need a product line to exist (a product line is just a label after all.) I'm comparing here to how a sale needs a customer to make sense, so that a `Sale` table would more clearly be the child of a `Customer` table. Is this distinction between `Part`-`ProductLine` and `Sale`-`Customer` a false one? | 2019/05/30 | [
"https://dba.stackexchange.com/questions/239478",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/180524/"
] | If the business requirement is
>
> a business rule, every part must belong to exactly one product line.
>
>
>
So if the rule is, **each part belongs to one product line** the other side of that relationship is **each product line contains zero-to-many parts** which should convince you this is a clear instance of a parent/child relationship.
How a something exists in the real world versus how it exists within a business context/database are not always strongly tied. If I have a part on my desk I do not care about it's product line. But if I'm a business and I am selling the part I will probably need to categorize that part for search/reporting/sales/commission purposes.
The other columns you will probably need FKs on (PartType, Grade, Family, PopularityCode, UnitClass) will have the same physical implementation (parent table, foreign key reference) even if the context might not be the same (Each Part is described by One Part Type/PartType describes zero-to-many Parts, etc).
Won't get into the column types or other aspects of the design because that's not pertinent to the question but I'll be happy to provide guidance elsewhere. | Like in `Part` Table,
```
PartID int PK
PartBase varchar(20) AK
PopularityCode char(20)
```
Similarly In `ProductLine` Table ,`PK` column should be of `INT` datatype.
Even if `ProductLine` table is small,it may be FK in Huge Table .
So if `ProductLineNumber varchar(20)` is Index then it may affect performance.
So it should be ,
```
ProductLine Table
ProductLineID int PK
ProductLineNumber varchar(20) AK
```
ProductLineID should be reference in other columns.
Now come the main question.
Foreign Key can be null-able also.
So if as per your Biz. requirement, `Part cannot exists without Product Line` then,
```
create table Part (
Partid int ,
PartBase varchar(20) not null,
ProductLineID int not null,
primary key(PartID,ProductLineID)
);
```
So `PartID,ProductLineID` will be composite primary key.
if `Part can exists of its own Product Line` then `ProductLineID` will be `Nullable FK`.
then Main question is ,
```
How many nullable ProductLineID rows will be there in Part table ?
create table Part (
Partid int primary key ,
PartBase varchar(20) not null,
ProductLineID int null,
PopularityCode char(20)
);
```
I assume Nullable ProductLineID rows will be very negligible 1% or 2%.
In that case `Create Unique Filtered index`,
```
CREATE UNIQUE INDEX
FUX_Part_ProductLine
ON dbo.Part
(Partid,ProductLineID )
WHERE
ProductLineID IS NOT NULL ;
```
When did you mention anything about `PopularityCode` ?
Even if `PopularityCode` is not mention in question,even if there is no issue of `Partial Dependency`,still we need Mapping Table.
So New Design of Part table,
```
create table Part (
Partid int primary key ,
PartBase varchar(20) not null,
PopularityCode char(20)
);
```
Create Mapping table
```
create table ProductLine_Part_Mapping (
Partid int not null ,
ProductLineID int not null,
primary key(PartID,ProductLineID)
);
```
It is better to create Mapping table in One-to-Many or Many-to-Many relation.
It help specially when records are in millions.
So `Partid` is Independent or not,this design is OK.
If you mention thing like ,
One Productline may contain how many PartID ?
How many rows will be there in each table ?
These question in help in making Index. |
36,318,280 | I'm trying to create a runnable JAR from <https://bitbucket.org/madsen953/ethervisu> in Eclipse. When I try to run it I get:
```
Exception in thread "Monitor" java.lang.UnsatisfiedLinkError: no jnetpcap in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1864)
at java.lang.Runtime.loadLibrary0(Runtime.java:870)
at java.lang.System.loadLibrary(System.java:1122)
at org.jnetpcap.Pcap.<clinit>(Unknown Source)
at ethervisu.monitors.JNetPcapMonitor.run(JNetPcapMonitor.java:28)
at java.lang.Thread.run(Thread.java:745)
java.lang.NullPointerException
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at processing.core.PFont.<init>(Unknown Source)
at processing.core.PApplet.loadFont(Unknown Source)
at jgv.graphics.JGVGraphics$GraphVisuApplet.setup(JGVGraphics.java:80)
at processing.core.PApplet.handleDraw(Unknown Source)
at processing.core.PApplet.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Exception in thread "Animation Thread" java.lang.RuntimeException: Could not load font /data/ArialMT-48.vlw. Make sure that the font has been copied to the data folder of your sketch.
at processing.core.PApplet.die(Unknown Source)
at processing.core.PApplet.die(Unknown Source)
at processing.core.PApplet.loadFont(Unknown Source)
at jgv.graphics.JGVGraphics$GraphVisuApplet.setup(JGVGraphics.java:80)
at processing.core.PApplet.handleDraw(Unknown Source)
at processing.core.PApplet.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
```
I think this is because I'm unable to preserve the directory structure when creating the JAR. The font files are at the root instead of the `data` directory. How can I fix this? | 2016/03/30 | [
"https://Stackoverflow.com/questions/36318280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/259288/"
] | You need to use a WHERE clause in your update statement.
```
UPDATE wp_posts
SET post_content = replace(post_content, 'free', 'free3' )
WHERE post_content LIKE '%blue%'
``` | Try this:
```
UPDATE wp_posts SET post_content = REPLACE(post_content, 'free', 'free3')
WHERE LOCATE('blue', post_content) > 0
``` |
16,469,150 | We are supposed to use the code below to print out the parameters listed in it, currently however we are unable to do so and are using a round about method. This is supposed to print out things instead of what we print out in the Game class in the playturn function
```
def __str__(self):
x = self.name + ":\t"
x += "Card(s):"
for y in range(len(self.hand)):
x +=self.hand[y].face + self.hand[y].suit + " "
if (self.name != "dealer"):
x += "\t Money: $" + str(self.money)
return(x)
```
Here is our actual code, if you also see any other issues your input would be greatly appreciated
```
from random import*
#do we need to address anywhere that all face cards are worth 10?
class Card(object):
def __init__(self,suit,number):
self.number=number
self.suit=suit
def __str__(self):
return '%s'%(self.number)
class DeckofCards(object):
def __init__(self,deck):
self.deck=deck
self.shuffledeck=self.shuffle()
def shuffle(self):
b=[]
count=0
while count<len(self.deck):
a=randrange(0,len(self.deck))
if a not in b:
b.append(self.deck[a])
count+=1
return(b)
def deal(self):
if len(self.shuffledeck)>0:
return(self.shuffledeck.pop(0))
else:
shuffle(self)
return(self.shuffledeck.pop(0))
class Player(object):
def __init__(self,name,hand,inout,money,score,bid):
self.name=name
self.hand=hand
self.inout=inout
self.money=money
self.score=score
self.bid=bid
def __str__(self):
x = self.name + ":\t"
x += "Card(s):"
for y in range(len(self.hand)):
x +=self.hand[y].face + self.hand[y].suit + " "
if (self.name != "dealer"):
x += "\t Money: $" + str(self.money)
return(x)
class Game(object):
def __init__(self,deck, player):
self.player=Player(player,[],True,100,0,0)
self.dealer=Player("Dealer",[],True,100,0,0)
self.deck=DeckofCards(deck)
self.blackjack= False
def blackjacksearch(self):
if Game.gettot(self.player.hand)==21:#changed
return True
else:
return False
def firstround(self):
#self.player.inout=True#do we need this since this is above
#self.player.hand=[]#do wee need this....
#self.dealer.hand=[]#do we need this ....
self.player.hand.append(DeckofCards.deal(self.deck))
for card in self.player.hand:
a=card
print(self.player.name + ' ,you were dealt a '+str(a))
self.dealer.hand.append(DeckofCards.deal(self.deck))
for card in self.dealer.hand:
a=card
print('The Dealer has '+str(a))
playerbid=int(input(self.player.name + ' how much would you like to bet? '))
self.player.money-=playerbid
self.player.bid=playerbid
def playturn(self): #should this be changed to inout instead of hit.....we never use inout
#for player in self.player:
# a=player
#print(str(a))
hit=input('Would you like to hit? ') #should input be in loop?
while self.player.inout==True: #and self.blackjack!=True:#changed
print(self.player.name + ' , your hand has:' + str(self.player.hand)) #do we want to make this gettot? so it prints out the players total instead of a list....if we want it in a list we should print it with out brakets
self.player.hand.append(DeckofCards.deal(self.deck))
for card in self.player.hand:
a=card
print('The card that you just drew is: ' + str(a))
#print(Game.gettot(self.player.hand))
hit=input('Would you like to hit? ')
if hit=='yes':
(self.player.hand.append(DeckofCards.deal(self.deck)))#changed
self.player.inout==True#
else:
(self.player.hand) #changed
self.player.inout==False #changed
if self.player.blackjack==True:
print(self.player.name + " has blackjack ")
if hit=='no':
print (self.player.hand.gettot())
def playdealer(self):
while Game.gettot(self.dealer.hand)<17:#changed
self.dealer.hand.append(DeckofCards.deal(self.deck))
dealerhand=Game.gettot(self.dealer.hand) #changed
print(dealerhand)
if Game.gettot(self.dealer.hand)==21:#changed
self.dealer.blackhjack=True
dealerhand1=Game.gettot(self.dealer.hand)#changed
print(dealerhand1)
def gettot(self,hand):
total=0
for x in self.hand:
if x==Card('H','A'):
b=total+x
if b>21:
total+=1
else:
total+=11
if x==Card('D','A'):
b=total+x
if b>21:
total+=1
else:
total+=11
if x==Card('S','A'):
b=total+x
if b>21:
total+=1
else:
total+=11
if x==Card('C','A'):
b=total+x #changed
if b>21:
total+=1
else:
total+=11
else:
total+=x
return(total)
def playgame(self):
play = "yes"
while (play.lower() == "yes"):
self.firstround()
self.playturn()
if self.player.blackjack == True:
print(self.player.name + " got BLACKJACK! ")
self.player.money += self.player.bid * 1.5
print (self.player.name + " now has " + str(self.player.money))
print("\n")
self.player.inout = False
if self.player.score > 21:
print(self.player.name + " lost with a tot of " + str(self.player.score))
self.player.money -= self.player.bid
print (self.player.name + " now has " + str(self.player.money))
print ("\n\n")
self.player.inout = False
self.playdealer()
if self.dealer.blackjack == True:
print("Dealer got blackjack, dealer wins\n")
self.player.money -= self.player.bid
print("Round\n")
print("\t",self.dealer)
print("\t",self.player)
print("\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
elif self.player.inout == True:
print("Round\n")
print("\t",self.dealer)
print("\t",self.player)
print("\n\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
if self.dealer.score > 21:
print("\t Dealer lost with a total of " + str(self.dealer.score))
self.player.money += self.player.bid
print(self.player.name + " now has " + str(self.player.money))
elif self.player.score > self.dealer.score:
print("\t" +self.player.name + " won with a total of " + str(self.player.score))
self.player.money += self.player.bid
print("\t"+self.player.name + " now has " + str(self.player.money))
else:
print("\t Dealer won with a total of " + str(self.dealer.score))
self.player.money -= self.player.bid
print("\t"+self.player.name + " now has " + str(self.player.money))
else:
print("Round")
print("\t",self.dealer)
print("\t",self.player)
if self.player.blackjack == False:
print("\t "+ self.player.name + " lost" )
else:
print("\t "+self.player.name + " Won!")
if self.player.money <= 0:
print(self.player.name + " out of money - out of game ")
play = "no"
else:
play = input("\nAnother round? ")
print("\n\n")
print("\nGame over. ")
print(self.player.name + " ended with " + str(self.player.money) + " dollars.\n")
print("Thanks for playing. Come back soon!")
ls= [Card('H','A'),Card('H','2'),Card('H','3'),Card('H','4'),Card('H','5'),Card('H','6'),Card('H','7'),Card('H','8'),Card('H','9'),Card('H','10'),
Card('H','J'),Card('H','Q'),Card('H','K'),
Card('S','A'),Card('S','2'),Card('S','3'),Card('S','4'),Card('S','5'),
Card('S','6'),Card('S','7'),Card('S','8'),Card('S','9'),Card('S','10'),
Card('S','J'),Card('S','Q'),Card('S','K'),
Card('C','A'),Card('C','2'),Card('C','3'),Card('C','4'),Card('C','5'),
Card('C','6'),Card('C','7'),Card('C','8'),Card('C','9'),Card('C','10'),
Card('C','J'),Card('C','Q'),Card('C','K'),
Card('D','A'),Card('D','2'),Card('D','3'),Card('D','4'),Card('D','5'),
Card('D','6'),Card('D','7'),Card('D','8'),Card('D','9'),Card('D','10'),
Card('D','J'),Card('D','Q'),Card('D','K')]
def main():
x = input("Player's name? ")
blackjack = Game(ls,x)
blackjack.playgame()
main()
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16469150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321264/"
] | The problem is that, in at least some places, you're trying to print a `list`.
While printing anything, including a `list`, calls `str` on it, the `list.__str__` method calls `repr` on its elements. (If you don't know the difference between `str` and `rep`, see [Difference between `__str__` and `__repr__` in Python](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python).)
If you want to print the `str` of every element in a list, you have to do it explicitly, with a `map` or list comprehension.
For example, instead of this:
```
print(self.player.name + ' , your hand has:' + str(self.player.hand))
```
… do this:
```
print(self.player.name + ' , your hand has:' + [str(card) for card in self.player.hand])
```
But this is still probably not what you want. You will get `['8', '9']` instead of `[<__main__.Card object at 0x1007aaad0>, <__main__.Card object at 0x1007aaaf0>]`, but you probably wanted something more like `8H 9C'. To do that, you'd want something like:
```
print(self.player.name + ' , your hand has:' +
' '.join(str(card) for card in self.player.hand))
```
You already have similar (although more verbose) code inside `Player.__str__`:
```
for y in range(len(self.hand)):
x +=self.hand[y].face + self.hand[y].suit + " "
```
This code could be improved in a few ways.
First, it's going to raise an `AttributeError` because you're using `face` instead of `number`. But really, you shouldn't need to do this at all—the whole reason you created a `Card.__str__` method is so you can just use `str(Card)`, right?
Second, you almost never want to loop over `range(len(foo))`, especially if you do `foo[y]` inside the loop. Just loop over `foo` directly.
Putting that together:
```
for card in self.hand:
x += str(card) + " "
```
At any rate, you need to do the same thing in both places.
The version that uses the `join` method and a generator expression is a little simpler than the explicit loop, but does require a bit more Python knowledge to understand. Here's how you'd use it here:
```
x += " ".join(str(card) for card in self.hand) + " "
```
---
Your next problem is that `Card.__str__` doesn't include the suit. So, instead of `8H 9C`, you're going to get `8 9`. That should be an easy fix to do on your own.
---
Meanwhile, if you find yourself writing the same code more than once, you probably want to abstract it out. You *could* just write a function that takes a hand `list` and turns it into a string:
```
def str_hand(hand):
return " ".join(str(card) for card in self.hand)
```
But it might be even better to create a `Hand` class that wraps up a list of cards, and pass that around, instead of using a `list` directly. | You are not running the functionality you want because you are referencing `player.hand`. Try changing
```
str(self.player.hand)
```
to
```
str(self.player)
``` |
65,753,830 | I'm trying to train Mask-R CNN model from cocoapi(<https://github.com/cocodataset/cocoapi>), and this error code keep come out.
```
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-8-83356bb9cf95> in <module>
19 sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version
20
---> 21 from pycocotools.coco import coco
22
23 get_ipython().run_line_magic('matplotlib', 'inline ')
~/Desktop/coco/PythonAPI/pycocotools/coco.py in <module>
53 import copy
54 import itertools
---> 55 from . import mask as maskUtils
56 import os
57 from collections import defaultdict
~/Desktop/coco/PythonAPI/pycocotools/mask.py in <module>
1 __author__ = 'tsungyi'
2
----> 3 import pycocotools._mask as _mask
4
5 # Interface for manipulating masks stored in RLE format.
ModuleNotFoundError: No module named 'pycocotools._mask'
```
I tried all the methods on the github 'issues' tab, but it is not working to me at all. Is there are another solution for this? I'm using Python 3.6, Linux. | 2021/01/16 | [
"https://Stackoverflow.com/questions/65753830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14258016/"
] | The answer is summarise from [these](https://github.com/cocodataset/cocoapi/issues/172) [three](https://github.com/cocodataset/cocoapi/issues/168) [GitHub issues](https://github.com/cocodataset/cocoapi/issues/141#issuecomment-386606299)
1.whether you have installed cython in the correct version. Namely, you should install cython for python2/3 if you use python2/3
```
pip install cython
```
2.whether you have downloaded the whole .zip file from this github project. Namely, you should download all the things here even though you only need PythonAPI
```
git clone https://github.com/cocodataset/cocoapi.git
```
or
unzip the [zip file](https://github.com/cocodataset/cocoapi/archive/refs/heads/master.zip)
3.whether you open Terminal and run "make" under the correct folder. The correct folder is the one that "Makefile" is located in
```
cd path/to/coco/PythonAPI/Makefile
make
```
Almost, the question can be solved.
If not, 4 and 5 may help.
4.whether you have already installed gcc in the correct version
5.whether you have already installed python-dev in the correct version. Namely you should install python3-dev (you may try "sudo apt-get install python3-dev"), if you use python3. | Try cloning official repo and run below commands
```
python setup.py install
make
``` |
73,039,121 | With great help from @pratik-wadekar I have the following working text animation.
Now my problem is that when I test it on different screen sizes/mobile the animated word `plants` breaks into pieces. For example PLA and in the next line NTS. How can I avoid this? So it always keeps as one full word.
First I tried to add `\xC2\xA0 – non-breaking space or ` before and after the word but this doesnt help. The CSS `word-wrap` property allows long words to be able to break but unfortunately for the reverse case to make a word unbreakable there is no option.
It seems that the CSS `word-break: "keep-all` property is what I need but when I apply it, it still breaks into pieces on smaller screens.
The [Codepen](https://codesandbox.io/s/lucid-mclaren-qytt3q?file=/src/App.tsx:0-1271)
And `App.tsx`:
```
import React from "react";
import { styled } from "@mui/material/styles";
import { Typography } from "@mui/material";
const AnimatedTypography = styled(Typography)`
& {
position: relative;
-webkit-box-reflect: below -20px linear-gradient(transparent, rgba(0, 0, 0, 0.2));
font-size: 60px;
}
& span {
color: #fbbf2c;
font-family: "Alfa Slab One", sans-serif;
position: relative;
display: inline-block;
text-transform: uppercase;
animation: waviy 1s infinite;
animation-delay: calc(0.1s * var(--i));
}
@keyframes waviy {
0%,
40%,
100% {
transform: translateY(0);
}
20% {
transform: translateY(-20px);
}
}
`;
interface Styles extends React.CSSProperties {
"--i": number;
}
function App() {
const string = "plants";
return (
<Typography variant={"h3"} fontWeight={"bold"}>
All Your
<AnimatedTypography>
{string.split("").map((char, idx) => {
const styles: Styles = {
"--i": idx + 1
};
return (
<span key={`${char}-${idx}`} style={styles}>
{char}
</span>
);
})}
</AnimatedTypography>
in One Place
</Typography>
);
}
export default App;
``` | 2022/07/19 | [
"https://Stackoverflow.com/questions/73039121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Every single character is a separate `<span>`, so it's not parsed as a single word. One solution would be to simply make the parent a `flex` container:
```
<AnimatedTypography style={{display:"flex"}}>
```
<https://codesandbox.io/s/blissful-sea-4o7498> | What you need is `white-space: nowrap`.
Please check
<https://codesandbox.io/s/infallible-matan-rcnclw> |
73,039,121 | With great help from @pratik-wadekar I have the following working text animation.
Now my problem is that when I test it on different screen sizes/mobile the animated word `plants` breaks into pieces. For example PLA and in the next line NTS. How can I avoid this? So it always keeps as one full word.
First I tried to add `\xC2\xA0 – non-breaking space or ` before and after the word but this doesnt help. The CSS `word-wrap` property allows long words to be able to break but unfortunately for the reverse case to make a word unbreakable there is no option.
It seems that the CSS `word-break: "keep-all` property is what I need but when I apply it, it still breaks into pieces on smaller screens.
The [Codepen](https://codesandbox.io/s/lucid-mclaren-qytt3q?file=/src/App.tsx:0-1271)
And `App.tsx`:
```
import React from "react";
import { styled } from "@mui/material/styles";
import { Typography } from "@mui/material";
const AnimatedTypography = styled(Typography)`
& {
position: relative;
-webkit-box-reflect: below -20px linear-gradient(transparent, rgba(0, 0, 0, 0.2));
font-size: 60px;
}
& span {
color: #fbbf2c;
font-family: "Alfa Slab One", sans-serif;
position: relative;
display: inline-block;
text-transform: uppercase;
animation: waviy 1s infinite;
animation-delay: calc(0.1s * var(--i));
}
@keyframes waviy {
0%,
40%,
100% {
transform: translateY(0);
}
20% {
transform: translateY(-20px);
}
}
`;
interface Styles extends React.CSSProperties {
"--i": number;
}
function App() {
const string = "plants";
return (
<Typography variant={"h3"} fontWeight={"bold"}>
All Your
<AnimatedTypography>
{string.split("").map((char, idx) => {
const styles: Styles = {
"--i": idx + 1
};
return (
<span key={`${char}-${idx}`} style={styles}>
{char}
</span>
);
})}
</AnimatedTypography>
in One Place
</Typography>
);
}
export default App;
``` | 2022/07/19 | [
"https://Stackoverflow.com/questions/73039121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Ok I got it. I had to make the animation as own component and add the `<AnimatedTypography>` the `component={"span"}` type and `white-space: nowrap`.
Additionally to my `const AnimatedTypography = styled(Typography)` I had to cast the resulting component with `as typeof Typograph`y so Typescript does not throws errors.
See here: [Complications with the component prop](https://mui.com/material-ui/guides/typescript/#usage-of-component-prop)
Then importing the component and addind into the Typography component between my text. Now the layout of my text is preserved and the animation does not split into single characters. | What you need is `white-space: nowrap`.
Please check
<https://codesandbox.io/s/infallible-matan-rcnclw> |
73,039,121 | With great help from @pratik-wadekar I have the following working text animation.
Now my problem is that when I test it on different screen sizes/mobile the animated word `plants` breaks into pieces. For example PLA and in the next line NTS. How can I avoid this? So it always keeps as one full word.
First I tried to add `\xC2\xA0 – non-breaking space or ` before and after the word but this doesnt help. The CSS `word-wrap` property allows long words to be able to break but unfortunately for the reverse case to make a word unbreakable there is no option.
It seems that the CSS `word-break: "keep-all` property is what I need but when I apply it, it still breaks into pieces on smaller screens.
The [Codepen](https://codesandbox.io/s/lucid-mclaren-qytt3q?file=/src/App.tsx:0-1271)
And `App.tsx`:
```
import React from "react";
import { styled } from "@mui/material/styles";
import { Typography } from "@mui/material";
const AnimatedTypography = styled(Typography)`
& {
position: relative;
-webkit-box-reflect: below -20px linear-gradient(transparent, rgba(0, 0, 0, 0.2));
font-size: 60px;
}
& span {
color: #fbbf2c;
font-family: "Alfa Slab One", sans-serif;
position: relative;
display: inline-block;
text-transform: uppercase;
animation: waviy 1s infinite;
animation-delay: calc(0.1s * var(--i));
}
@keyframes waviy {
0%,
40%,
100% {
transform: translateY(0);
}
20% {
transform: translateY(-20px);
}
}
`;
interface Styles extends React.CSSProperties {
"--i": number;
}
function App() {
const string = "plants";
return (
<Typography variant={"h3"} fontWeight={"bold"}>
All Your
<AnimatedTypography>
{string.split("").map((char, idx) => {
const styles: Styles = {
"--i": idx + 1
};
return (
<span key={`${char}-${idx}`} style={styles}>
{char}
</span>
);
})}
</AnimatedTypography>
in One Place
</Typography>
);
}
export default App;
``` | 2022/07/19 | [
"https://Stackoverflow.com/questions/73039121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Ok I got it. I had to make the animation as own component and add the `<AnimatedTypography>` the `component={"span"}` type and `white-space: nowrap`.
Additionally to my `const AnimatedTypography = styled(Typography)` I had to cast the resulting component with `as typeof Typograph`y so Typescript does not throws errors.
See here: [Complications with the component prop](https://mui.com/material-ui/guides/typescript/#usage-of-component-prop)
Then importing the component and addind into the Typography component between my text. Now the layout of my text is preserved and the animation does not split into single characters. | Every single character is a separate `<span>`, so it's not parsed as a single word. One solution would be to simply make the parent a `flex` container:
```
<AnimatedTypography style={{display:"flex"}}>
```
<https://codesandbox.io/s/blissful-sea-4o7498> |
23,423,572 | As title says, why does Rails prefer to use the @params variable inside of a Controller action when you are responding to the action instead of passing the individual parameters through the function arguments when we call the function?
Other frameworks use this (i.e, ASP MVC) and I was just wondering if there was a reason for that design decision, because it doesn't seem very intuitive.
Ie. Why does Rails do
```
def index
name = params[:name]
end
```
Instead of
```
def index(name)
end
``` | 2014/05/02 | [
"https://Stackoverflow.com/questions/23423572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073868/"
] | The Maven command `mvn eclipse:eclipse` generate the eclipse project files from POM.
The "-D" prefix in the argument means that it's a system property.
System property are defined like `http://docs.oracle.com/javase/jndi/tutorial/beyond/env/source.html#SYS`
`mvn eclipse:eclipse -Dwtpversion=2.0` command convert the web based java project to maven based java project to support Eclipse IDE.
You can simple use given below command to clean and build your project:
`mvn clean` and `mvn install`
OR **`mvn clean install`**
Suggestion: Check maven is installed properly using command `mvn --version`. | ```
mvn eclipse:eclipse -Dwtpversion=2.0 -e clean install
```
run this instead. This builds your project by resolving dependencies |
23,423,572 | As title says, why does Rails prefer to use the @params variable inside of a Controller action when you are responding to the action instead of passing the individual parameters through the function arguments when we call the function?
Other frameworks use this (i.e, ASP MVC) and I was just wondering if there was a reason for that design decision, because it doesn't seem very intuitive.
Ie. Why does Rails do
```
def index
name = params[:name]
end
```
Instead of
```
def index(name)
end
``` | 2014/05/02 | [
"https://Stackoverflow.com/questions/23423572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073868/"
] | Please try installing m2eclipse plugin (if you haven't done so yet) and nextly convert project to use maven behaviour through right clicking on project and choosing "convert to maven" option. | ```
mvn eclipse:eclipse -Dwtpversion=2.0 -e clean install
```
run this instead. This builds your project by resolving dependencies |
23,423,572 | As title says, why does Rails prefer to use the @params variable inside of a Controller action when you are responding to the action instead of passing the individual parameters through the function arguments when we call the function?
Other frameworks use this (i.e, ASP MVC) and I was just wondering if there was a reason for that design decision, because it doesn't seem very intuitive.
Ie. Why does Rails do
```
def index
name = params[:name]
end
```
Instead of
```
def index(name)
end
``` | 2014/05/02 | [
"https://Stackoverflow.com/questions/23423572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073868/"
] | The Maven command `mvn eclipse:eclipse` generate the eclipse project files from POM.
The "-D" prefix in the argument means that it's a system property.
System property are defined like `http://docs.oracle.com/javase/jndi/tutorial/beyond/env/source.html#SYS`
`mvn eclipse:eclipse -Dwtpversion=2.0` command convert the web based java project to maven based java project to support Eclipse IDE.
You can simple use given below command to clean and build your project:
`mvn clean` and `mvn install`
OR **`mvn clean install`**
Suggestion: Check maven is installed properly using command `mvn --version`. | Please try installing m2eclipse plugin (if you haven't done so yet) and nextly convert project to use maven behaviour through right clicking on project and choosing "convert to maven" option. |
40,925,951 | In our WPF software, we used a `ControlTemplate` which defines a `ToggleButton` that causes the window to shrink/extend. The definition of `ToggleButton` is given below:
```xml
<ToggleButton ToolTip="Standard/Extended" Grid.Column="0"
x:Name="PART_MaximizeToggle" VerticalAlignment="Top"
HorizontalAlignment="Right" Margin="0,5,5,0"
Width="14" Height="14" Cursor="Hand">
```
We're creating a custom `DockPanel` which contains this button at the upper right corner. Our application can contain up to three of this `DockPanel`s at the same time:
[](https://i.stack.imgur.com/FFsTH.png)
The small rectangle on the right of each `DockPanel` is shown in the image above.
Notice from the definition that all three of the rectangles have same name: `"PART_MaximizeToggle"`. This causes trouble when writing CodedUI programs to automate testing. CodedUI captures all of their FriendlyNames as `"PART_MaximizeToggle"` with Name field empty. The locations and sequence of the `DockPanel`s can change based or what the user want.
How can we make CodedUI capture exact the button where a click is expected? I was thinking of making the `Name` of each toggle button dynamic but fixed for a specific `DockPanel`.
How can I do that? Is there a better approach? | 2016/12/02 | [
"https://Stackoverflow.com/questions/40925951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68304/"
] | You could assign ([and register](https://msdn.microsoft.com/en-us/library/system.windows.frameworkcontentelement.registername.aspx)) the names automatically via an [AttachedProperty](https://msdn.microsoft.com/en-us/library/ms749011(v=vs.110).aspx) that increments a counter for each prefix.
(This is just a proof of concept, you should also check that the names are valid)
```
public static class TestingProperties
{
private static readonly Dictionary<string, int> _counter = new Dictionary<string, int>();
public static readonly DependencyProperty AutoNameProperty = DependencyProperty.RegisterAttached(
"AutoName", typeof(string), typeof(TestingProperties), new PropertyMetadata(default(string), OnAutoNamePropertyChanged));
private static void OnAutoNamePropertyChanged(DependencyObject element, DependencyPropertyChangedEventArgs eventArgs)
{
string value = (string) eventArgs.NewValue;
if (String.IsNullOrWhiteSpace(value)) return;
if (DesignerProperties.GetIsInDesignMode(element)) return;
if (!(element is FrameworkElement)) return;
int index = 0;
if (!_counter.ContainsKey(value))
_counter.Add(value, index);
else
index = ++_counter[value];
string name = String.Format("{0}_{1}", value, index);
((FrameworkElement)element).Name = name;
((FrameworkElement)element).RegisterName(name, element);
}
public static void SetAutoName(DependencyObject element, string value)
{
element.SetValue(AutoNameProperty, value);
}
public static string GetAutoName(DependencyObject element)
{
return (string)element.GetValue(AutoNameProperty);
}
}
```
Usage in XAML:
```xml
<!-- will be Button_0 -->
<Button namespace:TestingProperties.AutoName="Button"/>
<!-- will be Button_1 -->
<Button namespace:TestingProperties.AutoName="Button"/>
<!-- will be Button_2 -->
<Button namespace:TestingProperties.AutoName="Button"/>
```
Resulting Visual-Tree:
 | Manfred Radlwimmer's solution is useful but makes the controls code behind harder.
Any dynamic code in the Controls' OnApplyTemplate that searches for that template part will become a pain.
An alternative would be to use same trick (generation of a unique id) for the automation id instead and use the automation id in the tests.
See:
<http://www.jonathanantoine.com/2011/11/03/coded-ui-tests-automationid-or-how-to-find-the-chose-one-control/> |
20,810,059 | Is it good practice to declare variables to be used across a program in a Module then populate them in one form and use what you have populated to these variables in another form?
I plan on closing the population form after the data has been populated to the variables so I see this as the only method that would work.
Am I right in thinking that passing parameters from the population form to the display form wouldn't be appropriate in this situation, if even possible? | 2013/12/28 | [
"https://Stackoverflow.com/questions/20810059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2177940/"
] | I guess it **depends** on your application and the kind of data you're talking about.
Think of a `User Login form` that saves the user information after logging in. You can then keep this information in a Module shared across your entire application because it's not expected to change during the session. So you can quickly check the Permission, the Role, the Username from all your program Forms.
On the other end if you're querying a database you are probably asking for the latest data available and you do that in the specific Form you're using, without the need to share it across other Forms in the program. | No, and yes.
Define a class or perhaps more than one to hold the data, pass that about. If by module you mean one of those .bas things with a bunch of primitive types in it, then that would be considered bad practice unless there was no practical alternative.
It's not expected to change was what you said, but if you use a bunch of global variables, you can expect them to be changed and it to be very hard to track down, when and why.
They'll be changed because it was convenient, or in error and you end up with an intermittent major PIA bug. A class with getters and setters on it's properties, and it can manage changes to it's members, so if some "fool" of programmer makes a slight mistake..
The other consideration is unit testing which would be a nightmare if you go the way you are thinking. |
20,810,059 | Is it good practice to declare variables to be used across a program in a Module then populate them in one form and use what you have populated to these variables in another form?
I plan on closing the population form after the data has been populated to the variables so I see this as the only method that would work.
Am I right in thinking that passing parameters from the population form to the display form wouldn't be appropriate in this situation, if even possible? | 2013/12/28 | [
"https://Stackoverflow.com/questions/20810059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2177940/"
] | I guess it **depends** on your application and the kind of data you're talking about.
Think of a `User Login form` that saves the user information after logging in. You can then keep this information in a Module shared across your entire application because it's not expected to change during the session. So you can quickly check the Permission, the Role, the Username from all your program Forms.
On the other end if you're querying a database you are probably asking for the latest data available and you do that in the specific Form you're using, without the need to share it across other Forms in the program. | ...on the other hand, there is nothing whatsoever that a module can do that cannot also be done with a class. For a UserLogin example, leaving it in a module does not make it easier to access:
```
Friend User As New UserLogin
' elsewhere:
theName = User.Name
thePass = User.Password
```
Meanwhile, a class can manage the info:
```
Class UserLogIn
Sub LoadData
Sub SaveData
Function GetLogIn ' display form, validate ID etc
Function ChangePassword
Private gfrm as New LogInForm
Friend Sub Display()
With gfrm
.IgnoreChange = True
.cboName.Text = Name
.cboName.Tag = Name
.txtURL.Text = Location
.txtUser.Text = UserName
.txtPW.Text = DES.DecryptData(_pass)
.txtHint.Text = PassHint
.txtNote.Text = Comment
.IgnoreChange = False
.DataChanged = False
.Show
End With
' store PW hashed or encrypted until needed...
' No one can change the PW except this class
Friend Property PassWord() As String
Get
Return DES.DecryptData(_pass)
End Get
Private Set(ByVal value As String) ' private setter
_pass = DES.EncryptData(value)
End Set
End Property
End Sub
```
Modules are simply not any easier to use, maintain, store or access data. They are considerably less powerful. |
20,810,059 | Is it good practice to declare variables to be used across a program in a Module then populate them in one form and use what you have populated to these variables in another form?
I plan on closing the population form after the data has been populated to the variables so I see this as the only method that would work.
Am I right in thinking that passing parameters from the population form to the display form wouldn't be appropriate in this situation, if even possible? | 2013/12/28 | [
"https://Stackoverflow.com/questions/20810059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2177940/"
] | ...on the other hand, there is nothing whatsoever that a module can do that cannot also be done with a class. For a UserLogin example, leaving it in a module does not make it easier to access:
```
Friend User As New UserLogin
' elsewhere:
theName = User.Name
thePass = User.Password
```
Meanwhile, a class can manage the info:
```
Class UserLogIn
Sub LoadData
Sub SaveData
Function GetLogIn ' display form, validate ID etc
Function ChangePassword
Private gfrm as New LogInForm
Friend Sub Display()
With gfrm
.IgnoreChange = True
.cboName.Text = Name
.cboName.Tag = Name
.txtURL.Text = Location
.txtUser.Text = UserName
.txtPW.Text = DES.DecryptData(_pass)
.txtHint.Text = PassHint
.txtNote.Text = Comment
.IgnoreChange = False
.DataChanged = False
.Show
End With
' store PW hashed or encrypted until needed...
' No one can change the PW except this class
Friend Property PassWord() As String
Get
Return DES.DecryptData(_pass)
End Get
Private Set(ByVal value As String) ' private setter
_pass = DES.EncryptData(value)
End Set
End Property
End Sub
```
Modules are simply not any easier to use, maintain, store or access data. They are considerably less powerful. | No, and yes.
Define a class or perhaps more than one to hold the data, pass that about. If by module you mean one of those .bas things with a bunch of primitive types in it, then that would be considered bad practice unless there was no practical alternative.
It's not expected to change was what you said, but if you use a bunch of global variables, you can expect them to be changed and it to be very hard to track down, when and why.
They'll be changed because it was convenient, or in error and you end up with an intermittent major PIA bug. A class with getters and setters on it's properties, and it can manage changes to it's members, so if some "fool" of programmer makes a slight mistake..
The other consideration is unit testing which would be a nightmare if you go the way you are thinking. |
60,803,621 | I'm having a little trouble figuring out a nested for loop here. Here's the problem:
>
> 3. The population of Ireland is 4.8 million and growing at a rate of 7% per year. Write a program to determine and display the population
> in 10 years time. Your program should also display a count of the
> number of years that the population is predicted to exceed 5 million.
>
>
>
And here's what I've coded so far:
```
double pop = 4.8;
int years = 0;
for (int i = 0; i < 10; i++)
{
pop += (pop / 100) * 7;
for (int j = 0; pop >5; j++)
{
years += j;
}
}
Console.WriteLine("Pop in year 2030 is " + Math.Round(pop, 2) + " million and the population will be over 5 million for " + years + " years.");
}
```
Now to be clear, I need the sum of the years in which population exceeds 5(million) (the answer is 10) and I must only use for loops to solve this problem. I'm thinking the answer is a nested for loop, but have tried and tried with no success.
Can anyone help me on where I've screwed this up? | 2020/03/22 | [
"https://Stackoverflow.com/questions/60803621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13105750/"
] | Look at your inner loop.
```
for (int j = 0; pop >5; j++)
{
years += j;
}
```
Your condition being `pop > 5`, you need `pop` to shrink if you ever want to exit the loop. But the body of the loop never alters `pop`, so if it's greater than 5, you'll loop forever.
The problem definition suggests that you don't need an inner loop at all. Just check `pop`, and if it's greater than 5, increment `years`.
```
if (pop > 5)
{
++years;
}
```
If you're really under such an insane restriction that you can't use `if`, you could do something boneheaded like create a `for` loop that only runs once if your other condition is right.
```
for (int j = 0; j < 1 && pop > 5; ++j)
{
++years;
}
```
but no sane person does this. | First, you need to clearer variable names in my opinion. Of course, don't go to far with that, but IMO `population` will be better than just `pop`.
Furhter, you could use `Dictionary` to store years alongside with preidcted population.
Also, write comments to better see what's going on :)
With this suggestions, I would code this like below:
```
double population = 4.8;
int currentYear = 2020;
Dictionary<int, double> predictions = new Dictionary<int, double>();
// Adding current state
predictions.Add(currentYear, population);
// I changed bounds of a loop to handle years in more comfortable way :)
for (int i = 1; i <= 10; i++)
{
population *= 1.07;
predictions.Add(currentYear + i, population);
}
```
Now you have data in `Dictionary` that looks like this:
```
2020 4.8
2021 ...
2022 ...
... ...
```
Now you can get all years, where population was over 5 million easily with `predictions.Where(kvp => kvp.Value > 5)`. |
60,803,621 | I'm having a little trouble figuring out a nested for loop here. Here's the problem:
>
> 3. The population of Ireland is 4.8 million and growing at a rate of 7% per year. Write a program to determine and display the population
> in 10 years time. Your program should also display a count of the
> number of years that the population is predicted to exceed 5 million.
>
>
>
And here's what I've coded so far:
```
double pop = 4.8;
int years = 0;
for (int i = 0; i < 10; i++)
{
pop += (pop / 100) * 7;
for (int j = 0; pop >5; j++)
{
years += j;
}
}
Console.WriteLine("Pop in year 2030 is " + Math.Round(pop, 2) + " million and the population will be over 5 million for " + years + " years.");
}
```
Now to be clear, I need the sum of the years in which population exceeds 5(million) (the answer is 10) and I must only use for loops to solve this problem. I'm thinking the answer is a nested for loop, but have tried and tried with no success.
Can anyone help me on where I've screwed this up? | 2020/03/22 | [
"https://Stackoverflow.com/questions/60803621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13105750/"
] | Look at your inner loop.
```
for (int j = 0; pop >5; j++)
{
years += j;
}
```
Your condition being `pop > 5`, you need `pop` to shrink if you ever want to exit the loop. But the body of the loop never alters `pop`, so if it's greater than 5, you'll loop forever.
The problem definition suggests that you don't need an inner loop at all. Just check `pop`, and if it's greater than 5, increment `years`.
```
if (pop > 5)
{
++years;
}
```
If you're really under such an insane restriction that you can't use `if`, you could do something boneheaded like create a `for` loop that only runs once if your other condition is right.
```
for (int j = 0; j < 1 && pop > 5; ++j)
{
++years;
}
```
but no sane person does this. | If I well understand your question.
Technically if you add 7% each year your program should look like this
```
bool passed = true;
double pop = 4.8;
int year = 0;
for (int i=0; i<10; i++)
{
pop *= 1.07;
if (pop > 5 && passed)
{
year = i;
passed = false;
}
}
``` |
16,688,245 | I'm trying to deploy my app on heroku. But everytime I try to push my database, I get the following error:
```
heroku db:push
Sending schema
Schema: 100% |==========================================| Time: 00:00:16
Sending indexes
refinery_page: 100% |==========================================| Time: 00:00:02
refinery_page: 100% |==========================================| Time: 00:00:01
refinery_page: 100% |==========================================| Time: 00:00:01
refinery_page: 100% |==========================================| Time: 00:00:04
refinery_role: 100% |==========================================| Time: 00:00:01
refinery_user: 100% |==========================================| Time: 00:00:01
refinery_user: 100% |==========================================| Time: 00:00:00
seo_meta: 100% |==========================================| Time: 00:00:01
schema_migrat: 100% |==========================================| Time: 00:00:00
Sending data
14 tables, 49 records
refinery_arti: 0% |
Saving session to push_201305220223.dat..
!!! Caught Server Exception
HTTP CODE: 500
Taps Server Error: LoadError: no such file to load -- sequel/adapters/
["/app/.bundle/gems/ruby/1.9.1/gems/sequel-3.20.0/lib/sequel/core.rb:249:in `require'",
...
```
I use Rails 3.2.13, Ruby 1.9.3, refinerycms and mysql lite. I also tried to install missing gems ... Is this a fault of heroku? Or am I just stupid? :-)
my gem file:
```
source 'https://rubygems.org'
gem 'rails', '3.2.13'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
group :development, :test do
gem 'sqlite3'
end
group :production do
gem 'pg'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails', '~> 2.0.0'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'debugger'
# Refinery CMS
gem 'refinerycms', '~> 2.0.0', :git => 'git://github.com/refinery/refinerycms.git', :branch => '2-0-stable'
# Specify additional Refinery CMS Extensions here (all optional):
gem 'refinerycms-i18n', '~> 2.0.0'
# gem 'refinerycms-blog', '~> 2.0.0'
# gem 'refinerycms-inquiries', '~> 2.0.0'
# gem 'refinerycms-search', '~> 2.0.0'
# gem 'refinerycms-page-images', '~> 2.0.0'
gem 'refinerycms-articles', :path => 'vendor/extensions'
```
database.yml:
```
# SQLite version 3.x
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
adapter: sqlite3
database: db/production.sqlite3
pool: 5
timeout: 5000
``` | 2013/05/22 | [
"https://Stackoverflow.com/questions/16688245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1458773/"
] | I too had same problem, but i solved with these lines. To my knowledge we cannot request a session for new permissions which is already opened.
```
Session session = new Session(this);
Session.setActiveSession(session);
session.openForRead(new Session.OpenRequest(this).setCallback(callback).setPermissions(Arrays.asList("your_permissions")));
```
I hope you already added below line in `onActivityResult()`
```
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
``` | If the Session is neither opened nor closed, I think it is better to Session.openActiveSession()
This snipped is copied-pasted from the Facebook SDK sample project SessionLoginSample, LoginUsingActivityActivity#onClickLogin()
```
private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
}
}
```
Note that Session#openActiveSession() also creates a Session under the hood, which is OK. From <https://developers.facebook.com/docs/technical-guides/iossdk/session/#lifecycle>:
>
> Sessions can only be opened once. When a session is closed, it cannot
> be re-opened. Instead, a new session should be created. Typical apps
> will only require one active session at any time. The Facebook SDK
> provides static active session methods that take care of opening new
> session instances.
>
>
> |
15,469,904 | I need to set up a listener that can call a method every time a `show()` method is invoked to display a window. How can I do this? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15469904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2172496/"
] | You'd probably be interested in `WindowListener`.
From [the tutorial, "How to Write Window Listeners"](http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html):
>
> The following window activities or states can precede a window event:
>
>
> * Opening a window — Showing a window for the first time.
> * Closing a window — Removing the window from the screen.
> * Iconifying a window — Reducing the window to an icon on the desktop.
> * Deiconifying a window — Restoring the window to its original size.
> * Focused window — The window which contains the "focus owner".
> * Activated window (frame or dialog) — This window is either the focused window, or owns the focused window.
> * Deactivated window — This window has lost the focus. For more information about focus, see the AWT Focus Subsystem specification.
>
>
>
If you don't want to have to implement all of them, you could use a [`WindowAdapter`](http://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowAdapter.html), as follows:
```
myFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent we) {
System.out.println("this window was opened for the first time");
}
@Override
public void windowActivated(WindowEvent we) {
System.out.println("this window or a subframe was focused");
}
});
``` | There is an interface called [WindowListener](http://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowListener.html) and here is a event that gets fired when window is [opened](http://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowListener.html#windowOpened%28java.awt.event.WindowEvent%29).You can find all the events in the first link.
**EDIT :**
The WindowListener works only once. As Per @Andrew Thompson's post we should be using ComponentListener. Certainly **the best answer**. |
15,469,904 | I need to set up a listener that can call a method every time a `show()` method is invoked to display a window. How can I do this? | 2013/03/18 | [
"https://Stackoverflow.com/questions/15469904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2172496/"
] | You'd probably be interested in `WindowListener`.
From [the tutorial, "How to Write Window Listeners"](http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html):
>
> The following window activities or states can precede a window event:
>
>
> * Opening a window — Showing a window for the first time.
> * Closing a window — Removing the window from the screen.
> * Iconifying a window — Reducing the window to an icon on the desktop.
> * Deiconifying a window — Restoring the window to its original size.
> * Focused window — The window which contains the "focus owner".
> * Activated window (frame or dialog) — This window is either the focused window, or owns the focused window.
> * Deactivated window — This window has lost the focus. For more information about focus, see the AWT Focus Subsystem specification.
>
>
>
If you don't want to have to implement all of them, you could use a [`WindowAdapter`](http://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowAdapter.html), as follows:
```
myFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent we) {
System.out.println("this window was opened for the first time");
}
@Override
public void windowActivated(WindowEvent we) {
System.out.println("this window or a subframe was focused");
}
});
``` | Add a `ComponentListener` and check for the `componentShown` event. Note that a `WindowListener` will only fire the **first time** the window is opened while `ComponentListener` will fire ***every*** time.
See [How to Write a Component Listener](http://docs.oracle.com/javase/tutorial/uiswing/events/componentlistener.html) for more details.
This source demonstrates the two listeners.
```
import java.awt.*;
import java.awt.event.*;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.event.*;
class DetectVisibility {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
JPanel gui = new JPanel(new BorderLayout());
final Logger log = Logger.getAnonymousLogger();
ComponentListener cl = new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
log.log(Level.INFO, e.toString());
}
@Override
public void componentMoved(ComponentEvent e) {
log.log(Level.INFO, e.toString());
}
@Override
public void componentShown(ComponentEvent e) {
log.log(Level.INFO, e.toString());
}
@Override
public void componentHidden(ComponentEvent e) {
log.log(Level.INFO, e.toString());
}
};
WindowListener we = new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
log.log(Level.INFO, e.toString());
}
@Override
public void windowClosing(WindowEvent e) {
log.log(Level.INFO, e.toString());
}
@Override
public void windowClosed(WindowEvent e) {
log.log(Level.INFO, e.toString());
}
@Override
public void windowIconified(WindowEvent e) {
log.log(Level.INFO, e.toString());
}
@Override
public void windowDeiconified(WindowEvent e) {
log.log(Level.INFO, e.toString());
}
@Override
public void windowActivated(WindowEvent e) {
log.log(Level.INFO, e.toString());
}
@Override
public void windowDeactivated(WindowEvent e) {
log.log(Level.INFO, e.toString());
}
};
final JWindow w = new JWindow();
w.setSize(100,100);
w.setLocation(10,10);
w.addComponentListener(cl);
w.addWindowListener(we);
final JCheckBox show = new JCheckBox("Show Window");
ChangeListener chl = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
w.setVisible(show.isSelected());
}
};
show.addChangeListener(chl);
gui.add(show);
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
``` |
60,747,796 | I have a simple table
```
**targeted_url_redirect targeted_countries msg_type non_targeted_url**
http://new.botweet.com india,nepal,philippines NEW http://twisend.com
http://expapers.com United States,Canada OLD http://all.twisend.com
https://tweeasy.com india,england OLD http://all.twisend.com
```
I receive traffics on my website `followerise.com` and I want to redirect users to specific urls based on their countries as defined in the above table. I am able to write query to get rows for the users who coming from the countries that are target stored in my database. But I am looking for a solution to get all the rows if the `targeted_countries` condition not return any rows.
I written below queries.
```
SELECT * FROM tweeasy_website_redirection
WHERE message_type='OLD'
AND targeted_countries LIKE '%@country%'
```
This query gives me desired rows if visitor coming from the countries `india`,`england`,`United States`,`Canada`
But I want all rows (2nd and 3rd) should be fetched if a user coming from the countries not specified in `targeted_countries` column.
Also let me know if I need to restructure this table into 2 or more tables to get desired result. | 2020/03/18 | [
"https://Stackoverflow.com/questions/60747796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2014130/"
] | One option uses `not exists`:
```
SELECT t.*
FROM tweeasy_website_redirection t
WHERE
t.message_type = 'OLD'
AND (
t.targeted_countries LIKE '%@country%'
OR NOT EXISTS (
SELECT 1
FROM tweeasy_website_redirection t1
WHERE t1.targeted_countries LIKE '%@country%'
)
)
```
When it comes to the structure of your table: one design flaw is to store list of values as CSV list. You should have two separate tables: one to store the urls, and the other to store the 1-N relationship between urls and countries. Something like:
```
table "url"
id targeted_url_redirect msg_type non_targeted_url
1 http://new.botweet.com NEW http://twisend.com
2 http://expapers.com OLD http://all.twisend.com
3 https://tweeasy.com OLD http://all.twisend.com
table "url_countries"
url_id country
1 india
1 nepal
1 philippines
2 united states
2 canada
3 india
3 england
``` | select \* from tweeasy\_website\_redirection
where targeted\_countries not in (SELECT targeted\_countries FROM stack WHERE targeted\_countries LIKE '%@country%') |
42,549,008 | what is the best way to maintain global variable in `angular2`. I am unable to find a way to maintain a global variable through out the application. After user logged into the application I need `User` object which has user details and `isLoggedIn` values in all other components. Here is what I am doing ...
```
@Injectable()
export class AppGlobals {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);
setLoginStatus(isLoggedIn) {
this.isUserLoggedIn.next(isLoggedIn);
}
setCurrentUser(currentUser) {
this.currentUser.next(currentUser);
}
}
```
In loginComponent I am setting up the `user` and `isLoggedIn` details upon successful login
```
login() {
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.appGlobals.setLoginStatus(true);
this.appGlobals.setCurrentUser(data);
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
```
and accessing the value in other component ....
```
export class ProductsComponent {
currentUser: User;
isLoggedIn: boolean;
constructor(private productService: ProductService, private router:Router,
private confirmationService: ConfirmationService,
private auth: AuthenticationService,
private appGlobal: AppGlobals) {
appGlobal.isUserLoggedIn.subscribe(value => {this.isLoggedIn = value; console.log(value);}); // should be true
appGlobal.currentUser.subscribe(value => {console.log(value); this.userRole = value}); // should have user data
.....
}
.....
}
```
In `ProductsComponent` values for `isLoggedIn` and `currentUser` are correct for the first time but when I refresh the browser I am getting `false for isLoggedIn` and `null for user`. Not sure what I am doing wrong and where. Is it totally wrong way to maintain the user and loggedIn status for all components? I don't want to go with `sessionStorage` or `localStorage`. Please suggest. Thanks. | 2017/03/02 | [
"https://Stackoverflow.com/questions/42549008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653027/"
] | Simply, follow the instructions given in the error:
Download miniconda, then run the script file by typing following command: `bash <file_name.sh>` e.g.
`bash Miniconda3-latest-Linux-x86_64.sh`.
Now reopen the terminal for the changes to take effect.
If conda is already installed on your system, you can reinstall it with the `-f` force option, for example,
`bash Miniconda3-latest-Linux-x86_64.sh -f`
To test your installation, enter the command `conda --version`. If installed correctly, you will see the version of conda installed.
miniconda: <https://conda.io/en/latest/miniconda.html>
conda troubleshooting: <https://conda.io/docs/troubleshooting.html> | **TL;DR**: nothing is corrupted, the message you're seeing is a hardcoded stub and could be fixed.
*conda* package manager actually **can** be used with regular python installation.
**Update**: I've been tinkering with the described method and found that you should use `conda install --dry-run ...` to see changes that are going to happen. Some conda packages depend on other python version, which would overwrite the installed one. There's might be a solution for this with changing conda channels or using virtualenv. I also found that `--dry-run` doesn't work when using local package archives.
I'll show you how to run cudatoolkit 9.1 without any Anaconda and python-3.6-amd64. I'm using cuda 9.1 from [here](https://developer.nvidia.com/cuda-downloads?target_os=Windows&target_arch=x86_64).
Since conda is artificially tethered with Anaconda, you have to untie them.
I recommend you to backup up python installation directory you'll be working with (or use virtualenv).
1. Install *menuinst* dependency.
At the moment, it's broken from PyPi, so get if from
[github](https://github.com/ContinuumIO/menuinst/releases/tag/1.4.8). Build it and install `python setup.py install`
This package is problematic also in Anaconda distribution. It triggers series of requests for admin rights every time, which should be suppressed with `conda ... --no-shortcuts` option.
2. `pip install pypiwin32`, dependency of (1)
3. `pip install conda`, requires (1)
4. Move to python installation directory. **./Scripts/conda.exe** should exist.
5. Move to **./Lib/site-packages/conda**
Search directory recursively for **pip\_warning** substring in following **TEXT** file types: .py, .json, .txt
6. Replace matching substrings **pip\_warning** with **main**
Don't forget to abide the syntax of file types you'd be editing.
7. Now open the **./Scripts/conda.exe** executable in any hex-editor and
find **pip\_warning**, carefully overwrite it with **main** and wipe the
rest with spaces until bytes **import main**
Check for file size not have changed.
8. Remove any **\_\_pycache\_\_** dirs if found in **./Lib/site-packages/conda**
**If you only need working conda without cuda, you're done here.**
9. Run `conda install mkl`, `pip install llvmlite numpy`
10. Download packages [cudatoolkit-9.1-0.tar.bz2](https://anaconda.org/numba/cudatoolkit/files)
and [numba-0.36.2.tar.bz2](https://anaconda.org/anaconda/numba/files?version=0.36.2)
and run
`conda install cudatoolkit-9.1-0.tar.bz2`
`conda install numba-0.36.2-***.tar.bz2`
Wait a little while unpacking finished.
Now try [these](https://numba.pydata.org/numba-doc/dev/cuda/intrinsics.html#example) examples, they should work and your gpu monitor show some activity. `conda ...` commands also do work.
With Linux, I guess instructions are the same, just would be .sh or ELF in place of .exe. |
42,549,008 | what is the best way to maintain global variable in `angular2`. I am unable to find a way to maintain a global variable through out the application. After user logged into the application I need `User` object which has user details and `isLoggedIn` values in all other components. Here is what I am doing ...
```
@Injectable()
export class AppGlobals {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);
setLoginStatus(isLoggedIn) {
this.isUserLoggedIn.next(isLoggedIn);
}
setCurrentUser(currentUser) {
this.currentUser.next(currentUser);
}
}
```
In loginComponent I am setting up the `user` and `isLoggedIn` details upon successful login
```
login() {
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.appGlobals.setLoginStatus(true);
this.appGlobals.setCurrentUser(data);
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
```
and accessing the value in other component ....
```
export class ProductsComponent {
currentUser: User;
isLoggedIn: boolean;
constructor(private productService: ProductService, private router:Router,
private confirmationService: ConfirmationService,
private auth: AuthenticationService,
private appGlobal: AppGlobals) {
appGlobal.isUserLoggedIn.subscribe(value => {this.isLoggedIn = value; console.log(value);}); // should be true
appGlobal.currentUser.subscribe(value => {console.log(value); this.userRole = value}); // should have user data
.....
}
.....
}
```
In `ProductsComponent` values for `isLoggedIn` and `currentUser` are correct for the first time but when I refresh the browser I am getting `false for isLoggedIn` and `null for user`. Not sure what I am doing wrong and where. Is it totally wrong way to maintain the user and loggedIn status for all components? I don't want to go with `sessionStorage` or `localStorage`. Please suggest. Thanks. | 2017/03/02 | [
"https://Stackoverflow.com/questions/42549008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653027/"
] | Simply, follow the instructions given in the error:
Download miniconda, then run the script file by typing following command: `bash <file_name.sh>` e.g.
`bash Miniconda3-latest-Linux-x86_64.sh`.
Now reopen the terminal for the changes to take effect.
If conda is already installed on your system, you can reinstall it with the `-f` force option, for example,
`bash Miniconda3-latest-Linux-x86_64.sh -f`
To test your installation, enter the command `conda --version`. If installed correctly, you will see the version of conda installed.
miniconda: <https://conda.io/en/latest/miniconda.html>
conda troubleshooting: <https://conda.io/docs/troubleshooting.html> | If you are facing this problem in Virtual Machine (VM) then you have to activate the main environment by running below line of code:
```
source /anaconda_installation_folder_path/bin/activate
```
Once you are in your main environment you can work with conda. |
42,549,008 | what is the best way to maintain global variable in `angular2`. I am unable to find a way to maintain a global variable through out the application. After user logged into the application I need `User` object which has user details and `isLoggedIn` values in all other components. Here is what I am doing ...
```
@Injectable()
export class AppGlobals {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);
setLoginStatus(isLoggedIn) {
this.isUserLoggedIn.next(isLoggedIn);
}
setCurrentUser(currentUser) {
this.currentUser.next(currentUser);
}
}
```
In loginComponent I am setting up the `user` and `isLoggedIn` details upon successful login
```
login() {
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.appGlobals.setLoginStatus(true);
this.appGlobals.setCurrentUser(data);
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
```
and accessing the value in other component ....
```
export class ProductsComponent {
currentUser: User;
isLoggedIn: boolean;
constructor(private productService: ProductService, private router:Router,
private confirmationService: ConfirmationService,
private auth: AuthenticationService,
private appGlobal: AppGlobals) {
appGlobal.isUserLoggedIn.subscribe(value => {this.isLoggedIn = value; console.log(value);}); // should be true
appGlobal.currentUser.subscribe(value => {console.log(value); this.userRole = value}); // should have user data
.....
}
.....
}
```
In `ProductsComponent` values for `isLoggedIn` and `currentUser` are correct for the first time but when I refresh the browser I am getting `false for isLoggedIn` and `null for user`. Not sure what I am doing wrong and where. Is it totally wrong way to maintain the user and loggedIn status for all components? I don't want to go with `sessionStorage` or `localStorage`. Please suggest. Thanks. | 2017/03/02 | [
"https://Stackoverflow.com/questions/42549008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653027/"
] | Simply, follow the instructions given in the error:
Download miniconda, then run the script file by typing following command: `bash <file_name.sh>` e.g.
`bash Miniconda3-latest-Linux-x86_64.sh`.
Now reopen the terminal for the changes to take effect.
If conda is already installed on your system, you can reinstall it with the `-f` force option, for example,
`bash Miniconda3-latest-Linux-x86_64.sh -f`
To test your installation, enter the command `conda --version`. If installed correctly, you will see the version of conda installed.
miniconda: <https://conda.io/en/latest/miniconda.html>
conda troubleshooting: <https://conda.io/docs/troubleshooting.html> | In my case, what worked was:
```
pip uninstall conda
```
and then installing [miniconda](https://docs.conda.io/en/latest/miniconda.html) |
42,549,008 | what is the best way to maintain global variable in `angular2`. I am unable to find a way to maintain a global variable through out the application. After user logged into the application I need `User` object which has user details and `isLoggedIn` values in all other components. Here is what I am doing ...
```
@Injectable()
export class AppGlobals {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);
setLoginStatus(isLoggedIn) {
this.isUserLoggedIn.next(isLoggedIn);
}
setCurrentUser(currentUser) {
this.currentUser.next(currentUser);
}
}
```
In loginComponent I am setting up the `user` and `isLoggedIn` details upon successful login
```
login() {
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.appGlobals.setLoginStatus(true);
this.appGlobals.setCurrentUser(data);
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
```
and accessing the value in other component ....
```
export class ProductsComponent {
currentUser: User;
isLoggedIn: boolean;
constructor(private productService: ProductService, private router:Router,
private confirmationService: ConfirmationService,
private auth: AuthenticationService,
private appGlobal: AppGlobals) {
appGlobal.isUserLoggedIn.subscribe(value => {this.isLoggedIn = value; console.log(value);}); // should be true
appGlobal.currentUser.subscribe(value => {console.log(value); this.userRole = value}); // should have user data
.....
}
.....
}
```
In `ProductsComponent` values for `isLoggedIn` and `currentUser` are correct for the first time but when I refresh the browser I am getting `false for isLoggedIn` and `null for user`. Not sure what I am doing wrong and where. Is it totally wrong way to maintain the user and loggedIn status for all components? I don't want to go with `sessionStorage` or `localStorage`. Please suggest. Thanks. | 2017/03/02 | [
"https://Stackoverflow.com/questions/42549008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653027/"
] | Simply, follow the instructions given in the error:
Download miniconda, then run the script file by typing following command: `bash <file_name.sh>` e.g.
`bash Miniconda3-latest-Linux-x86_64.sh`.
Now reopen the terminal for the changes to take effect.
If conda is already installed on your system, you can reinstall it with the `-f` force option, for example,
`bash Miniconda3-latest-Linux-x86_64.sh -f`
To test your installation, enter the command `conda --version`. If installed correctly, you will see the version of conda installed.
miniconda: <https://conda.io/en/latest/miniconda.html>
conda troubleshooting: <https://conda.io/docs/troubleshooting.html> | Download miniconda, then run the script file by typing following command: bash <file\_name.sh> e.g. bash Miniconda3-latest-Linux-x86\_64.sh -u
'-u' : update tag, used if the original conda bash paths get lost due to certain modifications in the .bashrc file |
42,549,008 | what is the best way to maintain global variable in `angular2`. I am unable to find a way to maintain a global variable through out the application. After user logged into the application I need `User` object which has user details and `isLoggedIn` values in all other components. Here is what I am doing ...
```
@Injectable()
export class AppGlobals {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);
setLoginStatus(isLoggedIn) {
this.isUserLoggedIn.next(isLoggedIn);
}
setCurrentUser(currentUser) {
this.currentUser.next(currentUser);
}
}
```
In loginComponent I am setting up the `user` and `isLoggedIn` details upon successful login
```
login() {
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.appGlobals.setLoginStatus(true);
this.appGlobals.setCurrentUser(data);
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
```
and accessing the value in other component ....
```
export class ProductsComponent {
currentUser: User;
isLoggedIn: boolean;
constructor(private productService: ProductService, private router:Router,
private confirmationService: ConfirmationService,
private auth: AuthenticationService,
private appGlobal: AppGlobals) {
appGlobal.isUserLoggedIn.subscribe(value => {this.isLoggedIn = value; console.log(value);}); // should be true
appGlobal.currentUser.subscribe(value => {console.log(value); this.userRole = value}); // should have user data
.....
}
.....
}
```
In `ProductsComponent` values for `isLoggedIn` and `currentUser` are correct for the first time but when I refresh the browser I am getting `false for isLoggedIn` and `null for user`. Not sure what I am doing wrong and where. Is it totally wrong way to maintain the user and loggedIn status for all components? I don't want to go with `sessionStorage` or `localStorage`. Please suggest. Thanks. | 2017/03/02 | [
"https://Stackoverflow.com/questions/42549008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653027/"
] | **TL;DR**: nothing is corrupted, the message you're seeing is a hardcoded stub and could be fixed.
*conda* package manager actually **can** be used with regular python installation.
**Update**: I've been tinkering with the described method and found that you should use `conda install --dry-run ...` to see changes that are going to happen. Some conda packages depend on other python version, which would overwrite the installed one. There's might be a solution for this with changing conda channels or using virtualenv. I also found that `--dry-run` doesn't work when using local package archives.
I'll show you how to run cudatoolkit 9.1 without any Anaconda and python-3.6-amd64. I'm using cuda 9.1 from [here](https://developer.nvidia.com/cuda-downloads?target_os=Windows&target_arch=x86_64).
Since conda is artificially tethered with Anaconda, you have to untie them.
I recommend you to backup up python installation directory you'll be working with (or use virtualenv).
1. Install *menuinst* dependency.
At the moment, it's broken from PyPi, so get if from
[github](https://github.com/ContinuumIO/menuinst/releases/tag/1.4.8). Build it and install `python setup.py install`
This package is problematic also in Anaconda distribution. It triggers series of requests for admin rights every time, which should be suppressed with `conda ... --no-shortcuts` option.
2. `pip install pypiwin32`, dependency of (1)
3. `pip install conda`, requires (1)
4. Move to python installation directory. **./Scripts/conda.exe** should exist.
5. Move to **./Lib/site-packages/conda**
Search directory recursively for **pip\_warning** substring in following **TEXT** file types: .py, .json, .txt
6. Replace matching substrings **pip\_warning** with **main**
Don't forget to abide the syntax of file types you'd be editing.
7. Now open the **./Scripts/conda.exe** executable in any hex-editor and
find **pip\_warning**, carefully overwrite it with **main** and wipe the
rest with spaces until bytes **import main**
Check for file size not have changed.
8. Remove any **\_\_pycache\_\_** dirs if found in **./Lib/site-packages/conda**
**If you only need working conda without cuda, you're done here.**
9. Run `conda install mkl`, `pip install llvmlite numpy`
10. Download packages [cudatoolkit-9.1-0.tar.bz2](https://anaconda.org/numba/cudatoolkit/files)
and [numba-0.36.2.tar.bz2](https://anaconda.org/anaconda/numba/files?version=0.36.2)
and run
`conda install cudatoolkit-9.1-0.tar.bz2`
`conda install numba-0.36.2-***.tar.bz2`
Wait a little while unpacking finished.
Now try [these](https://numba.pydata.org/numba-doc/dev/cuda/intrinsics.html#example) examples, they should work and your gpu monitor show some activity. `conda ...` commands also do work.
With Linux, I guess instructions are the same, just would be .sh or ELF in place of .exe. | In my case, what worked was:
```
pip uninstall conda
```
and then installing [miniconda](https://docs.conda.io/en/latest/miniconda.html) |
42,549,008 | what is the best way to maintain global variable in `angular2`. I am unable to find a way to maintain a global variable through out the application. After user logged into the application I need `User` object which has user details and `isLoggedIn` values in all other components. Here is what I am doing ...
```
@Injectable()
export class AppGlobals {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);
setLoginStatus(isLoggedIn) {
this.isUserLoggedIn.next(isLoggedIn);
}
setCurrentUser(currentUser) {
this.currentUser.next(currentUser);
}
}
```
In loginComponent I am setting up the `user` and `isLoggedIn` details upon successful login
```
login() {
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.appGlobals.setLoginStatus(true);
this.appGlobals.setCurrentUser(data);
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
```
and accessing the value in other component ....
```
export class ProductsComponent {
currentUser: User;
isLoggedIn: boolean;
constructor(private productService: ProductService, private router:Router,
private confirmationService: ConfirmationService,
private auth: AuthenticationService,
private appGlobal: AppGlobals) {
appGlobal.isUserLoggedIn.subscribe(value => {this.isLoggedIn = value; console.log(value);}); // should be true
appGlobal.currentUser.subscribe(value => {console.log(value); this.userRole = value}); // should have user data
.....
}
.....
}
```
In `ProductsComponent` values for `isLoggedIn` and `currentUser` are correct for the first time but when I refresh the browser I am getting `false for isLoggedIn` and `null for user`. Not sure what I am doing wrong and where. Is it totally wrong way to maintain the user and loggedIn status for all components? I don't want to go with `sessionStorage` or `localStorage`. Please suggest. Thanks. | 2017/03/02 | [
"https://Stackoverflow.com/questions/42549008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653027/"
] | **TL;DR**: nothing is corrupted, the message you're seeing is a hardcoded stub and could be fixed.
*conda* package manager actually **can** be used with regular python installation.
**Update**: I've been tinkering with the described method and found that you should use `conda install --dry-run ...` to see changes that are going to happen. Some conda packages depend on other python version, which would overwrite the installed one. There's might be a solution for this with changing conda channels or using virtualenv. I also found that `--dry-run` doesn't work when using local package archives.
I'll show you how to run cudatoolkit 9.1 without any Anaconda and python-3.6-amd64. I'm using cuda 9.1 from [here](https://developer.nvidia.com/cuda-downloads?target_os=Windows&target_arch=x86_64).
Since conda is artificially tethered with Anaconda, you have to untie them.
I recommend you to backup up python installation directory you'll be working with (or use virtualenv).
1. Install *menuinst* dependency.
At the moment, it's broken from PyPi, so get if from
[github](https://github.com/ContinuumIO/menuinst/releases/tag/1.4.8). Build it and install `python setup.py install`
This package is problematic also in Anaconda distribution. It triggers series of requests for admin rights every time, which should be suppressed with `conda ... --no-shortcuts` option.
2. `pip install pypiwin32`, dependency of (1)
3. `pip install conda`, requires (1)
4. Move to python installation directory. **./Scripts/conda.exe** should exist.
5. Move to **./Lib/site-packages/conda**
Search directory recursively for **pip\_warning** substring in following **TEXT** file types: .py, .json, .txt
6. Replace matching substrings **pip\_warning** with **main**
Don't forget to abide the syntax of file types you'd be editing.
7. Now open the **./Scripts/conda.exe** executable in any hex-editor and
find **pip\_warning**, carefully overwrite it with **main** and wipe the
rest with spaces until bytes **import main**
Check for file size not have changed.
8. Remove any **\_\_pycache\_\_** dirs if found in **./Lib/site-packages/conda**
**If you only need working conda without cuda, you're done here.**
9. Run `conda install mkl`, `pip install llvmlite numpy`
10. Download packages [cudatoolkit-9.1-0.tar.bz2](https://anaconda.org/numba/cudatoolkit/files)
and [numba-0.36.2.tar.bz2](https://anaconda.org/anaconda/numba/files?version=0.36.2)
and run
`conda install cudatoolkit-9.1-0.tar.bz2`
`conda install numba-0.36.2-***.tar.bz2`
Wait a little while unpacking finished.
Now try [these](https://numba.pydata.org/numba-doc/dev/cuda/intrinsics.html#example) examples, they should work and your gpu monitor show some activity. `conda ...` commands also do work.
With Linux, I guess instructions are the same, just would be .sh or ELF in place of .exe. | Download miniconda, then run the script file by typing following command: bash <file\_name.sh> e.g. bash Miniconda3-latest-Linux-x86\_64.sh -u
'-u' : update tag, used if the original conda bash paths get lost due to certain modifications in the .bashrc file |
42,549,008 | what is the best way to maintain global variable in `angular2`. I am unable to find a way to maintain a global variable through out the application. After user logged into the application I need `User` object which has user details and `isLoggedIn` values in all other components. Here is what I am doing ...
```
@Injectable()
export class AppGlobals {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);
setLoginStatus(isLoggedIn) {
this.isUserLoggedIn.next(isLoggedIn);
}
setCurrentUser(currentUser) {
this.currentUser.next(currentUser);
}
}
```
In loginComponent I am setting up the `user` and `isLoggedIn` details upon successful login
```
login() {
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.appGlobals.setLoginStatus(true);
this.appGlobals.setCurrentUser(data);
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
```
and accessing the value in other component ....
```
export class ProductsComponent {
currentUser: User;
isLoggedIn: boolean;
constructor(private productService: ProductService, private router:Router,
private confirmationService: ConfirmationService,
private auth: AuthenticationService,
private appGlobal: AppGlobals) {
appGlobal.isUserLoggedIn.subscribe(value => {this.isLoggedIn = value; console.log(value);}); // should be true
appGlobal.currentUser.subscribe(value => {console.log(value); this.userRole = value}); // should have user data
.....
}
.....
}
```
In `ProductsComponent` values for `isLoggedIn` and `currentUser` are correct for the first time but when I refresh the browser I am getting `false for isLoggedIn` and `null for user`. Not sure what I am doing wrong and where. Is it totally wrong way to maintain the user and loggedIn status for all components? I don't want to go with `sessionStorage` or `localStorage`. Please suggest. Thanks. | 2017/03/02 | [
"https://Stackoverflow.com/questions/42549008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653027/"
] | If you are facing this problem in Virtual Machine (VM) then you have to activate the main environment by running below line of code:
```
source /anaconda_installation_folder_path/bin/activate
```
Once you are in your main environment you can work with conda. | In my case, what worked was:
```
pip uninstall conda
```
and then installing [miniconda](https://docs.conda.io/en/latest/miniconda.html) |
42,549,008 | what is the best way to maintain global variable in `angular2`. I am unable to find a way to maintain a global variable through out the application. After user logged into the application I need `User` object which has user details and `isLoggedIn` values in all other components. Here is what I am doing ...
```
@Injectable()
export class AppGlobals {
public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);
setLoginStatus(isLoggedIn) {
this.isUserLoggedIn.next(isLoggedIn);
}
setCurrentUser(currentUser) {
this.currentUser.next(currentUser);
}
}
```
In loginComponent I am setting up the `user` and `isLoggedIn` details upon successful login
```
login() {
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.appGlobals.setLoginStatus(true);
this.appGlobals.setCurrentUser(data);
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
```
and accessing the value in other component ....
```
export class ProductsComponent {
currentUser: User;
isLoggedIn: boolean;
constructor(private productService: ProductService, private router:Router,
private confirmationService: ConfirmationService,
private auth: AuthenticationService,
private appGlobal: AppGlobals) {
appGlobal.isUserLoggedIn.subscribe(value => {this.isLoggedIn = value; console.log(value);}); // should be true
appGlobal.currentUser.subscribe(value => {console.log(value); this.userRole = value}); // should have user data
.....
}
.....
}
```
In `ProductsComponent` values for `isLoggedIn` and `currentUser` are correct for the first time but when I refresh the browser I am getting `false for isLoggedIn` and `null for user`. Not sure what I am doing wrong and where. Is it totally wrong way to maintain the user and loggedIn status for all components? I don't want to go with `sessionStorage` or `localStorage`. Please suggest. Thanks. | 2017/03/02 | [
"https://Stackoverflow.com/questions/42549008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653027/"
] | If you are facing this problem in Virtual Machine (VM) then you have to activate the main environment by running below line of code:
```
source /anaconda_installation_folder_path/bin/activate
```
Once you are in your main environment you can work with conda. | Download miniconda, then run the script file by typing following command: bash <file\_name.sh> e.g. bash Miniconda3-latest-Linux-x86\_64.sh -u
'-u' : update tag, used if the original conda bash paths get lost due to certain modifications in the .bashrc file |
56,197,545 | I have Tab navigator that handles data changing of itself and other two sibling component.
**Main parent Component** that does data fetching and manipulation based on three sentiments: positive, negative and neutral as request body parameter in *http post request*.
**Second parent component** that stores all positive data, negative data and neutral data from main parent component.
Then **three** **Child Components**: **Table one and Tab Navigation**.
The Tab navigation has three three tabs namely: *Positive, Negative and Neutral*.
As soon as the page renders on first load, by default (without clicking positive tab button), it fetches positive data and displays it in all three child components. Then on clicking on Negative tab, it should display negative data in all three child components i.e. Table one and under negative tab of tab navigation. Same thing follows for Neutral Tab.
In short, Tab navigation handles data rendering of it's self and sibling components based on its active state and getting that data from parent component.
I tried passing the active event from tab navigation to its upper container but it doesn't seem to work fine.
Tab.js
```
import React, { Component } from 'react';
export default class Tab extends Component
{
constructor(props)
{
super(props);
this.state =
{
active: 'positive',
}
}
toggle = (event) =>
{
this.setState({
active: event
})
this.props.sendEvent(this.state.active);
}
get_tab_content =()=>
{
switch(this.state.active)
{
case 'positive':
return <div><SomeDataComponent1 positiveprops={} /></div>;
case 'negative':
return <div><SomeDataComponent2 negativeprops={}/></div>;
case 'neutral':
return <div><SomeDataComponent3 neutralprops={} /></div>;
default :
}
}
render() {
const tabStyles = {
display: 'flex',
justifyContent: 'center',
listStyleType: 'none',
cursor: 'pointer',
width: '100px',
padding: 5,
margin: 4,
fontSize: 20,
color: 'green'
}
const tabStyles2 = {
display: 'flex',
justifyContent: 'center',
listStyleType: 'none',
cursor: 'pointer',
width: '100px',
padding: 5,
margin: 4,
fontSize: 20,
color: 'red'
}
const tabStyles3 = {
display: 'flex',
justifyContent: 'center',
listStyleType: 'none',
cursor: 'pointer',
width: '100px',
padding: 5,
margin: 4,
fontSize: 20,
color: 'yellow'
}
const linkStyles = {
display: 'flex',
justifyContent: 'center',
color: '#000',
listStyleType: 'none'
}
const divStyle = {
border: '1px solid #34baa2',
width: '450px'
}
const box = this.get_tab_content()
return (
<div style={divStyle} >
<ul style={linkStyles}>
<li style={tabStyles} onClick={function(){this.toggle('positive')}.bind(this)}>Positive</li>
<li style={tabStyles2} onClick={function(){this.toggle('negative')}.bind(this)}>Negative</li>
<li style={tabStyles3} onClick={function(){this.toggle('neutral')}.bind(this)}>Neutral</li>
</ul>
<div>
{box}
</div>
</div>
);
}
}
```
Second Parent Component.js
```
import React,{Component} from 'react';
import Tab from '../tab/tab';
import MentionTable from '../table/table';
class DataCharts extends Component{
constructor(props){
super(props);
this.state = {
childEvent: ''
}
}
getEvent = (childevent) => {
this.setState({
childEvent: childevent
});
console.log(this.state.childEvent)
}
render(){
const {positivetable,positivewords, negativetable, negativewords, neutraltable, neutralwords } = this.props;
return(
<div style={{display:'flex', flexDirection: 'row'}}>
<Table />
<Tab sendEvent={this.getEvent}/>
</div>
)
}
}
export default DataCharts;
``` | 2019/05/18 | [
"https://Stackoverflow.com/questions/56197545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11349591/"
] | You need **urgently** research about SQL injection, and **STOP USING** string concatenation for building your SQL insert statement **RIGHT NOW**.
You need to use the proper technique - **parametrized queries** -- always - **NO** exceptions!
And also, it's a commonly accepted Best Practice to list the columns in your `INSERT` statement, to avoid trouble when tables change their columns (read more about this here: [Bad habits to kick: using SELECT \* / omit the column list](http://sqlblog.org/2009/10/10/bad-habits-to-kick-using-select-omitting-the-column-list.aspx) ).
Use this code as a sample/template:
```
string insertQuery = @"INSERT INTO dbo.Table1 (FirstName, LastName, City)
VALUES (@FirstName, @LastName, @City);";
using (SqlCommand cmd = new SqlCommmand(insertQuery, con))
{
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstname.Text;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 50).Value = lastname.Text;
cmd.Parameters.Add("@City", SqlDbType.VarChar, 50).Value = city.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close()
}
``` | You should specify the columns names. For example:
```
cmd.CommandText = $"Insert into Table1 ({ColumnName of firstname}, { ColumnName of lastname}, { ColumnName of city})
values({firstname.Text}, {lastname.Text}, {city.Text})";
```
You can better use a stored procedure - something like that:
```
cmd.CommandText = "your SP name";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = firstName.Text;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = lastName.Text;
etc...
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.