qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
2,970,248
This question is related but not the same as this: [How do you give a C# Auto-Property a default value?](https://stackoverflow.com/questions/40730/how-do-you-give-a-c-auto-property-a-default-value) I love auto-properties, but sometimes I have to do something like this: ``` private string someName; public string SomeName { get { return someName; } set { someName = value.Trim(); } } ``` If I have to do the same thing many times, I start wishing that I did not need to type so many lines/characters of code. I want to be able to intercept the value and change it sort of like so: ``` public string Somename { get; [Trim] set; } ``` Is there a way to do something like this? Would it be stupid? Is there a better way? Any other general comments? I admit, the example I gave is a bit hypothetical and I cannot locate the exact code now which made me think of this. Thanks.
2010/06/03
[ "https://Stackoverflow.com/questions/2970248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231677/" ]
Your database is not normalized. You say it's all in one table, but you haven't given any information about the schema. The kinds of problems which non-normalized databases have include problems with consistency related to storing redundant information - if you have something like: Album, Track, Artist then to change the Album name, you have to change it on every track associated with the Album. Of course, there are all kinds of "database" systems out there which are not normalized, but these usually have mechanisms to handle these kinds of things which are appropriate to their paradigms.
pretty screwed, indeed. it's hardly normalized. go for separate tables. if you've never heard of normalization or understood why it was important, perhaps you should read [this](http://www.phlonx.com/resources/nf3/). it's a succinct, simple explanation without a lot of jargon. or you could go straight to the source since you're already using mysql: <http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html> think about the cardinalities and relationships in your model: 1. an album will have zero or more tracks; a track will belong to only one album (album-to-track is one to many) 2. an artist can create zero or more albums; an album can be created by one or more artists (artist-to-album is many-to-many) you'll want to think carefully about indexes, primary, and foreign keys. add indexes to non-key columns or groups that you'll want to search on. this design would have four tables: album, track, artist, and artist\_to\_album many to many join table.
2,970,248
This question is related but not the same as this: [How do you give a C# Auto-Property a default value?](https://stackoverflow.com/questions/40730/how-do-you-give-a-c-auto-property-a-default-value) I love auto-properties, but sometimes I have to do something like this: ``` private string someName; public string SomeName { get { return someName; } set { someName = value.Trim(); } } ``` If I have to do the same thing many times, I start wishing that I did not need to type so many lines/characters of code. I want to be able to intercept the value and change it sort of like so: ``` public string Somename { get; [Trim] set; } ``` Is there a way to do something like this? Would it be stupid? Is there a better way? Any other general comments? I admit, the example I gave is a bit hypothetical and I cannot locate the exact code now which made me think of this. Thanks.
2010/06/03
[ "https://Stackoverflow.com/questions/2970248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231677/" ]
pretty screwed, indeed. it's hardly normalized. go for separate tables. if you've never heard of normalization or understood why it was important, perhaps you should read [this](http://www.phlonx.com/resources/nf3/). it's a succinct, simple explanation without a lot of jargon. or you could go straight to the source since you're already using mysql: <http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html> think about the cardinalities and relationships in your model: 1. an album will have zero or more tracks; a track will belong to only one album (album-to-track is one to many) 2. an artist can create zero or more albums; an album can be created by one or more artists (artist-to-album is many-to-many) you'll want to think carefully about indexes, primary, and foreign keys. add indexes to non-key columns or groups that you'll want to search on. this design would have four tables: album, track, artist, and artist\_to\_album many to many join table.
So the subject you're asking about is called "Normalization" and while this is useful in many circumstances, it can't always be applied. Consider the artist Pink. Some of her albums have her name as `Pink` and others `P!nk` which we recognize as the same visually, because we know it's her. But a database would by force see these two separately (which also makes searching for her songs harder, but that's another story). Also consider Prince, "The artist formally known as Prince", etc. So it might be possible to have an artist `ID` that matches to both `Pink` and `P!nk` but that also matches to her albums `Funhouse` etc. (I'm really gonna stop with the examples now, as any more examples will need to be tabular). So, I think the question becomes, how complex do you want your searching to be? As is, you're able to maintain a 1:1 correlation between tag and database info. It just depends how fancy you want things to be. Also, for the lookup I mentioned above, consider that most times that information is coming from the user, you really can't supply a lookup from P!nk to Pink any more than you would from Elephant to Pachyderm because you don't know what people are going to want to enter. I think in this case, the naive approach is just as well.
2,970,248
This question is related but not the same as this: [How do you give a C# Auto-Property a default value?](https://stackoverflow.com/questions/40730/how-do-you-give-a-c-auto-property-a-default-value) I love auto-properties, but sometimes I have to do something like this: ``` private string someName; public string SomeName { get { return someName; } set { someName = value.Trim(); } } ``` If I have to do the same thing many times, I start wishing that I did not need to type so many lines/characters of code. I want to be able to intercept the value and change it sort of like so: ``` public string Somename { get; [Trim] set; } ``` Is there a way to do something like this? Would it be stupid? Is there a better way? Any other general comments? I admit, the example I gave is a bit hypothetical and I cannot locate the exact code now which made me think of this. Thanks.
2010/06/03
[ "https://Stackoverflow.com/questions/2970248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231677/" ]
In regards to the Pink/P!nk situation, if that's a big deal to you, then yes, normalization would be useful. Your songs table would reference an artist\_id. You'd also have a table of artist aliases, which would map the various names that a particular artist has gone by to that artist\_id. But this can get pretty complex, and technically, it may not even be correct in your situation, as if an artist chooses to release projects under different names, they may not want them all lumped together. In general, normalized databases are a safe place to start, but there are plenty of good reasons to denormalize, and it is more important to understand those reasons then blindly always do things one way.
pretty screwed, indeed. it's hardly normalized. go for separate tables. if you've never heard of normalization or understood why it was important, perhaps you should read [this](http://www.phlonx.com/resources/nf3/). it's a succinct, simple explanation without a lot of jargon. or you could go straight to the source since you're already using mysql: <http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html> think about the cardinalities and relationships in your model: 1. an album will have zero or more tracks; a track will belong to only one album (album-to-track is one to many) 2. an artist can create zero or more albums; an album can be created by one or more artists (artist-to-album is many-to-many) you'll want to think carefully about indexes, primary, and foreign keys. add indexes to non-key columns or groups that you'll want to search on. this design would have four tables: album, track, artist, and artist\_to\_album many to many join table.
2,970,248
This question is related but not the same as this: [How do you give a C# Auto-Property a default value?](https://stackoverflow.com/questions/40730/how-do-you-give-a-c-auto-property-a-default-value) I love auto-properties, but sometimes I have to do something like this: ``` private string someName; public string SomeName { get { return someName; } set { someName = value.Trim(); } } ``` If I have to do the same thing many times, I start wishing that I did not need to type so many lines/characters of code. I want to be able to intercept the value and change it sort of like so: ``` public string Somename { get; [Trim] set; } ``` Is there a way to do something like this? Would it be stupid? Is there a better way? Any other general comments? I admit, the example I gave is a bit hypothetical and I cannot locate the exact code now which made me think of this. Thanks.
2010/06/03
[ "https://Stackoverflow.com/questions/2970248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231677/" ]
Your database is not normalized. You say it's all in one table, but you haven't given any information about the schema. The kinds of problems which non-normalized databases have include problems with consistency related to storing redundant information - if you have something like: Album, Track, Artist then to change the Album name, you have to change it on every track associated with the Album. Of course, there are all kinds of "database" systems out there which are not normalized, but these usually have mechanisms to handle these kinds of things which are appropriate to their paradigms.
So the subject you're asking about is called "Normalization" and while this is useful in many circumstances, it can't always be applied. Consider the artist Pink. Some of her albums have her name as `Pink` and others `P!nk` which we recognize as the same visually, because we know it's her. But a database would by force see these two separately (which also makes searching for her songs harder, but that's another story). Also consider Prince, "The artist formally known as Prince", etc. So it might be possible to have an artist `ID` that matches to both `Pink` and `P!nk` but that also matches to her albums `Funhouse` etc. (I'm really gonna stop with the examples now, as any more examples will need to be tabular). So, I think the question becomes, how complex do you want your searching to be? As is, you're able to maintain a 1:1 correlation between tag and database info. It just depends how fancy you want things to be. Also, for the lookup I mentioned above, consider that most times that information is coming from the user, you really can't supply a lookup from P!nk to Pink any more than you would from Elephant to Pachyderm because you don't know what people are going to want to enter. I think in this case, the naive approach is just as well.
2,970,248
This question is related but not the same as this: [How do you give a C# Auto-Property a default value?](https://stackoverflow.com/questions/40730/how-do-you-give-a-c-auto-property-a-default-value) I love auto-properties, but sometimes I have to do something like this: ``` private string someName; public string SomeName { get { return someName; } set { someName = value.Trim(); } } ``` If I have to do the same thing many times, I start wishing that I did not need to type so many lines/characters of code. I want to be able to intercept the value and change it sort of like so: ``` public string Somename { get; [Trim] set; } ``` Is there a way to do something like this? Would it be stupid? Is there a better way? Any other general comments? I admit, the example I gave is a bit hypothetical and I cannot locate the exact code now which made me think of this. Thanks.
2010/06/03
[ "https://Stackoverflow.com/questions/2970248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231677/" ]
In regards to the Pink/P!nk situation, if that's a big deal to you, then yes, normalization would be useful. Your songs table would reference an artist\_id. You'd also have a table of artist aliases, which would map the various names that a particular artist has gone by to that artist\_id. But this can get pretty complex, and technically, it may not even be correct in your situation, as if an artist chooses to release projects under different names, they may not want them all lumped together. In general, normalized databases are a safe place to start, but there are plenty of good reasons to denormalize, and it is more important to understand those reasons then blindly always do things one way.
So the subject you're asking about is called "Normalization" and while this is useful in many circumstances, it can't always be applied. Consider the artist Pink. Some of her albums have her name as `Pink` and others `P!nk` which we recognize as the same visually, because we know it's her. But a database would by force see these two separately (which also makes searching for her songs harder, but that's another story). Also consider Prince, "The artist formally known as Prince", etc. So it might be possible to have an artist `ID` that matches to both `Pink` and `P!nk` but that also matches to her albums `Funhouse` etc. (I'm really gonna stop with the examples now, as any more examples will need to be tabular). So, I think the question becomes, how complex do you want your searching to be? As is, you're able to maintain a 1:1 correlation between tag and database info. It just depends how fancy you want things to be. Also, for the lookup I mentioned above, consider that most times that information is coming from the user, you really can't supply a lookup from P!nk to Pink any more than you would from Elephant to Pachyderm because you don't know what people are going to want to enter. I think in this case, the naive approach is just as well.
39,573,568
How can I use result from a `LEFT JOIN` in an `IN` clause? This is my query so far: ``` SELECT n.id, n.title, n.public, CAST(GROUP_CONCAT(DISTINCT ngm.members_group_id) AS CHAR(1000)) AS `news_groups_text`, GROUP_CONCAT(DISTINCT ngm.members_group_id) AS `news_groups` FROM news n LEFT JOIN news_groups_map ngm ON ngm.news_id = n.id WHERE public=0 GROUP BY n.id ``` Which returns results in form ``` id title public news_groups_text news_groups 159 Test 0 5,6,4 (BLOB) 5 bytes ``` How can I add a clause that checks which groups the article belongs to? For example, I have groups 4 and 6, I need to return all results that have at least one of them in `news_groups`. I am trying to get to check one group with `IN` clause, by adding this to the `WHERE` clause: ``` WHERE public=0 AND 4 IN (GROUP_CONCAT(DISTINCT ngm.members_group_id)) ``` But then i get error `[Err] 1111 - Invalid use of group function` How can I filter out the articles by groups? If I could check at least one group I could just chain them with `AND` Thanks!
2016/09/19
[ "https://Stackoverflow.com/questions/39573568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594299/" ]
I think you are looking for [**`FIND_IN_SET`**](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set): ``` FIND_IN_SET(4, news_groups_text) ``` **Note**: This can be used only by an outer query that uses the original query as a subquery. But it is more natural to place the condition in the `HAVING` clause: ``` HAVING COUNT(CASE WHEN news_groups_text=4 THEN 1 END) > 0 ```
The simplest way to do this in MySQL is to use a `HAVING` clause after the `GROUP BY`. The simplest such clause is: ``` HAVING MAX(ngm.members_group_id = 4) > 0 ```
5,716,123
Is it possible to declare `DataGrid` columns in a style or as a resource? I would like to do something like this: ``` <....Resources> <DataGridColumns x:Key="dgcDataGridColumns"> <DataGridTextColumn /> <DataGridTextColumn /> </DataGridColumns </....Resources> <DataGrid Columns="{StaticResource dgcDataGridColumns}" /> ``` The reason is that i have to share the column definition for 4 different `DataGrids`. Any way to achieve this? Best would be without code behind!
2011/04/19
[ "https://Stackoverflow.com/questions/5716123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/613320/" ]
Columns property of the DataGrid has no setter so it is not possibly. You can however do something like this: ``` <Window.Resources> <Controls:DataGrid x:Key="PersonDataGrid" AutoGenerateColumns="False" ItemsSource="{Binding .}" x:Shared="False"> <Controls:DataGrid.Columns> <Controls:DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}" IsReadOnly="True"/> <Controls:DataGridTextColumn Header="Last Name" Binding="{Binding Path=LastName}" IsReadOnly="True"/> </Controls:DataGrid.Columns> </Controls:DataGrid> </Window.Resources> <StackPanel> <ContentControl Content="{StaticResource PersonDataGrid}" DataContext="{Binding Path=Customers}"></ContentControl> <ContentControl Content="{StaticResource PersonDataGrid}" DataContext="{Binding Path=Employees}"></ContentControl> </StackPanel> ```
I don't think you can, as in that situation you aren't specifying a template or a style, but the actual Column object. I don't think the data grids play nicely when sharing like that; I think you'll get an exception to the extent of "This UIElement is already the child of another UIElement". So I tried the following...slightly different than what you're talking about. but I got this exception: {"DataGridColumn with Header '' already exists in the Columns collection of a DataGrid. DataGrids cannot share columns and cannot contain duplicate column instances.\r\nParameter name: item"} with this XAML: ``` <Grid.Resources> <DataGridTextColumn x:Key="MyColumn" /> </Grid.Resources> <DataGrid> <DataGrid.Columns> <StaticResource ResourceKey="MyColumn" /> </DataGrid.Columns> </DataGrid> <DataGrid> <DataGrid.Columns> <StaticResource ResourceKey="MyColumn" /> </DataGrid.Columns> </DataGrid> ```
5,716,123
Is it possible to declare `DataGrid` columns in a style or as a resource? I would like to do something like this: ``` <....Resources> <DataGridColumns x:Key="dgcDataGridColumns"> <DataGridTextColumn /> <DataGridTextColumn /> </DataGridColumns </....Resources> <DataGrid Columns="{StaticResource dgcDataGridColumns}" /> ``` The reason is that i have to share the column definition for 4 different `DataGrids`. Any way to achieve this? Best would be without code behind!
2011/04/19
[ "https://Stackoverflow.com/questions/5716123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/613320/" ]
x:Shared helps to avoid the exception MattS423 has got. ``` <Window.Resources> <DataGridTextColumn x:Key="dgtcFirstName" x:Shared="False" Header="First Name" Binding="{Binding FirstName}"/> <DataGridTextColumn x:Key="dgtcSecondName" x:Shared="False" Header="Second Name" Binding="{Binding SecondName}"/> </Window.Resources> <Grid> <StackPanel> <DataGrid AutoGenerateColumns="False" Height="200" Name="dataGrid1" Width="200"> <DataGrid.Columns> <StaticResource ResourceKey="dgtcFirstName"/> <StaticResource ResourceKey="dgtcSecondName"/> </DataGrid.Columns> </DataGrid> <DataGrid AutoGenerateColumns="False" Height="200" Name="dataGrid2" Width="200"> <DataGrid.Columns> <StaticResource ResourceKey="dgtcSecondName"/> <StaticResource ResourceKey="dgtcFirstName"/> </DataGrid.Columns> </DataGrid> </StackPanel> </Grid> ```
I don't think you can, as in that situation you aren't specifying a template or a style, but the actual Column object. I don't think the data grids play nicely when sharing like that; I think you'll get an exception to the extent of "This UIElement is already the child of another UIElement". So I tried the following...slightly different than what you're talking about. but I got this exception: {"DataGridColumn with Header '' already exists in the Columns collection of a DataGrid. DataGrids cannot share columns and cannot contain duplicate column instances.\r\nParameter name: item"} with this XAML: ``` <Grid.Resources> <DataGridTextColumn x:Key="MyColumn" /> </Grid.Resources> <DataGrid> <DataGrid.Columns> <StaticResource ResourceKey="MyColumn" /> </DataGrid.Columns> </DataGrid> <DataGrid> <DataGrid.Columns> <StaticResource ResourceKey="MyColumn" /> </DataGrid.Columns> </DataGrid> ```
5,716,123
Is it possible to declare `DataGrid` columns in a style or as a resource? I would like to do something like this: ``` <....Resources> <DataGridColumns x:Key="dgcDataGridColumns"> <DataGridTextColumn /> <DataGridTextColumn /> </DataGridColumns </....Resources> <DataGrid Columns="{StaticResource dgcDataGridColumns}" /> ``` The reason is that i have to share the column definition for 4 different `DataGrids`. Any way to achieve this? Best would be without code behind!
2011/04/19
[ "https://Stackoverflow.com/questions/5716123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/613320/" ]
Columns property of the DataGrid has no setter so it is not possibly. You can however do something like this: ``` <Window.Resources> <Controls:DataGrid x:Key="PersonDataGrid" AutoGenerateColumns="False" ItemsSource="{Binding .}" x:Shared="False"> <Controls:DataGrid.Columns> <Controls:DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}" IsReadOnly="True"/> <Controls:DataGridTextColumn Header="Last Name" Binding="{Binding Path=LastName}" IsReadOnly="True"/> </Controls:DataGrid.Columns> </Controls:DataGrid> </Window.Resources> <StackPanel> <ContentControl Content="{StaticResource PersonDataGrid}" DataContext="{Binding Path=Customers}"></ContentControl> <ContentControl Content="{StaticResource PersonDataGrid}" DataContext="{Binding Path=Employees}"></ContentControl> </StackPanel> ```
x:Shared helps to avoid the exception MattS423 has got. ``` <Window.Resources> <DataGridTextColumn x:Key="dgtcFirstName" x:Shared="False" Header="First Name" Binding="{Binding FirstName}"/> <DataGridTextColumn x:Key="dgtcSecondName" x:Shared="False" Header="Second Name" Binding="{Binding SecondName}"/> </Window.Resources> <Grid> <StackPanel> <DataGrid AutoGenerateColumns="False" Height="200" Name="dataGrid1" Width="200"> <DataGrid.Columns> <StaticResource ResourceKey="dgtcFirstName"/> <StaticResource ResourceKey="dgtcSecondName"/> </DataGrid.Columns> </DataGrid> <DataGrid AutoGenerateColumns="False" Height="200" Name="dataGrid2" Width="200"> <DataGrid.Columns> <StaticResource ResourceKey="dgtcSecondName"/> <StaticResource ResourceKey="dgtcFirstName"/> </DataGrid.Columns> </DataGrid> </StackPanel> </Grid> ```
2,863,189
Suppose that $C$ and $B$ are $n \times p$ and $p \times n$, respectively, and that $A + BC$ and $A$ are full rank. Then why is $(I + CA^{-1}B)$ also full rank? I've tried to manipulate things around, and I wanted to show that $(I + CA^{-1}B)x = 0$ implies $x =0$. So far, all I can see is that if $(I + CA^{-1}B)x = 0$, then $(IB + BCA^{-1}B)x = 0$ and thus $(A + BC)(A^{-1}B)x = 0$, so $A^{-1}Bx = 0$ by the non singularity of $A + BC$, and hence $x \in \mathcal{N}(B)$. But that isn't good enough, since $B$ is not full rank.
2018/07/26
[ "https://math.stackexchange.com/questions/2863189", "https://math.stackexchange.com", "https://math.stackexchange.com/users/503984/" ]
If you consider using Newton method to find the zero of $$f(x)=x^3+x^2 (\text{Cb}+\text{Ka})-x (\text{Ca} \,\text{Ka}+\text{Kw})-\text{Ka} \, \text{Kw}$$ $$f'(x)=3 x^2+2 x (\text{Cb}+\text{Ka})-(\text{Ca} \text{Ka}+\text{Kw})$$ $$f''(x)=6 x+2 (\text{Cb}+\text{Ka})$$ you must not start at $x=0$ since $$f(0) \,f''(0)=-2\, \text{Ka} \,\text{Kw} \,(\text{Cb}+\text{Ka})<0$$ (think about Darboux-Fourier theorem). If you use $x\_0=0$, then the first iterate would be $$x\_1=-\frac{\text{Ka} \, \text{Kw}}{\text{Ca} \,\text{Ka}+\text{Kw}} <0$$ The first derivative cancels at $$x\_\*=\frac{1}{3} \left(\sqrt{(\text{Cb}+\text{Ka})^2+3 (\text{Ca}\, \text{Ka}+\text{Kw})}-(\text{Cb}+\text{Ka})\right) > 0$$ and the second derivative test shows that this is a minimum. In order to generate the starting point $x\_0$, perform around $x=x\_\*$ (were $f'(x\_\*)=0$), the Taylor expansion $$0=f(x\_\*)+\frac 12 f''(x\_\*)\,(x-x\_\*)^2+O((x-x\_\*)^3 ) \implies x\_0=x\_\*+ \sqrt{-2\frac {f(x\_\*)}{f''(x\_\*)}}$$ Using your numbers, Newton iterates would be $$\left( \begin{array}{cc} n & x\_n \\ 0 & \color{blue}{8.8902}609452502354578 \times 10^{-6}\\ 1 & \color{blue}{8.89021155}71665711819 \times 10^{-6}\\ 2 & \color{blue}{8.8902115568921917511} \times 10^{-6} \end{array} \right)$$ This is a very reliable procedure. **Edit** I am *almost* sure that we could even skip the Newton procedure using a $[1,2]$ Padé approximant built around $x\_1$. This would give $$x\_1=x\_0+\frac 12\frac{ f(x\_0) \left(f(x\_0)\, f''(x\_0)-2\, f'(x\_0)^2\right)}{f(x\_0)^2 +f'(x\_0)^3- f(x\_0)\,f'(x\_0)\, f''(x\_0)}$$ For the worked example, this would give $x\_2=\color{blue}{8.890211556892191751}2 \times 10^{-6}$
According to the [computation on Wolfram Alpha](http://www.wolframalpha.com/input/?i=solve+x%5E3+%2B+(0.2%2B1e-4.75)*x%5E2++-(0.1*1e-4.75+%2B+1e-14)*x+%E2%88%921e-4.75*1e-14+%3D+0) linked in the question, the task is to find the roots of the cubic equation $x^{3} + (0.2 + 1 \times 10^{-4.75})x^{2}-(0.1 \times 10^{-4.75} + 1 \times 10^{-14})x - (1 \times 10^{-4.75} \times 1 \times 10^{-14})$ If this is representative of the cubic equations that need to be solved, there seems to be no problem in tackling this with IEEE-754 double precision computation and a standard solver, such as Kahan's `QBC` solver: William Kahan, "To Solve a Real Cubic Equation". Lecture notes, UC Berkeley, Nov. 1986 ([online](https://cs.berkeley.edu/~wkahan/Math128/Cubic.pdf)) I am using Kahan's code pretty much verbatim, but have enhanced it in various places by the use of the FMA (fused multiply-add) operation which is readily accessible from C++ as the standard math function `fma()`. I specified the coefficients as follows: ``` double a3 = 1.0; double a2 = 0.2 + exp10 (-4.75); double a1 = -(0.1 * exp10 (-4.75) + exp10 (-14.0)); double a0 = -(exp10 (-4.75) * exp10 (-14.0)); ``` The results returned by the `QBC` solver are: ``` -2.0002667300555729e-001 -9.9999998312876059e-014 + i * 0.0000000000000000e+000 8.8902115568921925e-006 + i * 0.0000000000000000e+000 ``` These match the results computed by Wolfram Alpha: $-0.200027, -1.\times10^{-13}, 8.89021\times10^{-6}$
29,349,014
I have an array in PHP that I encode to json: ``` $jsonOutput = json_encode($output); ``` Then in my javascript, I use this to parse it: ``` var jsonOutput = JSON.parse('<?php echo $jsonOutput; ?>'); ``` My output looks like this in the Chrome console: ![enter image description here](https://i.stack.imgur.com/FqyD7.png) Ultimately, I have two arrays, and I'm trying to write a compare between the two to show if there are any items in the first array that aren't in the second, but I'm not sure how to reference `red` and `orange` here. I tried `console.log(jsonOutput[0])` but I get `undefined`. Also, as a side note, does anyone have any good resources for reading up on arrays in javascript and all their ins-and-outs? It seems to be one aspect that I'm struggling with lately...
2015/03/30
[ "https://Stackoverflow.com/questions/29349014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4316726/" ]
The problem is that your jsonOutput is an Object, so in order to access one member of the object you either have to user jsonOutput.red/jsonOutput.orange or jsonOutput["red"], jsonOutput["orange"] to access a member of the object. More info here [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json).
``` jsonOutput.red[0] ``` You have an object with two keys. Not an array.
29,349,014
I have an array in PHP that I encode to json: ``` $jsonOutput = json_encode($output); ``` Then in my javascript, I use this to parse it: ``` var jsonOutput = JSON.parse('<?php echo $jsonOutput; ?>'); ``` My output looks like this in the Chrome console: ![enter image description here](https://i.stack.imgur.com/FqyD7.png) Ultimately, I have two arrays, and I'm trying to write a compare between the two to show if there are any items in the first array that aren't in the second, but I'm not sure how to reference `red` and `orange` here. I tried `console.log(jsonOutput[0])` but I get `undefined`. Also, as a side note, does anyone have any good resources for reading up on arrays in javascript and all their ins-and-outs? It seems to be one aspect that I'm struggling with lately...
2015/03/30
[ "https://Stackoverflow.com/questions/29349014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4316726/" ]
The problem is that your jsonOutput is an Object, so in order to access one member of the object you either have to user jsonOutput.red/jsonOutput.orange or jsonOutput["red"], jsonOutput["orange"] to access a member of the object. More info here [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json).
You access those arrays using: ``` jsonOutput.red; jsonOutput.orange; ```
2,505,484
I saw in a lot of AjaxControlToolkit.resources.dll for different languages, even mine (Russian) in my bin folder so I guess that's real to change the language of my Ajax Calendar Extender. ``` <asp:TextBox ID="TextBox4" runat="server" oninit="TextBox4_Init" /> <ajaxToolkit:CalendarExtender ID="TextBox4_CalendarExtender" runat="server" Enabled="True" FirstDayOfWeek="Monday" Format="dd.MM.yyyy" TargetControlID="TextBox4" /> <br /> ``` It's English by default But how can I change it to my Language ? (or to the current culture language) I've tried ``` <%@ Page Title="gfregrhtrhr" Language="Nemerle" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="Report.aspx.n" Inherits="Flow_WEB_Nemerle.Report" Culture="ru-RU" UICulture="ru-RU" %> ``` but it made no sense for calendar :-/ by the way I have some fun in comparing my page and <http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/Calendar/Calendar.aspx> there I can see month names etc on Russian BUT "Today" an english >\_< instead on my page month names are English and "Today" is Russian "Сегодня" ... is it phenomenon Finally fixed by adding ``` <asp:ScriptManager ID="ScriptManager1" runat="server" EnableScriptGlobalization="true" EnableScriptLocalization="true"/> ```
2010/03/24
[ "https://Stackoverflow.com/questions/2505484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238232/" ]
The components are going to work by default in the language defined in the page culture property in your page directive. This directive also fix the date format and all the culture relative parameters and preferences. This is an example to set them work for English-United Kingdom: ``` <%@ Page Language="C#" Culture="en-UK" UICulture="en-UK" %> ```
You must set EnableScriptGlobalization="true" in ToolkitScriptManager like this ``` <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnableScriptGlobalization="True"></asp:ToolkitScriptManager> ```
33,612,097
I have recently started to work with MySQL for my study job and now face following problem: My predecessor created a textmining table of the following structure: ``` +------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+-------+ | TokenId | int(11) | NO | PRI | 0 | | | Value | varchar(255) | YES | | NULL | | | Frequency | int(11) | YES | | NULL | | | PMID | int(11) | YES | MUL | NULL | | +------------+--------------+------+-----+---------+-------+ ``` In the context of restructuring, I added the following column: ``` +------------+--------------+------+-----+---------+-------+ | NewTokenId | int(11) | YES | | NULL | | +------------+--------------+------+-----+---------+-------+ ``` If I now run the query: ``` insert into TitleToken(NewTokenId) select t.TokenId from Token as t, TitleToken as tt where t.Value = tt.Value ``` or even the query: ``` insert into TitleToken(NewTokenId) values(1); ``` I get following output: > > ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY' > > > As I said, I am relatively new to (hands-on) \*SQL and it feels like a stupid mistake, but since the column NewTokenId is no primary key, not unique and even Null is YES, I thought I'd be able to insert basically anything I want. Any hint would be appreciated... thanks in advance :)
2015/11/09
[ "https://Stackoverflow.com/questions/33612097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5542712/" ]
You're missing a semi-colon after the following: ``` chomp $choice ``` Keep in mind that the following is a valid statement: ``` chomp $choice if ($choice = "Ruby") ``` --- By the way, ``` $choice = "Ruby" ``` should be ``` $choice eq "Ruby" ``` `=` is the scalar assignment or list assignment operator. `==` is the numerical comparison operator. `eq` is the string comparison operator.
You are missing a `;` after the line `chomp $choice` Always include `use strict;` and `use warnings;` in your scripts.
100,195
Ahlfors says that once the existence of the quotient $\frac{a}{b}$ has been proven, its value can be found by calculating $\frac{a}{b} \cdot \frac{\bar b}{\bar b}$. Why doesn't this manipulation show the existence of the quotient? $\frac{a}{b} = \frac{a}{b} \cdot \frac{\bar b}{\bar b} = a\bar b \cdot b^{-1} \cdot\bar b^{-1} = a\bar b \cdot (b\bar b)^{-1}$, the last term clearly exists since the thing being inversed is real.
2012/01/18
[ "https://math.stackexchange.com/questions/100195", "https://math.stackexchange.com", "https://math.stackexchange.com/users/19192/" ]
I will consider the case when $X\_1$ and $X\_2$ are *independent identically distributed* and integer-valued. The following properites hold: 1. Since $Y$ is discrete with finite support, its pmf is a polynomial in $z$ and $z^{-1}$ with non-negative coefficients. $$ Z\_Y(z) = \sum\_{k=m(Y)}^{n(Y)} \mathbb{P}(Y=k) z^k $$ 2. Let $X$ be the purported solution with $Z\_X(z) = \sum\_{k=m(X)}^{n(X)} \mathbb{P}(X=k) z^k$. 3. Since $Y = X\_1-X\_2$, for $X\_1$, $X\_2$ iids, $Z\_Y(z) = Z\_{X}(z) Z\_{X}(z^{-1})$. The problem you are posing is whether, given $Z\_Y(z)$ one can determine $Z\_X(z)$ such that $Z\_Y(z) = Z\_X(z) Z\_X(z^{-1})$. Observe that the solution, if exists, is not unique, since $Z\_{X^\prime}(z) = z^k Z\_{X}(z)$ would also be a solution for arbitrary $k \in \mathbb{Z}$. The necessary condition for existence of a solution is that $Z\_Y(z)$ should verify $Z\_{Y}(z) = Z\_Y(z^{-1})$. Assuming that the given $Z\_Y(z)$ satisfies this property, finding $Z\_X(z)$ reduces to polynomial factorization.
No. If $X\_1$ and $X\_2$ are identically equal to any constant, then $Y$ is identically equal to zero.
100,195
Ahlfors says that once the existence of the quotient $\frac{a}{b}$ has been proven, its value can be found by calculating $\frac{a}{b} \cdot \frac{\bar b}{\bar b}$. Why doesn't this manipulation show the existence of the quotient? $\frac{a}{b} = \frac{a}{b} \cdot \frac{\bar b}{\bar b} = a\bar b \cdot b^{-1} \cdot\bar b^{-1} = a\bar b \cdot (b\bar b)^{-1}$, the last term clearly exists since the thing being inversed is real.
2012/01/18
[ "https://math.stackexchange.com/questions/100195", "https://math.stackexchange.com", "https://math.stackexchange.com/users/19192/" ]
I will consider the case when $X\_1$ and $X\_2$ are *independent identically distributed* and integer-valued. The following properites hold: 1. Since $Y$ is discrete with finite support, its pmf is a polynomial in $z$ and $z^{-1}$ with non-negative coefficients. $$ Z\_Y(z) = \sum\_{k=m(Y)}^{n(Y)} \mathbb{P}(Y=k) z^k $$ 2. Let $X$ be the purported solution with $Z\_X(z) = \sum\_{k=m(X)}^{n(X)} \mathbb{P}(X=k) z^k$. 3. Since $Y = X\_1-X\_2$, for $X\_1$, $X\_2$ iids, $Z\_Y(z) = Z\_{X}(z) Z\_{X}(z^{-1})$. The problem you are posing is whether, given $Z\_Y(z)$ one can determine $Z\_X(z)$ such that $Z\_Y(z) = Z\_X(z) Z\_X(z^{-1})$. Observe that the solution, if exists, is not unique, since $Z\_{X^\prime}(z) = z^k Z\_{X}(z)$ would also be a solution for arbitrary $k \in \mathbb{Z}$. The necessary condition for existence of a solution is that $Z\_Y(z)$ should verify $Z\_{Y}(z) = Z\_Y(z^{-1})$. Assuming that the given $Z\_Y(z)$ satisfies this property, finding $Z\_X(z)$ reduces to polynomial factorization.
**The answer below is no longer relevant since the OP now says that $X\_1$ and $X\_2$ take on strictly positive integer values and are also independent.** --- If you don't like Byron Schmuland's answer with degenerate random variables, here is an example with Bernoulli random variables showing that the information you have is insufficient to determine the identical marginal distributions of $X\_1$ and $X\_2$. More information about the joint distribution is needed. Let $Y$ have pmf $p\_Y(-1) = p\_Y(+1) = 0.2, p\_Y(0) = 0.6$. $X\_1$ and $X\_2$ thus are Bernoulli random variables. The two joint distributions shown below are consistent with $Y$. Both give rise to identical marginal distributions for $X\_1$ and $X\_2$, but the marginal distributions are different in the two cases: $$p(0,1) = p(1,0) = 0.2; p(0,0) = p(1,1) = 0.3; \Rightarrow X\_1, X\_2 \sim \text{Bernoulli}(0.5)$$ $$p(0,1) = p(1,0) = 0.2; p(0,0) = 2p(1,1) = 0.4; \Rightarrow X\_1, X\_2 \sim \text{Bernoulli}(0.4)$$ In fact, for the given pmf of $Y$, we can choose to make $X\_1, X\_2 \sim \text{Bernoulli}(p)$ for any $p \in [0.2,0.8]$.
46,255,248
I want to retrieve the value of an input using jQuery. Here's the HTML: ``` <input type="text" name="a" id="a" /> <input type="button" name="b" id="b" value="Click here"/> ``` Here's the jQuery: ``` $(document).ready(function() { var normal=$('#a').val(); $('#b').on("click", function() { alert(normal); }); }); ``` Due to some reason the `alert(normal);` does not work whereas `alert($('#a').val());` does. Why? Isn't `normal` and `$('#a').val();` holding the same value? In case you want a jsfiddle: <http://jsfiddle.net/L2uX4/20/> Thanks
2017/09/16
[ "https://Stackoverflow.com/questions/46255248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8312107/" ]
You're assigning `normal` upon `document.ready()` and not reassigning when you click, so normal will be whatever value you give to the input field when the page loads.
Try this code ``` $(document).ready(function() { $('#b').on("click", function() { var normal=$('#a').val(); alert(normal); }); }); ```
46,255,248
I want to retrieve the value of an input using jQuery. Here's the HTML: ``` <input type="text" name="a" id="a" /> <input type="button" name="b" id="b" value="Click here"/> ``` Here's the jQuery: ``` $(document).ready(function() { var normal=$('#a').val(); $('#b').on("click", function() { alert(normal); }); }); ``` Due to some reason the `alert(normal);` does not work whereas `alert($('#a').val());` does. Why? Isn't `normal` and `$('#a').val();` holding the same value? In case you want a jsfiddle: <http://jsfiddle.net/L2uX4/20/> Thanks
2017/09/16
[ "https://Stackoverflow.com/questions/46255248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8312107/" ]
if you declare `var normal` outside the click function handler then the initial value will be empty as there is no value in the text box once the DOM is ready . But if you declare it within the `click` event handler then the value will be assigned once you type something in the textbox and click the button. The below code works for me ```js $(document).ready(function() { $('#b').on("click", function() { var normal= $('#a').val(); alert(normal); // same as alert($('#a').val()); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="a" id="a" /> <input type="button" name="b" id="b" value="Click here"/> ```
You're assigning `normal` upon `document.ready()` and not reassigning when you click, so normal will be whatever value you give to the input field when the page loads.
46,255,248
I want to retrieve the value of an input using jQuery. Here's the HTML: ``` <input type="text" name="a" id="a" /> <input type="button" name="b" id="b" value="Click here"/> ``` Here's the jQuery: ``` $(document).ready(function() { var normal=$('#a').val(); $('#b').on("click", function() { alert(normal); }); }); ``` Due to some reason the `alert(normal);` does not work whereas `alert($('#a').val());` does. Why? Isn't `normal` and `$('#a').val();` holding the same value? In case you want a jsfiddle: <http://jsfiddle.net/L2uX4/20/> Thanks
2017/09/16
[ "https://Stackoverflow.com/questions/46255248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8312107/" ]
You're assigning `normal` upon `document.ready()` and not reassigning when you click, so normal will be whatever value you give to the input field when the page loads.
Yes, you are right, > > provided the text box with `id= a` had some text on load. > > > by that I mean something along the lines of ``` <input type="text" name="a" id="a" value= "foo"/> ``` Fiddle: <http://jsfiddle.net/Jayas/vhjm8v31/2/> Now if you hit `Clickhere` button it will display `foo`. **In your case** 1. When you assign the value of `a` to `normal` the text box is empty. 2. You dont have any handlers or events hooked up to reset/set the variable `normal`on something being typed or after something has got typed in. by that I mean something along the lines of having the value stored on `input change` along the lines of ``` $(document).ready(function(){ $('#a').bind('input propertychange', function() { normal = $('#a').val(); } }) ``` **Fiddle** <http://jsfiddle.net/Jayas/vhjm8v31/4/> > > tl:dr - rebinding of the text to the declared variable does not "automagically" happen > > > So now when you click on the button after reassigning `normal` you will see the typed value. or alternatively you can capture the value of normal on click event as you already have it , along the lines of ``` $('#b').on("click", function() { var normal = $('#a').val(); alert(normal); }); ```
46,255,248
I want to retrieve the value of an input using jQuery. Here's the HTML: ``` <input type="text" name="a" id="a" /> <input type="button" name="b" id="b" value="Click here"/> ``` Here's the jQuery: ``` $(document).ready(function() { var normal=$('#a').val(); $('#b').on("click", function() { alert(normal); }); }); ``` Due to some reason the `alert(normal);` does not work whereas `alert($('#a').val());` does. Why? Isn't `normal` and `$('#a').val();` holding the same value? In case you want a jsfiddle: <http://jsfiddle.net/L2uX4/20/> Thanks
2017/09/16
[ "https://Stackoverflow.com/questions/46255248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8312107/" ]
if you declare `var normal` outside the click function handler then the initial value will be empty as there is no value in the text box once the DOM is ready . But if you declare it within the `click` event handler then the value will be assigned once you type something in the textbox and click the button. The below code works for me ```js $(document).ready(function() { $('#b').on("click", function() { var normal= $('#a').val(); alert(normal); // same as alert($('#a').val()); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="a" id="a" /> <input type="button" name="b" id="b" value="Click here"/> ```
Try this code ``` $(document).ready(function() { $('#b').on("click", function() { var normal=$('#a').val(); alert(normal); }); }); ```
46,255,248
I want to retrieve the value of an input using jQuery. Here's the HTML: ``` <input type="text" name="a" id="a" /> <input type="button" name="b" id="b" value="Click here"/> ``` Here's the jQuery: ``` $(document).ready(function() { var normal=$('#a').val(); $('#b').on("click", function() { alert(normal); }); }); ``` Due to some reason the `alert(normal);` does not work whereas `alert($('#a').val());` does. Why? Isn't `normal` and `$('#a').val();` holding the same value? In case you want a jsfiddle: <http://jsfiddle.net/L2uX4/20/> Thanks
2017/09/16
[ "https://Stackoverflow.com/questions/46255248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8312107/" ]
if you declare `var normal` outside the click function handler then the initial value will be empty as there is no value in the text box once the DOM is ready . But if you declare it within the `click` event handler then the value will be assigned once you type something in the textbox and click the button. The below code works for me ```js $(document).ready(function() { $('#b').on("click", function() { var normal= $('#a').val(); alert(normal); // same as alert($('#a').val()); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="a" id="a" /> <input type="button" name="b" id="b" value="Click here"/> ```
Yes, you are right, > > provided the text box with `id= a` had some text on load. > > > by that I mean something along the lines of ``` <input type="text" name="a" id="a" value= "foo"/> ``` Fiddle: <http://jsfiddle.net/Jayas/vhjm8v31/2/> Now if you hit `Clickhere` button it will display `foo`. **In your case** 1. When you assign the value of `a` to `normal` the text box is empty. 2. You dont have any handlers or events hooked up to reset/set the variable `normal`on something being typed or after something has got typed in. by that I mean something along the lines of having the value stored on `input change` along the lines of ``` $(document).ready(function(){ $('#a').bind('input propertychange', function() { normal = $('#a').val(); } }) ``` **Fiddle** <http://jsfiddle.net/Jayas/vhjm8v31/4/> > > tl:dr - rebinding of the text to the declared variable does not "automagically" happen > > > So now when you click on the button after reassigning `normal` you will see the typed value. or alternatively you can capture the value of normal on click event as you already have it , along the lines of ``` $('#b').on("click", function() { var normal = $('#a').val(); alert(normal); }); ```
56,275
This question arose from considering for a connected smooth Hausdorff manifold the (possible) equivalence of the following properties: (1) paracompact, (2) metrizable, (3) second countable, (4) countable at infinity, (5) $\sigma$−compact, (6) Lindelöf, (7) separable. I know proofs for the equivalence of the first six, and that they imply (7), but it is problematic, whether this implies the others. By *countable at infinity* I mean existence of a sequence of compact sets $K\_i$ whose union covers the space and which satisfies $K\_i\subseteq{\rm Int\ }K\_{i+1}$ . Of course, *locally euclidean* means that each point has a neighbourhood homeomorphic to $\mathbb R^k$ with the standard topology and $k\in\mathbb N$ .
2011/02/22
[ "https://mathoverflow.net/questions/56275", "https://mathoverflow.net", "https://mathoverflow.net/users/12643/" ]
I answer my our question: *Separability of a connected locally euclidean Hausdorff topological space **does not** imply second countability*, or any of the equivalent conditions (1), ... (6) given in the question. A counterexample is given in Example 5 on page 15 in [David Gauld's preprint](http://arxiv.org/PS_cache/arxiv/pdf/0910/0910.0885v1.pdf). There is constructed a separable Hausdorff topological space, which is not second countable. The space can be equipped with a compatible **analytic** atlas modelled on $\mathbb R^2$ . One such is $\lbrace{\rm id\ }S\rbrace\cup\lbrace\phi\_{\eta,\zeta}:\eta,\zeta\in\mathbb R\rbrace$ , where $\phi\_{\eta,\zeta}$ is given by $(0,\eta,z)\mapsto(0,z-\zeta)=(0,v)$ when $|v|<1$ , and $(x,y)\mapsto(x,|x|^{-1}(y-\eta)-\zeta)=(u,v)$ when $0<|x|<1$ and $|v|<1$ . So Gauld's space **does not** satisfy any of the conditions (1), ... (6).
Indeed, check [the paper by Gauld](http://arxiv.org/pdf/0910.0885v1). Your (4) implies his condition hemicompact. His example at p15, that you saw refutes the just separable condition (7). Note that (1)-(6) imply imply metrisability for just continuous manifolds, so it still might be that the situation vis à vis separability is different for **smooth** manifolds instead of continuous ones, though I suspect not.
56,275
This question arose from considering for a connected smooth Hausdorff manifold the (possible) equivalence of the following properties: (1) paracompact, (2) metrizable, (3) second countable, (4) countable at infinity, (5) $\sigma$−compact, (6) Lindelöf, (7) separable. I know proofs for the equivalence of the first six, and that they imply (7), but it is problematic, whether this implies the others. By *countable at infinity* I mean existence of a sequence of compact sets $K\_i$ whose union covers the space and which satisfies $K\_i\subseteq{\rm Int\ }K\_{i+1}$ . Of course, *locally euclidean* means that each point has a neighbourhood homeomorphic to $\mathbb R^k$ with the standard topology and $k\in\mathbb N$ .
2011/02/22
[ "https://mathoverflow.net/questions/56275", "https://mathoverflow.net", "https://mathoverflow.net/users/12643/" ]
I answer my our question: *Separability of a connected locally euclidean Hausdorff topological space **does not** imply second countability*, or any of the equivalent conditions (1), ... (6) given in the question. A counterexample is given in Example 5 on page 15 in [David Gauld's preprint](http://arxiv.org/PS_cache/arxiv/pdf/0910/0910.0885v1.pdf). There is constructed a separable Hausdorff topological space, which is not second countable. The space can be equipped with a compatible **analytic** atlas modelled on $\mathbb R^2$ . One such is $\lbrace{\rm id\ }S\rbrace\cup\lbrace\phi\_{\eta,\zeta}:\eta,\zeta\in\mathbb R\rbrace$ , where $\phi\_{\eta,\zeta}$ is given by $(0,\eta,z)\mapsto(0,z-\zeta)=(0,v)$ when $|v|<1$ , and $(x,y)\mapsto(x,|x|^{-1}(y-\eta)-\zeta)=(u,v)$ when $0<|x|<1$ and $|v|<1$ . So Gauld's space **does not** satisfy any of the conditions (1), ... (6).
See my article on nonmetrizable manifolds in the Handbook of Set-Theoretic Topology. Examples 3.7 and 3.9 include separable, nonmetrizable manifolds; neither is due to me and the second is due to R.L. Moore in a 1942 paper. After reading the descriptions, you might try going back to Gauld's smooth example.
46,213,500
I want to make a Back to top button like the page below <https://www.k-kosho.co.jp/> As the scroll button will be hidden, only show again when I stop the scroll. This is my start js, hope everyone helps. ``` $(window).scroll(function() { if ($(this).scrollTop() != 0) { $('.ev-scrolltop').fadeIn(); } else { $('.ev-scrolltop').fadeOut(); } }); ``` Thank you everyone!
2017/09/14
[ "https://Stackoverflow.com/questions/46213500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6772972/" ]
You could use [*`get_level_values`*](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html): ``` df[df.val >= 3].index.get_level_values(1).unique() Index(['var', 'rf', 'uf'], dtype='object') ```
You need [`remove_unused_levels`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.remove_unused_levels.html), `new in version 0.20.0.`: ``` df1 = df[df.val >= 3] print (df1.index) MultiIndex(levels=[['Rad', 'Tan'], ['max', 'min', 'rf', 'uf', 'var']], labels=[[1, 1, 1, 0, 0, 0], [4, 2, 3, 4, 2, 3]]) df1.index = df1.index.remove_unused_levels() print (df1.index) MultiIndex(levels=[['Rad', 'Tan'], ['var', 'rf', 'uf']], labels=[[1, 1, 1, 0, 0, 0], [0, 1, 2, 0, 1, 2]]) print (df1.index.levels[1]) Index(['var', 'rf', 'uf'], dtype='object') ```
98,320
Thunderwave, on a failed save, pushes a target 10 feet when it hits them in addition to doing damage. In the event that a party as a whole were falling, a creative Cleric could Ready his spell to be cast when they're about to hit the ground, by Thunderwaving the other member's of the party, directly, 10 feet in the opposite direction. Since physics aren't really a thing in D&D, would this theoretically counter the fall damage by negating all forward momentum and setting it back to zero? I understand they'll likely still take at least 10 feet of fall damage, but that's not what I'm mainly curious about.
2017/04/18
[ "https://rpg.stackexchange.com/questions/98320", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/23110/" ]
This method nets you more damage ================================ Falling damage is dealt *at the end of a fall*. > > **PHB 183, Falling** > > > At the end of a fall, a creature takes 1d6 bludgeoning damage for every 10 feet it fell, to a maximum of 20d6. The creature lands prone, unless it avoids taking damage from the fall. > > > So in order for Thunderwave to stop you from taking this damage, it has to *end the fall first* and then begin a new one, wherein you fall at a height of 15 ft or less. Furthermore, it must end the fall without dealing damage to you. If you are falling and then are subjected to Thunderwave such that your fall stops and is reversed (ie, you are tossed upwards), you should take falling damage then. And now you begin a new fall from your new height. For example: you fell from a height of 100 ft. After falling 90 ft, your Cleric (who is on the ground, right at the spot you are going to land on) casts Thunderwave, sending you back 15 ft upwards. Then, your fall must have ended at the moment you were 10 ft away from the ground when you were hit by Thunderwave. You take 9d6 + 2d8 damage for this. Then you begin a new fall from a height of 25 ft (the 10 ft you were at, plus the 15 ft from TW), dealing you another 2d6 damage when you land. All in all, this nets you extra damage equal to 1d6 bludgeoning, for the extra 15 ft fall, and 2d8 thunder, from the Thunderwave. --- Response to Objections: ======================= 1. **Thunderwave causes forced movement, and forced movement doesn't trigger damage effects. Is there a rule that Thunderwave must trigger the damage?** * A spell does only what it states it does. Thunderwave does not say it prevents falling damage. Moreover, the saying goes "It's not the fall that hurts you; it’s the sudden stop" which I feel is applicable here. The rules for taking falling damage state that you take damage "at the end of the fall." If Thunderwave causes your fall to end, then you must take damage. * There is no rule that says forced movement *never* triggers damage. 2. **Is there a rule that the falling counter isn't reset once pushed back up? Take Feather Fall -- you don't take fall damage by just waiting to cast it.** * There are no rules about "resetting the counter of fall damage"; however, Feather Fall specifically negates fall damage. 3. **So going by (2), then if you cast Fly on yourself while mid fall, do you take damage because your fall ended?** * *PHB 191, Flying Movement* seems to suggest that if you are held aloft by magic, you are not considered falling. A non-falling creature does not take Fall damage. See [this answer](https://rpg.stackexchange.com/a/98347/27327) which discusses this specific objection in more depth. 4. **"At the end of the a fall... the creature lands prone..." Thus the fall ends when the creature lands. That is not to say that the creature didn't fall 100', but that the thunderwave doesn't itself precipitate falling damage** * These are two separate sentences with independent thoughts. More accurately, it's "At the end of the fall, you take damage equal to X" and "If you take damage after falling, you land prone." If Thunderwave causes the fall to end, damage is still taken. But landing becomes inapplicable as you do not land when hit by TW in this way.
This is mostly likely a DM Discretion issue, but what follows is some guidance: In order for Thunderwave to successfully push you 10' away from the ground, the Cleric would need to have done the following: 1. Depending on initiative order at the time of falling, there may not have been an opportunity to ready the action. For the sake of this discussion - there was sufficient time. 2. Cleric would need to fall first and be 'below' the party. This would allow him to "push" his party 10' up prior to hitting the ground. 3. The party would need to be directly above and in range of the Cleric. [Your mileage may vary on how you interpret in range.](https://rpg.stackexchange.com/questions/48998/is-thunderwave-centered-on-the-caster) 4. All party members would still have to make the save against it and take the 3d8 Thunder Damage (either full or half depending on save state.)Further discussion on saving throws can be found [here](https://rpg.stackexchange.com/questions/47487/can-you-choose-to-fail-a-saving-throw). If those conditions are met, then the question arises as to what happens. The cleric would of course hit the ground with regular falling damage. The party, after falling X feet, would now be pushed back up, only to fall back down final 10 feet to the ground. From a pure calculation point, you have the original X distance, then they are pushed back up 10', only to fall again. The original fall is still occurring, but you have moved sent them back up 10' in order to fall. It is unknown if falling damage is based purely on distance, or on an assumption of speed/momentum. However, given that the falling damage is calculated purely on distance, you have still falling the full distance, plus an additional 10' AND the thunder damage. However - I think there is a case for saying the push 'resets' the falling meter and it's only 10 feet that they have fallen (if you timed it right after you hit the ground, but before your party does.) This basically turns a Readied Thunderwave into a bit of a Featherfall. For a level One spell slot, I think this is reasonable as long as the first four conditions I listed are met.
98,320
Thunderwave, on a failed save, pushes a target 10 feet when it hits them in addition to doing damage. In the event that a party as a whole were falling, a creative Cleric could Ready his spell to be cast when they're about to hit the ground, by Thunderwaving the other member's of the party, directly, 10 feet in the opposite direction. Since physics aren't really a thing in D&D, would this theoretically counter the fall damage by negating all forward momentum and setting it back to zero? I understand they'll likely still take at least 10 feet of fall damage, but that's not what I'm mainly curious about.
2017/04/18
[ "https://rpg.stackexchange.com/questions/98320", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/23110/" ]
This method nets you more damage ================================ Falling damage is dealt *at the end of a fall*. > > **PHB 183, Falling** > > > At the end of a fall, a creature takes 1d6 bludgeoning damage for every 10 feet it fell, to a maximum of 20d6. The creature lands prone, unless it avoids taking damage from the fall. > > > So in order for Thunderwave to stop you from taking this damage, it has to *end the fall first* and then begin a new one, wherein you fall at a height of 15 ft or less. Furthermore, it must end the fall without dealing damage to you. If you are falling and then are subjected to Thunderwave such that your fall stops and is reversed (ie, you are tossed upwards), you should take falling damage then. And now you begin a new fall from your new height. For example: you fell from a height of 100 ft. After falling 90 ft, your Cleric (who is on the ground, right at the spot you are going to land on) casts Thunderwave, sending you back 15 ft upwards. Then, your fall must have ended at the moment you were 10 ft away from the ground when you were hit by Thunderwave. You take 9d6 + 2d8 damage for this. Then you begin a new fall from a height of 25 ft (the 10 ft you were at, plus the 15 ft from TW), dealing you another 2d6 damage when you land. All in all, this nets you extra damage equal to 1d6 bludgeoning, for the extra 15 ft fall, and 2d8 thunder, from the Thunderwave. --- Response to Objections: ======================= 1. **Thunderwave causes forced movement, and forced movement doesn't trigger damage effects. Is there a rule that Thunderwave must trigger the damage?** * A spell does only what it states it does. Thunderwave does not say it prevents falling damage. Moreover, the saying goes "It's not the fall that hurts you; it’s the sudden stop" which I feel is applicable here. The rules for taking falling damage state that you take damage "at the end of the fall." If Thunderwave causes your fall to end, then you must take damage. * There is no rule that says forced movement *never* triggers damage. 2. **Is there a rule that the falling counter isn't reset once pushed back up? Take Feather Fall -- you don't take fall damage by just waiting to cast it.** * There are no rules about "resetting the counter of fall damage"; however, Feather Fall specifically negates fall damage. 3. **So going by (2), then if you cast Fly on yourself while mid fall, do you take damage because your fall ended?** * *PHB 191, Flying Movement* seems to suggest that if you are held aloft by magic, you are not considered falling. A non-falling creature does not take Fall damage. See [this answer](https://rpg.stackexchange.com/a/98347/27327) which discusses this specific objection in more depth. 4. **"At the end of the a fall... the creature lands prone..." Thus the fall ends when the creature lands. That is not to say that the creature didn't fall 100', but that the thunderwave doesn't itself precipitate falling damage** * These are two separate sentences with independent thoughts. More accurately, it's "At the end of the fall, you take damage equal to X" and "If you take damage after falling, you land prone." If Thunderwave causes the fall to end, damage is still taken. But landing becomes inapplicable as you do not land when hit by TW in this way.
The combo is outside the rules, and by strict RAW provides no benefit. However, many DM's might still desire to encourage roleplaying and creative thinking, and PHB p.193 states: > > When you describe an action not detailed elsewhere in the rules, the DM tells you whether that action is possible and what kind of roll you need to make, if any, to determine success or failure. > > > In this case, I might still allow the spell to provide a sonic cushion, reducing the fall damage for the party by 10' (possibly more if the caster rolled high on Arcana). Similarly, if a player asked - I might grant the same minor benefit for say, using a fireball when falling into ice (to melt the ice) or water (to create bubbles or even an updraft). It's generally more fun to say "*Yes, and*" to players (but with minor benefits that don't unbalance the system). At the very least, it can provide a narrative reason why a high HP PC survived a terminal velocity fall.
1,208,989
I have downloaded this file : ubuntu-18.04.3-desktop-amd64.iso to install Unbuntu on an old computer. After startup, I have had this message : This kernel requires an x86-64 CPU, but only detected an i686 CPU. Unable to boot - please use a kernel appropriate for your CPU. Is it related to my CPU capabilities ? May I install an 32 bits version ? If yes, is it possible to have Unity as 32 bits version ?
2020/02/08
[ "https://askubuntu.com/questions/1208989", "https://askubuntu.com", "https://askubuntu.com/users/1042250/" ]
The usual way is to sign up for a [DDNS service](https://en.wikipedia.org/wiki/Dynamic_DNS), with that service's application running on your home server. The DDNS service and application work together to update your public IP address (which means your *router's* IP address) to internet nameservers. So you use `ssh [email protected]`, and the nameserver provides the correct IP address for your router and LAN. * Several free DDNS services are available. Your favorite search engine will happily point you to several. * Many consumer routers have DDNS clients built-in, so you needn't install anything on your server. Check your router settings. * You must still set up *port forwarding* on your router to connect to the server on your LAN.
Idk if this will help you or can solve the exact problem on your case, but maybe can help the others, because i was searching for the same problem and found this method somewhere so, i've tried **Teamviewer**, here is the details * The server is Ubuntu Server 22.04, i installed the **Teamviewer Host**, you can find it [here](https://www.teamviewer.com/en/download/linux/) then scroll down to Teamviewer Host section, the reason why i'm using this because the page says *"TeamViewer Host is used for 24/7 access to remote computers"*, i'm not sure about the regular version if you asked, i haven't tested it yet, anyway you can follow this article to install and setup <https://community.teamviewer.com/English/kb/articles/4352-install-teamviewer-on-linux-without-graphical-user-interface> * The client is Teamviewer on Windows 11, you can download it [here](https://www.teamviewer.com/en/download/windows/), then login using the same account you use on the server (Teamviewer Host), then you should see your server listed under "Computers & Contacts", for more details can see this [screenshot](https://i.stack.imgur.com/sVtcD.png) here is the results when i can connect to my server: [screenshot](https://i.stack.imgur.com/jSBLP.png) Please take note that Teamviewer is free but for **non-commercial and personal use only**, at least for now, for the details or limitations or something else you can find it on their website <https://www.teamviewer.com/en/>
1,208,989
I have downloaded this file : ubuntu-18.04.3-desktop-amd64.iso to install Unbuntu on an old computer. After startup, I have had this message : This kernel requires an x86-64 CPU, but only detected an i686 CPU. Unable to boot - please use a kernel appropriate for your CPU. Is it related to my CPU capabilities ? May I install an 32 bits version ? If yes, is it possible to have Unity as 32 bits version ?
2020/02/08
[ "https://askubuntu.com/questions/1208989", "https://askubuntu.com", "https://askubuntu.com/users/1042250/" ]
The usual way is to sign up for a [DDNS service](https://en.wikipedia.org/wiki/Dynamic_DNS), with that service's application running on your home server. The DDNS service and application work together to update your public IP address (which means your *router's* IP address) to internet nameservers. So you use `ssh [email protected]`, and the nameserver provides the correct IP address for your router and LAN. * Several free DDNS services are available. Your favorite search engine will happily point you to several. * Many consumer routers have DDNS clients built-in, so you needn't install anything on your server. Check your router settings. * You must still set up *port forwarding* on your router to connect to the server on your LAN.
There is a service called <https://ngrok.com/> which allows you to set up temporary tunnels for various protocols. Basically, you'd open an SSH tunnel to the local SSH server on the host you want to connect into; this then exposes the tunnel to the public network. You obviously have to do this when you are connected locally, but after that, remote access should be possible. Their (brief) instructions for this are at <https://ngrok.com/docs/using-ngrok-with#ssh> Obviously, you have to be careful not to expose services which are not properly secured, or you will be having visitors.
267,918
We are currently using Office 2002 on Windows XP but will be moving our users to Windows 7 in the next few months. Part of our business is writing research documents so there is heavy use of Word (including an in-house bespoke templating add-in). The Windows 7 test user group have found that Word 2002 documents which contain tables/graphics can sometimes (but not always) display an annoying 'flicker' (especially if there are any drawing objects such as call-outs layered on top). This can be temporarily fixed by adjusting the zoom level in Word, but scrolling through the document will often cause the flicker to return. The intention is to upgrade Office once all users have migrated to Windows 7 but realistically this may not be for 9-12 months; whilst that would possibly remove the problem, the time scale is too far in the future for users to accept at present. Has anyone else come across a similar problem with Word 2002 on Windows 7 and/or found a solution to it?
2011/04/07
[ "https://superuser.com/questions/267918", "https://superuser.com", "https://superuser.com/users/59/" ]
According to the Windows 7 Compatibility Center, Office 2002 may not be compatible with Windows 7: <http://www.microsoft.com/windows/compatibility/windows-7/en-us/Details.aspx?type=Software&p=Microsoft%20Office%20XP%202002%20Standard&v=Microsoft&uid=10&l=en&pf=0&pi=0&s=office%202002&os=64-bit> You may have to upgrade to end the flicker.
From skimming the web it seems there's a fair number of people out there using Office 2002 with minimal problems on Windows 7 (most issues seem related to Outlook). I think it's going to be fairly natural of Microsoft to mark the compatibility status of such an old version of Office with the latest Windows as ambiguous; they have newer versions available. Someone had [a similar flickering problem with Word 2002](https://www.sevenforums.com/microsoft-office/106239-flickering-display-word-2002-a.html) and posted a solution that worked for them: > > In essence the document was created by > copy/pastes. The problem was that some > of the data overlapped the right > margins of the table/document and Word > did not know how to format it and > became locked. I solved it by copy > pasting a bit of the text at the time > to ensure it fit within the prescribed > table cells. > > >
267,918
We are currently using Office 2002 on Windows XP but will be moving our users to Windows 7 in the next few months. Part of our business is writing research documents so there is heavy use of Word (including an in-house bespoke templating add-in). The Windows 7 test user group have found that Word 2002 documents which contain tables/graphics can sometimes (but not always) display an annoying 'flicker' (especially if there are any drawing objects such as call-outs layered on top). This can be temporarily fixed by adjusting the zoom level in Word, but scrolling through the document will often cause the flicker to return. The intention is to upgrade Office once all users have migrated to Windows 7 but realistically this may not be for 9-12 months; whilst that would possibly remove the problem, the time scale is too far in the future for users to accept at present. Has anyone else come across a similar problem with Word 2002 on Windows 7 and/or found a solution to it?
2011/04/07
[ "https://superuser.com/questions/267918", "https://superuser.com", "https://superuser.com/users/59/" ]
I have seen a similar issue. We solved this by running Word in Compatibility mode, as also suggested by Randolph Potter in the comments above. What worked for us was to choose "Windows XP Service Pack 3". Here is an article from How To Geek on changing Compatibility mode: <http://www.howtogeek.com/howto/10436/using-program-compatibility-mode-in-windows-7/>
According to the Windows 7 Compatibility Center, Office 2002 may not be compatible with Windows 7: <http://www.microsoft.com/windows/compatibility/windows-7/en-us/Details.aspx?type=Software&p=Microsoft%20Office%20XP%202002%20Standard&v=Microsoft&uid=10&l=en&pf=0&pi=0&s=office%202002&os=64-bit> You may have to upgrade to end the flicker.
267,918
We are currently using Office 2002 on Windows XP but will be moving our users to Windows 7 in the next few months. Part of our business is writing research documents so there is heavy use of Word (including an in-house bespoke templating add-in). The Windows 7 test user group have found that Word 2002 documents which contain tables/graphics can sometimes (but not always) display an annoying 'flicker' (especially if there are any drawing objects such as call-outs layered on top). This can be temporarily fixed by adjusting the zoom level in Word, but scrolling through the document will often cause the flicker to return. The intention is to upgrade Office once all users have migrated to Windows 7 but realistically this may not be for 9-12 months; whilst that would possibly remove the problem, the time scale is too far in the future for users to accept at present. Has anyone else come across a similar problem with Word 2002 on Windows 7 and/or found a solution to it?
2011/04/07
[ "https://superuser.com/questions/267918", "https://superuser.com", "https://superuser.com/users/59/" ]
I have seen a similar issue. We solved this by running Word in Compatibility mode, as also suggested by Randolph Potter in the comments above. What worked for us was to choose "Windows XP Service Pack 3". Here is an article from How To Geek on changing Compatibility mode: <http://www.howtogeek.com/howto/10436/using-program-compatibility-mode-in-windows-7/>
From skimming the web it seems there's a fair number of people out there using Office 2002 with minimal problems on Windows 7 (most issues seem related to Outlook). I think it's going to be fairly natural of Microsoft to mark the compatibility status of such an old version of Office with the latest Windows as ambiguous; they have newer versions available. Someone had [a similar flickering problem with Word 2002](https://www.sevenforums.com/microsoft-office/106239-flickering-display-word-2002-a.html) and posted a solution that worked for them: > > In essence the document was created by > copy/pastes. The problem was that some > of the data overlapped the right > margins of the table/document and Word > did not know how to format it and > became locked. I solved it by copy > pasting a bit of the text at the time > to ensure it fit within the prescribed > table cells. > > >
267,918
We are currently using Office 2002 on Windows XP but will be moving our users to Windows 7 in the next few months. Part of our business is writing research documents so there is heavy use of Word (including an in-house bespoke templating add-in). The Windows 7 test user group have found that Word 2002 documents which contain tables/graphics can sometimes (but not always) display an annoying 'flicker' (especially if there are any drawing objects such as call-outs layered on top). This can be temporarily fixed by adjusting the zoom level in Word, but scrolling through the document will often cause the flicker to return. The intention is to upgrade Office once all users have migrated to Windows 7 but realistically this may not be for 9-12 months; whilst that would possibly remove the problem, the time scale is too far in the future for users to accept at present. Has anyone else come across a similar problem with Word 2002 on Windows 7 and/or found a solution to it?
2011/04/07
[ "https://superuser.com/questions/267918", "https://superuser.com", "https://superuser.com/users/59/" ]
Run Microsoft Word in Compatibility Mode and choose an older version of Windows. This fixed the problem for me when running Office 2003 with Windows 8.
From skimming the web it seems there's a fair number of people out there using Office 2002 with minimal problems on Windows 7 (most issues seem related to Outlook). I think it's going to be fairly natural of Microsoft to mark the compatibility status of such an old version of Office with the latest Windows as ambiguous; they have newer versions available. Someone had [a similar flickering problem with Word 2002](https://www.sevenforums.com/microsoft-office/106239-flickering-display-word-2002-a.html) and posted a solution that worked for them: > > In essence the document was created by > copy/pastes. The problem was that some > of the data overlapped the right > margins of the table/document and Word > did not know how to format it and > became locked. I solved it by copy > pasting a bit of the text at the time > to ensure it fit within the prescribed > table cells. > > >
267,918
We are currently using Office 2002 on Windows XP but will be moving our users to Windows 7 in the next few months. Part of our business is writing research documents so there is heavy use of Word (including an in-house bespoke templating add-in). The Windows 7 test user group have found that Word 2002 documents which contain tables/graphics can sometimes (but not always) display an annoying 'flicker' (especially if there are any drawing objects such as call-outs layered on top). This can be temporarily fixed by adjusting the zoom level in Word, but scrolling through the document will often cause the flicker to return. The intention is to upgrade Office once all users have migrated to Windows 7 but realistically this may not be for 9-12 months; whilst that would possibly remove the problem, the time scale is too far in the future for users to accept at present. Has anyone else come across a similar problem with Word 2002 on Windows 7 and/or found a solution to it?
2011/04/07
[ "https://superuser.com/questions/267918", "https://superuser.com", "https://superuser.com/users/59/" ]
I have seen a similar issue. We solved this by running Word in Compatibility mode, as also suggested by Randolph Potter in the comments above. What worked for us was to choose "Windows XP Service Pack 3". Here is an article from How To Geek on changing Compatibility mode: <http://www.howtogeek.com/howto/10436/using-program-compatibility-mode-in-windows-7/>
Run Microsoft Word in Compatibility Mode and choose an older version of Windows. This fixed the problem for me when running Office 2003 with Windows 8.
501,626
I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well. Here is how the different versions are set up in /usr/bin: ``` python -> python2.6* python2 -> python2.6* python2.6* python3 -> python3.0* python3.0* ``` Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.
2009/02/01
[ "https://Stackoverflow.com/questions/501626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you are using python-mode.el you can try to change `py-which-shell`. In order to do this on a per-file basis you can put ``` # -*- py-which-shell: "python3"; -*- ``` at the first line of your file - or at the second line if the first line starts with `#!`. Another choice is to put ``` # Local Variables: # py-which-shell: "python3" # End: ``` at the end of your file. Perhaps you should give the full path to python3 instead of just "python3".
The answer is yes. If you can distinguish Python 2 from Python 3, then it is a Simple Matter Of Programming to get emacs to do what you want. ``` (define run-python (&optional buffer) (with-current-buffer (or buffer (current-buffer)) (if (is-python3-p) (run-python3) (run-python2)))) (define-key python-mode-map (kbd "C-c C-c") #'run-python) ``` All that's left to do is implement `is-python3-p` and `run-python3` (etc.)
501,626
I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well. Here is how the different versions are set up in /usr/bin: ``` python -> python2.6* python2 -> python2.6* python2.6* python3 -> python3.0* python3.0* ``` Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.
2009/02/01
[ "https://Stackoverflow.com/questions/501626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The answer is yes. If you can distinguish Python 2 from Python 3, then it is a Simple Matter Of Programming to get emacs to do what you want. ``` (define run-python (&optional buffer) (with-current-buffer (or buffer (current-buffer)) (if (is-python3-p) (run-python3) (run-python2)))) (define-key python-mode-map (kbd "C-c C-c") #'run-python) ``` All that's left to do is implement `is-python3-p` and `run-python3` (etc.)
With current `python-mode.el` shebang is honored. Interactively open a Python shell just with ``` M-x pythonVERSION M-x python ``` will call the installed default. <http://launchpad.net/python-mode>
501,626
I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well. Here is how the different versions are set up in /usr/bin: ``` python -> python2.6* python2 -> python2.6* python2.6* python3 -> python3.0* python3.0* ``` Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.
2009/02/01
[ "https://Stackoverflow.com/questions/501626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you are using python-mode.el you can try to change `py-which-shell`. In order to do this on a per-file basis you can put ``` # -*- py-which-shell: "python3"; -*- ``` at the first line of your file - or at the second line if the first line starts with `#!`. Another choice is to put ``` # Local Variables: # py-which-shell: "python3" # End: ``` at the end of your file. Perhaps you should give the full path to python3 instead of just "python3".
My comment on [this answer](https://stackoverflow.com/questions/501626/both-python-2-and-3-in-emacs/502422#502422). I wrote /t/min.py which will run fine in python3 but not in python2 (dictionary comprehension works in python3) Contents of /t/min.py ``` #!/usr/bin/python3 # -*- py-python-command: "/usr/bin/python3"; -*- a = {i:i**2 for i in range(10)} print(a) ``` Note that the shebang indicates python3 and the file local variable py-python-command too. I also wrote /t/min-py.el which makes sure that python-mode.el (ver 5.1.0)is used instead of python.el. Contents of /t/min-py.el ``` (add-to-list 'load-path "~/m/em/lisp/") (autoload 'python-mode "python-mode" "Python Mode." t) ;; (setq py-python-command "python3") ``` Note that the last line is commented out. I start emacs with the following command: ``` emacs -Q -l /t/min-py.el /t/min.py & ``` Now emacs is started with my alternate dotemacs /t/min-py.el and it opens /t/min.py. When I press C-c C-c to send the buffer to python, it says the "for" part is wrong and that indicates that python2 is being used instead of python3. When I press C-c ! to start the python interpreter, it says python 2.5 is started. I can even change the second line of /t/min.py to this: ``` # -*- py-python-command: "chunkybacon"; -*- ``` and do this experiment again and emacs still uses python2. If the last line of /t/min-py.el is not commented out, then C-c C-c and C-c ! both use python3.
501,626
I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well. Here is how the different versions are set up in /usr/bin: ``` python -> python2.6* python2 -> python2.6* python2.6* python3 -> python3.0* python3.0* ``` Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.
2009/02/01
[ "https://Stackoverflow.com/questions/501626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you are using python-mode.el you can try to change `py-which-shell`. In order to do this on a per-file basis you can put ``` # -*- py-which-shell: "python3"; -*- ``` at the first line of your file - or at the second line if the first line starts with `#!`. Another choice is to put ``` # Local Variables: # py-which-shell: "python3" # End: ``` at the end of your file. Perhaps you should give the full path to python3 instead of just "python3".
regarding jrockway's comment: ``` (defun is-python3-p () "Check whether we're running python 2 or 3." (setq mystr (first (split-string (buffer-string) "\n" t))) (with-temp-buffer (insert mystr) (goto-char 0) (search-forward "python3" nil t))) (defun run-python () "Call the python interpreter." (interactive) (if (is-python3-p) (setq py-python-command "/usr/bin/python3") (setq py-python-command "/usr/bin/python")) (py-execute-buffer)) ``` This will call `python3` if "python3" is in the top line of your buffer (shebang, usually). For some reason the `(setq py-pyton-command ...)` doesn't let you change versions once you've run `py-execute-buffer` once. That shouldn't be an issue unless you change your file on the same buffer back and forth.
501,626
I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well. Here is how the different versions are set up in /usr/bin: ``` python -> python2.6* python2 -> python2.6* python2.6* python3 -> python3.0* python3.0* ``` Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.
2009/02/01
[ "https://Stackoverflow.com/questions/501626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you are using python-mode.el you can try to change `py-which-shell`. In order to do this on a per-file basis you can put ``` # -*- py-which-shell: "python3"; -*- ``` at the first line of your file - or at the second line if the first line starts with `#!`. Another choice is to put ``` # Local Variables: # py-which-shell: "python3" # End: ``` at the end of your file. Perhaps you should give the full path to python3 instead of just "python3".
With current `python-mode.el` shebang is honored. Interactively open a Python shell just with ``` M-x pythonVERSION M-x python ``` will call the installed default. <http://launchpad.net/python-mode>
501,626
I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well. Here is how the different versions are set up in /usr/bin: ``` python -> python2.6* python2 -> python2.6* python2.6* python3 -> python3.0* python3.0* ``` Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.
2009/02/01
[ "https://Stackoverflow.com/questions/501626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My comment on [this answer](https://stackoverflow.com/questions/501626/both-python-2-and-3-in-emacs/502422#502422). I wrote /t/min.py which will run fine in python3 but not in python2 (dictionary comprehension works in python3) Contents of /t/min.py ``` #!/usr/bin/python3 # -*- py-python-command: "/usr/bin/python3"; -*- a = {i:i**2 for i in range(10)} print(a) ``` Note that the shebang indicates python3 and the file local variable py-python-command too. I also wrote /t/min-py.el which makes sure that python-mode.el (ver 5.1.0)is used instead of python.el. Contents of /t/min-py.el ``` (add-to-list 'load-path "~/m/em/lisp/") (autoload 'python-mode "python-mode" "Python Mode." t) ;; (setq py-python-command "python3") ``` Note that the last line is commented out. I start emacs with the following command: ``` emacs -Q -l /t/min-py.el /t/min.py & ``` Now emacs is started with my alternate dotemacs /t/min-py.el and it opens /t/min.py. When I press C-c C-c to send the buffer to python, it says the "for" part is wrong and that indicates that python2 is being used instead of python3. When I press C-c ! to start the python interpreter, it says python 2.5 is started. I can even change the second line of /t/min.py to this: ``` # -*- py-python-command: "chunkybacon"; -*- ``` and do this experiment again and emacs still uses python2. If the last line of /t/min-py.el is not commented out, then C-c C-c and C-c ! both use python3.
With current `python-mode.el` shebang is honored. Interactively open a Python shell just with ``` M-x pythonVERSION M-x python ``` will call the installed default. <http://launchpad.net/python-mode>
501,626
I have been using Emacs to write Python 2 code. Now I have both Python 2.6 and 3.0 installed on my system, and I need to write Python 3 code as well. Here is how the different versions are set up in /usr/bin: ``` python -> python2.6* python2 -> python2.6* python2.6* python3 -> python3.0* python3.0* ``` Is there any way to set this up so that Emacs uses the correct version of Python, depending on which language I am using? For instance, C-c C-c currently runs the buffer, but it always calls python2.6, even if I am writing Python 3 code.
2009/02/01
[ "https://Stackoverflow.com/questions/501626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
regarding jrockway's comment: ``` (defun is-python3-p () "Check whether we're running python 2 or 3." (setq mystr (first (split-string (buffer-string) "\n" t))) (with-temp-buffer (insert mystr) (goto-char 0) (search-forward "python3" nil t))) (defun run-python () "Call the python interpreter." (interactive) (if (is-python3-p) (setq py-python-command "/usr/bin/python3") (setq py-python-command "/usr/bin/python")) (py-execute-buffer)) ``` This will call `python3` if "python3" is in the top line of your buffer (shebang, usually). For some reason the `(setq py-pyton-command ...)` doesn't let you change versions once you've run `py-execute-buffer` once. That shouldn't be an issue unless you change your file on the same buffer back and forth.
With current `python-mode.el` shebang is honored. Interactively open a Python shell just with ``` M-x pythonVERSION M-x python ``` will call the installed default. <http://launchpad.net/python-mode>
45,864,260
I have been stuck with this error since a week now, i have googled and tried every possible solution including the ones on Stackoverflow. This is my code: ``` <?php require("phpsqlsearch_dbinfo.php"); // Get parameters from URL $center_lat = $_GET["lat"]; $center_lng = $_GET["lng"]; $radius = $_GET["radius"]; // Start XML file, create parent node $dom = new DOMDocument("1.0"); $node = $dom->createElement("markers"); $parnode = $dom->appendChild($node); // Opens a connection to a mySQL server $connection=mysqli_connect ("localhost", $username, $password); if (!$connection) { die("Not connected : " . mysqli_error()); } // Set the active mySQL database $db_selected = mysqli_select_db($connection, $database); if (!$db_selected) { die ("Can\'t use db : " . mysqli_error($connection)); } // Search the rows in the markers table $query = sprintf("SELECT id, name, address, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20", mysqli_real_escape_string($connection, $center_lat), mysqli_real_escape_string($connection, $center_lng), mysqli_real_escape_string($connection, $center_lat), mysqli_real_escape_string($connection, $radius)); $result = mysqli_query($connection, $query); $result = mysqli_query($connection, $query); if (!$result) { die("Invalid query: " . mysqli_error($connection)); } header("Content-type: text/xml"); // Iterate through the rows, adding XML nodes for each while ($row = @mysqli_fetch_assoc($result)){ $node = $dom->createElement("marker"); $newnode = $parnode->appendChild($node); $newnode->setAttribute("id", $row['id']); $newnode->setAttribute("name", $row['name']); $newnode->setAttribute("address", $row['address']); $newnode->setAttribute("lat", $row['lat']); $newnode->setAttribute("lng", $row['lng']); $newnode->setAttribute("distance", $row['distance']); } echo $dom->saveXML(); ?> ``` My goal is to output the XML to the browser to make sure that it's working but i have been getting these errors: [![enter image description here](https://i.stack.imgur.com/ARb3v.png)](https://i.stack.imgur.com/ARb3v.png) For more info see:<https://developers.google.com/maps/solutions/store-locator/clothing-store-locator> Can someone help me out???
2017/08/24
[ "https://Stackoverflow.com/questions/45864260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5058637/" ]
There isn't enough to go on to actually solve your problem. You can use the following to ensure that you are getting the input you expect. ``` $required = ['lat', 'lng']; $missing = array_diff($required, $_GET); if ( ! empty($missing) ) { $missingString = implode(',', $missing); die("missing {$missingString}"); } ``` With XML, the opening <?xml version="1.0" encoding="UTF-8"?> cannot have a space before it. Your PHP code somewhere is outputting spaces before the echo outputs the XML.
That's a browser message, not a PHP error\_log message. Something has output before the XML. Most likely a PHP warning or notice. Suppress that rubbish! For the best error logging experience, set `error_reporting` to -1, turn `display_errors` off, and set a custom `error_log`. Then in the terminal, type `tail -f /path/to/error_log`. Your notices, warnings and errors will now scroll past in real time, without distorting your web page's display.
206,940
NOTE: I see many similar topics on this, but I've tried all their suggestions, and nothing has worked. ***THE MAIN DIFFERENCE SEEMS TO BE: I always get a black screen with a blinking cursor, while others seem to get through the boot-up and see distorted graphics or just their wallpaper.*** **ISSUE:** > > I do a clean install of Ubuntu 12.10. Boots fine with the “nouveau” graphics driver – **graphics (even just menus) are very slow, choppy, and distorted**. The three other driver options in Ubuntu (official NVIDIA drivers), all result in a variation of the black screen on boot up. There will be NO access to a command line/GUI in anyway what-so-ever (tried every option recommended out there, but the system is unusable at this stage). > > > I can only reinstall, and try different drivers…and I only ever get one shot at it. > > > **QUESTIONS:** > > **-Does anyone know of a PROPRIETARY driver that will actually work on 12.10 with a NVIDIA or ATI card?** > > > **-Should I just buy a newer graphics card to put in as a replacement?** > > > MORE INFO: This is my second computer, and I’m just trying to get a working install of Ubuntu on it. I don’t want to put much money into it, as I have seen Ubuntu run great on much older/less capable machines. I’ve got a decent'ish Core2Duo Intel processor (2.13Ghz), 2GB of RAM, 320GB hard drive, 32-bit architecture, and there is no other O/S installed. It appears as if the graphics card ***(NVIDIA Geforce 7350 LE)*** is holding me back. > > > **TRIED SO FAR:** -all drivers available in Ubuntu \*all fail -manual install of some different NVIDIA drivers \*all fail -also tried installing the generic kernel, [Nvidia driver doesn't work in 12.10](https://askubuntu.com/questions/202677/nvidia-driver-doesnt-work-in-12-10) \*no difference -tried installing 12.04 \*same results -every method suggested to at least get a command line after switching to a NVIDIA driver \*all fail > > **-UPDATE-** > > > Re-tried everything above with a new ***NVIDIA Geforce 210***...**same results for everything.** > > > **-UPDATE #2-** > > > Re-tried everything above with a new ***AMD Radeon HD 6450***...installed the proprietary driver from Ubuntu's "Software Sources" menu...**EVERYTHING NOW WORKS**. See "answer" below for summary. > > >
2012/10/26
[ "https://askubuntu.com/questions/206940", "https://askubuntu.com", "https://askubuntu.com/users/101207/" ]
Install the linux sources and headers. These are required to build the driver. ``` sudo apt-get install linux-source linux-headers-3.5.0-17-generic ``` Then unistall any nvidia drivers you have installed. Then reinstall the nvidia driver ``` sudo apt-get install nvidia-current ``` Then restart the computer ``` sudo shutdown -r now ``` It should now boot up using the nvidia drivers.
Note: This issue has been resolved by way of a hardware replacement, a solution (in regards to software) was not reached. This answer is intended to save people (with similar circumstances) time. On my system, and being fairly new to Linux...I could not get any NVIDIA drivers to work, after trying two different cards. > > **The solution for me was an AMD card, with the AMD/ATI proprietary drivers (all versions available in Ubuntu work). For those interested - the open source driver worked, but there were odd colored pixels everywhere.** > > >
116,283
I am an editor for a trade publication with 40 years of experience in journalism. The company wants me to take a job on the events side, writing content, helping with organization, moderating panels, archiving video. They haven’t called it a promotion but it would clearly be more intense work and involve traveling to conferences every other month. I’d like to accept the offer but I want to negotiate a salary increase after a six-month review. Can I do that upfront or do I wait the six months and in either case, what kind of percentage would be equitable?
2018/07/21
[ "https://workplace.stackexchange.com/questions/116283", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/90496/" ]
You are playing well above your pay grade. Let your manager manage your colleague. An outcome like "the project got finished but wasn't great, one of the interns worked hard but the other was a nightmare" is common as dirt in this industry. Do the tasks your manager has assigned to you. When you're out of tasks, go ask for more. When you can't do something because you're waiting on the colleague, let your manager know. When you get something from your colleague and it's unusably bad, ask your manager whether you should fix it up, or bounce it back explaining why you can't use it. Then ask what you should do next given that you can't do what you were planning to do (use the thing from the colleague.) You seem to think that if you can't fix this other intern (or arrange for a firing) it will reflect poorly on you. Do you really think your manager is so terrible as not to see what you see? You've reported it, shown the code, the manager has already started dealing out tasks and telling the other intern to use source control, and so on. This is all the manager's job, not yours. Relax and do yours, keep your manager informed, and let the manager manage.
* Inform you manager about the Verbatim copies of code from the Internet, and tell that you see a potential legal liability there * Explicitly state in commit messages which of his commits you fixed * Your manager listened to you once, so the next time a huge and messy commit comes which breaks something working and could have been caught by the test, you write an email to your coworker with the manager in CC stating that you need he should show you on his machine how he tested the code and how it works. * When he submitted something which breaks and leaves during the office hours, you go to the manager shortly after he left and ask him to locate your coworker, stating that you would prefer if the coworker helps integrating the code - state that you can do it alone, but it may take more time and state which of your tasks is delayed by this. * In case this continues, take notes over one week how much work integrating your coworkers mess has caused you, with specific incidents, go to your manager and state that you "can handle it without him"
116,283
I am an editor for a trade publication with 40 years of experience in journalism. The company wants me to take a job on the events side, writing content, helping with organization, moderating panels, archiving video. They haven’t called it a promotion but it would clearly be more intense work and involve traveling to conferences every other month. I’d like to accept the offer but I want to negotiate a salary increase after a six-month review. Can I do that upfront or do I wait the six months and in either case, what kind of percentage would be equitable?
2018/07/21
[ "https://workplace.stackexchange.com/questions/116283", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/90496/" ]
Since you are using a versioning system: Fix one bug in his code and check the fix into the versioning system. Then fix another bug and check the fix into the versioning system. And so on. So when you need evidence you point your boss to the versioning system, which contains your name 99 times and his name once. (In a professional environment with experienced developers you use a source code control system in a different way). And consider that many companies use an internship as a very, very long interview. If that is the case in your company, then by the sounds of it you are passing the interview, and your colleague is not.
* Inform you manager about the Verbatim copies of code from the Internet, and tell that you see a potential legal liability there * Explicitly state in commit messages which of his commits you fixed * Your manager listened to you once, so the next time a huge and messy commit comes which breaks something working and could have been caught by the test, you write an email to your coworker with the manager in CC stating that you need he should show you on his machine how he tested the code and how it works. * When he submitted something which breaks and leaves during the office hours, you go to the manager shortly after he left and ask him to locate your coworker, stating that you would prefer if the coworker helps integrating the code - state that you can do it alone, but it may take more time and state which of your tasks is delayed by this. * In case this continues, take notes over one week how much work integrating your coworkers mess has caused you, with specific incidents, go to your manager and state that you "can handle it without him"
116,283
I am an editor for a trade publication with 40 years of experience in journalism. The company wants me to take a job on the events side, writing content, helping with organization, moderating panels, archiving video. They haven’t called it a promotion but it would clearly be more intense work and involve traveling to conferences every other month. I’d like to accept the offer but I want to negotiate a salary increase after a six-month review. Can I do that upfront or do I wait the six months and in either case, what kind of percentage would be equitable?
2018/07/21
[ "https://workplace.stackexchange.com/questions/116283", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/90496/" ]
* Inform you manager about the Verbatim copies of code from the Internet, and tell that you see a potential legal liability there * Explicitly state in commit messages which of his commits you fixed * Your manager listened to you once, so the next time a huge and messy commit comes which breaks something working and could have been caught by the test, you write an email to your coworker with the manager in CC stating that you need he should show you on his machine how he tested the code and how it works. * When he submitted something which breaks and leaves during the office hours, you go to the manager shortly after he left and ask him to locate your coworker, stating that you would prefer if the coworker helps integrating the code - state that you can do it alone, but it may take more time and state which of your tasks is delayed by this. * In case this continues, take notes over one week how much work integrating your coworkers mess has caused you, with specific incidents, go to your manager and state that you "can handle it without him"
As other recommend, I would ask somebody higher up if I could start CCing him in all your exchanges besides documenting everything in a source code system. Obviously, if you working for the two, your colleague does not need to do it. However, it seems a bit odd he taking such a relaxed stance of missing so many hours of work and days off in the middle of an intern project...it is as he knows he cannot fail. I would investigate if he has relatives inside. I have seen my share of pet employees over the years. It is usually not that hard to find out. Maybe you were setup together for a reason. Welcome to the fantastic world of the real world and office politics! Assuming no foul play, at the end of the day, someone is failing you not making regular meetings to guide you both and assess the state of the project. PS. A possible course of action if that is a University endorsed internship is probing on the University side if you can change for another place. The odds are slim, but without asking it is not possible to find out.
116,283
I am an editor for a trade publication with 40 years of experience in journalism. The company wants me to take a job on the events side, writing content, helping with organization, moderating panels, archiving video. They haven’t called it a promotion but it would clearly be more intense work and involve traveling to conferences every other month. I’d like to accept the offer but I want to negotiate a salary increase after a six-month review. Can I do that upfront or do I wait the six months and in either case, what kind of percentage would be equitable?
2018/07/21
[ "https://workplace.stackexchange.com/questions/116283", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/90496/" ]
You are playing well above your pay grade. Let your manager manage your colleague. An outcome like "the project got finished but wasn't great, one of the interns worked hard but the other was a nightmare" is common as dirt in this industry. Do the tasks your manager has assigned to you. When you're out of tasks, go ask for more. When you can't do something because you're waiting on the colleague, let your manager know. When you get something from your colleague and it's unusably bad, ask your manager whether you should fix it up, or bounce it back explaining why you can't use it. Then ask what you should do next given that you can't do what you were planning to do (use the thing from the colleague.) You seem to think that if you can't fix this other intern (or arrange for a firing) it will reflect poorly on you. Do you really think your manager is so terrible as not to see what you see? You've reported it, shown the code, the manager has already started dealing out tasks and telling the other intern to use source control, and so on. This is all the manager's job, not yours. Relax and do yours, keep your manager informed, and let the manager manage.
Since you are using a versioning system: Fix one bug in his code and check the fix into the versioning system. Then fix another bug and check the fix into the versioning system. And so on. So when you need evidence you point your boss to the versioning system, which contains your name 99 times and his name once. (In a professional environment with experienced developers you use a source code control system in a different way). And consider that many companies use an internship as a very, very long interview. If that is the case in your company, then by the sounds of it you are passing the interview, and your colleague is not.
116,283
I am an editor for a trade publication with 40 years of experience in journalism. The company wants me to take a job on the events side, writing content, helping with organization, moderating panels, archiving video. They haven’t called it a promotion but it would clearly be more intense work and involve traveling to conferences every other month. I’d like to accept the offer but I want to negotiate a salary increase after a six-month review. Can I do that upfront or do I wait the six months and in either case, what kind of percentage would be equitable?
2018/07/21
[ "https://workplace.stackexchange.com/questions/116283", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/90496/" ]
You are playing well above your pay grade. Let your manager manage your colleague. An outcome like "the project got finished but wasn't great, one of the interns worked hard but the other was a nightmare" is common as dirt in this industry. Do the tasks your manager has assigned to you. When you're out of tasks, go ask for more. When you can't do something because you're waiting on the colleague, let your manager know. When you get something from your colleague and it's unusably bad, ask your manager whether you should fix it up, or bounce it back explaining why you can't use it. Then ask what you should do next given that you can't do what you were planning to do (use the thing from the colleague.) You seem to think that if you can't fix this other intern (or arrange for a firing) it will reflect poorly on you. Do you really think your manager is so terrible as not to see what you see? You've reported it, shown the code, the manager has already started dealing out tasks and telling the other intern to use source control, and so on. This is all the manager's job, not yours. Relax and do yours, keep your manager informed, and let the manager manage.
As other recommend, I would ask somebody higher up if I could start CCing him in all your exchanges besides documenting everything in a source code system. Obviously, if you working for the two, your colleague does not need to do it. However, it seems a bit odd he taking such a relaxed stance of missing so many hours of work and days off in the middle of an intern project...it is as he knows he cannot fail. I would investigate if he has relatives inside. I have seen my share of pet employees over the years. It is usually not that hard to find out. Maybe you were setup together for a reason. Welcome to the fantastic world of the real world and office politics! Assuming no foul play, at the end of the day, someone is failing you not making regular meetings to guide you both and assess the state of the project. PS. A possible course of action if that is a University endorsed internship is probing on the University side if you can change for another place. The odds are slim, but without asking it is not possible to find out.
116,283
I am an editor for a trade publication with 40 years of experience in journalism. The company wants me to take a job on the events side, writing content, helping with organization, moderating panels, archiving video. They haven’t called it a promotion but it would clearly be more intense work and involve traveling to conferences every other month. I’d like to accept the offer but I want to negotiate a salary increase after a six-month review. Can I do that upfront or do I wait the six months and in either case, what kind of percentage would be equitable?
2018/07/21
[ "https://workplace.stackexchange.com/questions/116283", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/90496/" ]
Since you are using a versioning system: Fix one bug in his code and check the fix into the versioning system. Then fix another bug and check the fix into the versioning system. And so on. So when you need evidence you point your boss to the versioning system, which contains your name 99 times and his name once. (In a professional environment with experienced developers you use a source code control system in a different way). And consider that many companies use an internship as a very, very long interview. If that is the case in your company, then by the sounds of it you are passing the interview, and your colleague is not.
As other recommend, I would ask somebody higher up if I could start CCing him in all your exchanges besides documenting everything in a source code system. Obviously, if you working for the two, your colleague does not need to do it. However, it seems a bit odd he taking such a relaxed stance of missing so many hours of work and days off in the middle of an intern project...it is as he knows he cannot fail. I would investigate if he has relatives inside. I have seen my share of pet employees over the years. It is usually not that hard to find out. Maybe you were setup together for a reason. Welcome to the fantastic world of the real world and office politics! Assuming no foul play, at the end of the day, someone is failing you not making regular meetings to guide you both and assess the state of the project. PS. A possible course of action if that is a University endorsed internship is probing on the University side if you can change for another place. The odds are slim, but without asking it is not possible to find out.
74,615,696
So i updated the values of a dictionary into percentage by multiplying by 100. Now i want to replace the initial decimal with the updated results, but instead, i am getting each value replaced by the whole new values. ``` job_role_overtime_att_rate = {'Healthcare Representative Overtime Rate' : 2/37, ' Human Resources Overtime Rate': 5/13, 'Laboratory Technician Total' : 31/62, 'Manager Total': 4/27, 'Manufacturing Director Total': 4/39, 'Research Director Total' : 1/23, 'Research Scientist Total' : 33/97, 'Sales Executive Total' : 31/94, 'Sales Representative Total' : 16/24} job_role_overtime_att_rate() ``` ``` {'Healthcare Representative Overtime Rate': 0.05405405405405406, ' Human Resources Overtime Rate': 0.38461538461538464, 'Laboratory Technician Total': 0.5, 'Manager Total': 0.14814814814814814, 'Manufacturing Director Total': 0.10256410256410256, 'Research Director Total': 0.043478260869565216, 'Research Scientist Total': 0.3402061855670103, 'Sales Executive Total': 0.32978723404255317, 'Sales Representative Total': 0.6666666666666666} ``` this the result of the above code. ``` for i in job_role_overtime_att_rate.values(): a = i * 100 print('{0:.2f}'.format(a)) ``` this multiplies the initial result by 100. now ``` 5.41 38.46 50.00 14.81 10.26 4.35 34.02 32.98 66.67 ``` here is the result. ``` for i in job_role_overtime_att_rate.values(): a = i * 100 print('{0:.2f}'.format(a)) for values in job_role_overtime_att_rate.values(): values = a print(values) ``` this is to replace the intial values with the new one. at least that's what i thought it will do. ``` 5.41 5.405405405405405 5.405405405405405 5.405405405405405 5.405405405405405 5.405405405405405 5.405405405405405 5.405405405405405 5.405405405405405 5.405405405405405 38.46 38.46153846153847 38.46153846153847 38.46153846153847 38.46153846153847 38.46153846153847 38.46153846153847 38.46153846153847 38.46153846153847 38.46153846153847 50.00 50.0 50.0 50.0 50.0 50.0 50.0 50.0 50.0 50.0 14.81 14.814814814814813 14.814814814814813 14.814814814814813 14.814814814814813 14.814814814814813 14.814814814814813 14.814814814814813 14.814814814814813 14.814814814814813 10.26 10.256410256410255 10.256410256410255 10.256410256410255 10.256410256410255 10.256410256410255 10.256410256410255 10.256410256410255 10.256410256410255 10.256410256410255 4.35 4.3478260869565215 4.3478260869565215 4.3478260869565215 4.3478260869565215 4.3478260869565215 4.3478260869565215 4.3478260869565215 4.3478260869565215 4.3478260869565215 34.02 34.02061855670103 34.02061855670103 34.02061855670103 34.02061855670103 34.02061855670103 34.02061855670103 34.02061855670103 34.02061855670103 34.02061855670103 32.98 32.97872340425532 32.97872340425532 32.97872340425532 32.97872340425532 32.97872340425532 32.97872340425532 32.97872340425532 32.97872340425532 32.97872340425532 66.67 66.66666666666666 66.66666666666666 66.66666666666666 66.66666666666666 66.66666666666666 66.66666666666666 66.66666666666666 66.66666666666666 66.66666666666666 ``` here is what it's returning. Kindly help. Thanks
2022/11/29
[ "https://Stackoverflow.com/questions/74615696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10289706/" ]
You can loop through the `dict.items()` function to loop through the key and the value. ``` job_role_overtime_att_rate = { 'Healthcare Representative Overtime Rate': 0.05405405405405406, 'Human Resources Overtime Rate': 0.38461538461538464, 'Laboratory Technician Total': 0.5, 'Manager Total': 0.14814814814814814, 'Manufacturing Director Total': 0.10256410256410256, 'Research Director Total': 0.043478260869565216, 'Research Scientist Total': 0.3402061855670103, 'Sales Executive Total': 0.32978723404255317, 'Sales Representative Total': 0.6666666666666666 } for name, value in job_role_overtime_att_rate.items(): a = round(value*100, 2) job_role_overtime_att_rate[name] = a print(job_role_overtime_att_rate) ```
I'm not sure what your point is, but you loop over values and in the inner loop again over values. So for each value you loop over all values, thus it's expected that you will get **n^2** prints for dictionary with **n** values. If I guess right this code does what you need: ``` for key, value in job_role_overtime_att_rate.items(): job_role_overtime_att_rate[key]= value*100 ```
41,888,489
I am beginner to git and trying some hands on with it on Windows. I made a repository on Bitbucket. Added Three files ( SAY A , B , C ) to the master branch via Bitbucket online . Now i have folder on my local PC , where i used `git fetch` for getting those three file. Three files are now in local repository. Now , i added one other file (SAY D ) on bitbucket , and changed the content of all three files (A , B , C ) . Now if i try to fetch the changes via `git fetch MY_REMOTE master` , I am not getting any changes in my local. but * with `git pull MY_REMOTE master` , I am able to see the changes. * with `git checkout MY_REMOTE/master` , I am able to see the changes. So the doubt i have , * `git fetch` simply copies the changes those are not on the local to the local repo except Local repo have changed the same copy. Why `git fetch` is not working here ? * I don't understand the purpose of doing `git checkout MY_REMOTE/master` on Local . Why should i do that ?
2017/01/27
[ "https://Stackoverflow.com/questions/41888489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2218640/" ]
Use "git pull --rebase" to synchronize your changes to local from remote. Here is answer for git fetch git fetch really only downloads new data from a remote repository - but it doesn't integrate any of this new data into your working files. Fetch is great for getting a fresh view on all the things that happened in a remote repository. Git checkout , used to switch across branches of a repository. Just google and you will get plenty of information:.
Make sure you add all files and commit. `git add . && git commit -m "<your_message>"` also check any setting at coc-setting.json
41,888,489
I am beginner to git and trying some hands on with it on Windows. I made a repository on Bitbucket. Added Three files ( SAY A , B , C ) to the master branch via Bitbucket online . Now i have folder on my local PC , where i used `git fetch` for getting those three file. Three files are now in local repository. Now , i added one other file (SAY D ) on bitbucket , and changed the content of all three files (A , B , C ) . Now if i try to fetch the changes via `git fetch MY_REMOTE master` , I am not getting any changes in my local. but * with `git pull MY_REMOTE master` , I am able to see the changes. * with `git checkout MY_REMOTE/master` , I am able to see the changes. So the doubt i have , * `git fetch` simply copies the changes those are not on the local to the local repo except Local repo have changed the same copy. Why `git fetch` is not working here ? * I don't understand the purpose of doing `git checkout MY_REMOTE/master` on Local . Why should i do that ?
2017/01/27
[ "https://Stackoverflow.com/questions/41888489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2218640/" ]
As you mentioned, [`git fetch`](https://git-scm.com/docs/git-fetch) simply fetches the changes from the remote to your local machine. It doesn't apply them. `git checkout MY_REMOTE/master` applies the fetched changes to your local copy of the files. **Warning**: If your local files have been modified (and not commited) your local changes will be lost when you type `git checkout MY_REMOTE/master`. To apply both the remote and local changes * Commit your local changes: `git commit -a -m "my commit"` * Apply the remote changes: `git pull origin master` This will merge the two change sets (local and remote) Alternatively, you can use `pull --rebase origin master` to first apply your local commits, *then* apply the remote commits. See also [this answer](https://stackoverflow.com/a/38361930/1370722)
Make sure you add all files and commit. `git add . && git commit -m "<your_message>"` also check any setting at coc-setting.json
41,888,489
I am beginner to git and trying some hands on with it on Windows. I made a repository on Bitbucket. Added Three files ( SAY A , B , C ) to the master branch via Bitbucket online . Now i have folder on my local PC , where i used `git fetch` for getting those three file. Three files are now in local repository. Now , i added one other file (SAY D ) on bitbucket , and changed the content of all three files (A , B , C ) . Now if i try to fetch the changes via `git fetch MY_REMOTE master` , I am not getting any changes in my local. but * with `git pull MY_REMOTE master` , I am able to see the changes. * with `git checkout MY_REMOTE/master` , I am able to see the changes. So the doubt i have , * `git fetch` simply copies the changes those are not on the local to the local repo except Local repo have changed the same copy. Why `git fetch` is not working here ? * I don't understand the purpose of doing `git checkout MY_REMOTE/master` on Local . Why should i do that ?
2017/01/27
[ "https://Stackoverflow.com/questions/41888489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2218640/" ]
Git's `fetch` does not get files—well, not directly anyway. To some extent, Git doesn't care that much about files at all. What Git cares about are *commits*. Before we visit this idea any further, though, we should probably review some basic Git definitions. What's in a repository ====================== A *Git repository* has three main parts: *commits*, the *index*, and the *work-tree*. (Some Git repositories will omit the work-tree, and in newer versions of Git you can have more than one work-tree, where each work-tree has its own index. But in general you start with one of each.) A *commit* is a snapshot: a complete *set* of files. It's not just *a* file, and it's not the *difference* in some files either: it's a standalone thing, with all the files you have decided to save in that commit, in the form they had when you saved them. A commit is also permanent and unchanging. Like all Git objects, it has a unique identifier: `3313b78c145ba9212272b5318c111cde12bfef4a`, for instance. Once it is stored, you can never change *anything* in a commit. If you try, you get a *copy* of the commit, with the change, and the copy has a new, different ID. You can (sometimes) *delete* a commit entirely, but you can't change it, only copy it—well, most of it, all but the changed part of course—to a new different-ID commit. Git really, *really* cares about commits. It works very hard to make sure you never lose one. It cares much less about the index and work-tree: those are neither permanent, nor unchanging. The advantages of commits are obvious, but their disadvantage is also obvious: they're stored inside Git—in the repository—in a form that nothing else on the computer can deal with. The *work-tree* is the opposite of this: it's in a form that *everything* else on the computer can deal with, and it's quite impermanent and changeable. It's where you do all your work. It has files, rather than mysterious Git objects. This is where you read, write, and edit your files. Git's *index* is initially quite mysterious to most people (it was to me), and it has a lot of complicated twists you will eventually encounter. Some software tries to hide the index entirely, but that's not a good idea. In one way the index is actually very simple though: It's where Git has you build the *next commit*. The index starts out matching the *current* commit, and then you `git add` new versions of existing files, or entirely new files, to the index, to copy the new ones in. Then when you run `git commit`, Git makes a new commit out of whatever you have in the index right now. This makes the permanent, unchanging snapshot. The index, which is also called the *staging area*, is simply where you arrange (or "stage") your files to make them as pretty as possible for the snapshot. Each commit also records the ID of its immediate predecessor, or *parent*, commit. This becomes crucial as soon as you start working with history. The history is formed *by the commits themselves*, through this "my parent is ..." information. A branch name like `master` simply identifies—by its ID—the *newest* commit on that branch. Git calls this the *tip* of the branch. This newest commit remembers its parent, and that parent remembers its own parent (the newest commit's grandparent), and so on. Git also has other entities that do the same kind of thing: remember one specific commit's ID. The most important two are *tags* and *remote-tracking branches*. ### Summary A repository contains *commits*, which contain *snapshots*, and which form the history of all commits ever made. The *branch name* `master` finds the *newest* commit on `master`. And, although commits *contain* files, they are not themselves files: they contain whole sets of files, all as one collection. A repository has an index, which is an intermediary between internal Git commit form and work-tree form, and most repositories have a work-tree, which lets you get at the commits' files *as* files. What `git checkout` does ======================== The `git checkout` command mainly copies commits into the index and work-tree, so that you can move around throughout the history of all commits and see the corresponding snapshot in your work-tree. It also adjusts what Git calls `HEAD`. The name `HEAD`, in Git, *always refers to the current commit* by its ID—but it does so in one of two different ways. You can be "on a branch", in which case the name `HEAD` simply contains the name of the branch. It's then the branch name that gets Git the ID of the current commit. Or, you can have a "detached HEAD", in which case the name `HEAD` records the ID of the current commit. If you give `git checkout` a branch name—such as `git checkout master`—it puts you "on the branch": it checks out the tip commit, since that's the ID stored in the branch name, and it puts the branch name in `HEAD`. If you give `git checkout` a raw commit ID, or a tag name, or a remote-tracking branch name, it finds the corresponding ID, checks out that commit, and puts the ID into `HEAD`. What `git fetch`—and `git push`—do ================================== All of the above steps work entirely with your own repository. Git doesn't restrict you to just one repository, though. At well-defined times that *you* choose, you can tell your Git to call up another Git, usually over the Internet, and have a sort of conversation with that other Git. This is what both `git fetch` and `git push` do. They call up some other Git, at the other end of some URL. The URL is usually stored under a name, which is called a *remote*. The most common one—often the only remote in any given repository—is `origin` (because `git clone` sets that one up for you). Remember, though, Git mostly cares about *commits*. So when your Git calls up another Git, the conversation they have is mostly about commits. They do, of course, need a way to find the IDs of those commits, and for that they usually start with some branch names. This is in general how Git starts everything: take a branch name, or maybe just the name `HEAD`, and find a commit ID. Use that commit. Then, if it's appropriate, go to that commit's parent and do something with *that* commit, and so on. The `fetch` process in particular gets a list of all the branches in the other Git. It then obtains all the *commits* that are in those branches that it does not already have in its own repository. Those commits come with any necessary snapshot-files, almost as a sort of side effect. Last, your Git takes their Git's branch names and *renames* them, turning those branch names into your own *remote-tracking branch* names. If the remote is named `origin`, their (origin's) master becomes your `origin/master`. You get all their commits, except for the ones you already have. The ones you already have, you already have. Your Git can be sure you have them because you have the IDs. The ID of each commit is unique to that commit, and the commit is permanent and unchanging—so if you have the *same* ID they do, you both necessarily have the same *commit*. Your Git and their Git use `git push` very similarly, but in the other direction, and with a twist: your Git gives them your commits—the ones you have that they don't, that is—and then asks them to set *their* `master`, or whatever branch you are pushing, to set as its tip commit, the same commit you have as the tip of *your* `master`. There's no renaming here: you ask them to make their `master` exactly the same as your `master`. When you `git fetch`, your Git *renames* their branch-names, so it's safe to just take them whole. No matter what they did to *their* branches, this *cannot* affect your own branch names. But when you `git push`, you have your Git ask them to *set* their branch-names, with no renaming at all. If they don't like the requested setting, they can say "no, I won't set that": they can reject your push. That doesn't happen with fetch, and that's where your initial question comes in. `git pull` = `git fetch` + something else ========================================= Fetching just gets you their new commits. *Because* `git fetch` never touches your own branches, you often want a second step. The main problem here is that the *correct* second step to take depends on what commits you brought in, and what commits you already had. There are two main options: `git merge`, and `git rebase`. You can program Git to make `git pull` do either one. The default is to do `git merge`. Again, the "right" command depends on what you have in your branches, what you got from the remote when you fetched, and how you want to work. Most people, in practice, mostly want `git rebase` here, but `git pull` defaults to running `git merge`. In many cases, both commands wind up doing the same thing, so that it doesn't matter that the default is the *wrong* command. But I advise newbies to avoid `git pull`, because it does default to the command most people mostly *don't* want, and because when things go wrong—they always do eventually—the way to *recover* from the problem depends on you knowing that you ran `git rebase` or `git merge`. If you actually use those directly, you will know.
Make sure you add all files and commit. `git add . && git commit -m "<your_message>"` also check any setting at coc-setting.json
20,796,698
I have a table named "accounts" and it has two fields "month" and "amount". I like to get highest month records to display front page ``` eg: month amount 10/2013 -> 12 12/2013 -> 20 12/2013 -> 21 11/2013 -> 10 ``` how could i filter highest month all data , I used **time stamp format** to store date
2013/12/27
[ "https://Stackoverflow.com/questions/20796698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3099298/" ]
``` SELECT * FROM accounts WHERE month = (SELECT MAX(month) FROM accounts) ```
SELECT \* FROM accounts ORDER BY month DESC may work.
8,108,654
I am trying to find out maximum value in a hash and corresponding key to that maximum value. My hash looks like ``` %hash = ( bob => "4.9", gita => "3.9 , 6.8", diu => "3.0", ); ``` Now I want to find the maximum value in that hash with the key it belongs. Output needed is ``` gita 6.8 ``` I am trying to sort the values in `%hash` in ascending order to get the maximum value like this ``` sub hashValueAscendingNum { $hash{$a} cmp $hash{$b}; } foreach my $highest (sort hashValueAscendingNum(keys(%hash))) { print "\t $hash{$highestMagnitude} \t\t $highest \n"; } ``` I want all the values in the hash to be checked, and the one with maximum value should be returned with its key. How can i do that?
2011/11/13
[ "https://Stackoverflow.com/questions/8108654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009157/" ]
You need to first associate each key with the highest of the values corresponding to it in the original `%hash` and then find the key associated with the highest value. ``` #!/usr/bin/env perl use strict; use warnings; use List::Util qw( max ); my %hash = ( bob => [ 4.9 ], gita => [ 3.9, 6.8 ], diu => [ 3.0 ], ); my %max = map { $_ => max @{ $hash{$_} } } keys %hash; my ($argmax) = (sort { $max{$b} <=> $max{$a} } keys %max)[0]; my $max = $max{ $argmax }; print join(' => ', $argmax, $max), "\n"; ``` Of course, this is very inefficient (esp. using `sort`) but for the dimensions you showed, it does not matter. For completeness, here is a more efficient version using `each`: ``` #!/usr/bin/env perl use strict; use warnings; use List::Util qw( max ); my %hash = ( bob => [ 4.9 ], gita => [ 3.9, 6.8 ], diu => [ 3.0 ], ); my ($argmax, $max) = @{ init_argmax_max(\%hash) }; while (my ($k, $v) = each %hash) { $v = max @{ $v }; if ( $v > $max ) { $argmax = $k; $max = $v; } } print join(' => ', $argmax, $max), "\n"; sub init_argmax_max { my ($hash) = @_; my ($argmax, $max) = each %{ $hash }; keys %{ $hash }; $max = max @{ $max }; return [$argmax, $max]; } ```
``` #!/usr/bin/perl use warnings; use strict; my %hash = ( bob => [ 4.9 ], gita => [ 3.9, 6.8 ], diu => [ 3.0 ], ); my $max_key; my $max_val=0; foreach my $key (keys %hash) { foreach my $val ( @{$hash{$key}} ) { ($max_key, $max_val) = ($key, $val) if $val > $max_val; } } print "$max_key => $max_val\n"; ```
8,108,654
I am trying to find out maximum value in a hash and corresponding key to that maximum value. My hash looks like ``` %hash = ( bob => "4.9", gita => "3.9 , 6.8", diu => "3.0", ); ``` Now I want to find the maximum value in that hash with the key it belongs. Output needed is ``` gita 6.8 ``` I am trying to sort the values in `%hash` in ascending order to get the maximum value like this ``` sub hashValueAscendingNum { $hash{$a} cmp $hash{$b}; } foreach my $highest (sort hashValueAscendingNum(keys(%hash))) { print "\t $hash{$highestMagnitude} \t\t $highest \n"; } ``` I want all the values in the hash to be checked, and the one with maximum value should be returned with its key. How can i do that?
2011/11/13
[ "https://Stackoverflow.com/questions/8108654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009157/" ]
You need to first associate each key with the highest of the values corresponding to it in the original `%hash` and then find the key associated with the highest value. ``` #!/usr/bin/env perl use strict; use warnings; use List::Util qw( max ); my %hash = ( bob => [ 4.9 ], gita => [ 3.9, 6.8 ], diu => [ 3.0 ], ); my %max = map { $_ => max @{ $hash{$_} } } keys %hash; my ($argmax) = (sort { $max{$b} <=> $max{$a} } keys %max)[0]; my $max = $max{ $argmax }; print join(' => ', $argmax, $max), "\n"; ``` Of course, this is very inefficient (esp. using `sort`) but for the dimensions you showed, it does not matter. For completeness, here is a more efficient version using `each`: ``` #!/usr/bin/env perl use strict; use warnings; use List::Util qw( max ); my %hash = ( bob => [ 4.9 ], gita => [ 3.9, 6.8 ], diu => [ 3.0 ], ); my ($argmax, $max) = @{ init_argmax_max(\%hash) }; while (my ($k, $v) = each %hash) { $v = max @{ $v }; if ( $v > $max ) { $argmax = $k; $max = $v; } } print join(' => ', $argmax, $max), "\n"; sub init_argmax_max { my ($hash) = @_; my ($argmax, $max) = each %{ $hash }; keys %{ $hash }; $max = max @{ $max }; return [$argmax, $max]; } ```
You got several good answers. Now a bad one (assuming you fix the decimal separator in the hash): ``` my %hash = (bob => "4.9", gita =>"3.9 , 6.8", diu => "3.0", ); my $max = (map{join" ",@$_[0,1]}sort{$b->[1]-$a->[1]}map{[$_,sort{$b-$a}split(/ , /,$hash{$_})]}keys%hash)[0]; print "$max\n"; ``` Output: ``` gita 6.8 ``` Never do this unless you're deliberately trying to golf and/or obfuscate it though.
8,108,654
I am trying to find out maximum value in a hash and corresponding key to that maximum value. My hash looks like ``` %hash = ( bob => "4.9", gita => "3.9 , 6.8", diu => "3.0", ); ``` Now I want to find the maximum value in that hash with the key it belongs. Output needed is ``` gita 6.8 ``` I am trying to sort the values in `%hash` in ascending order to get the maximum value like this ``` sub hashValueAscendingNum { $hash{$a} cmp $hash{$b}; } foreach my $highest (sort hashValueAscendingNum(keys(%hash))) { print "\t $hash{$highestMagnitude} \t\t $highest \n"; } ``` I want all the values in the hash to be checked, and the one with maximum value should be returned with its key. How can i do that?
2011/11/13
[ "https://Stackoverflow.com/questions/8108654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009157/" ]
A hash has only a single key and a single value, and each key must be unique. In your original problem you have this: ``` %hash = ( bob => "4.9", gita =>"3.9 , 6,8", diu => "3.0", ); ``` Well, `gita` can't have two values. Nor, can you have two keys in your hash equal to `gita`. Thus, you can't use a simple hash to store your values. There are ways around this though by using references. For example, each element in your hash can contain a [reference to an array](http://perldoc.perl.org/perlreftut.html). Thus, your data structure can look like this: ``` %hash = ( bob => [(4.9)], gita => [(3.9, 6.8)], diu => [(3.0)], ); ``` The `[` and `]` marks a reference to an array. However, this wouldn't really solve your particular problem since you now have to go through each key in the hash, then each element in the array for each key, and sort those. You could create a sorting subroutine, but just because you can say `sort` doesn't make it efficient. Maybe what you need is an array of arrays. This will get rid of the issue you have with `gita` having two values, but make sorting a bit easier. Imagine a structure like this: ``` my @array = ( [bob => 4.9], [gita => 3.9], [gita => 6.8], [diu => 3.0], ); ``` Now, we can do a sort on `@array` depending upon the value of `$array[$x]->[1]`! All we need is for each element of the array `@array` is to compare $a->[1] with $b->[1]. Then, if we do a reverse sort on it, the biggest element will be `$array[0]`. The name is `$array[0]->[0]` and the element is `$array->[0]->[1]`. ``` #! /usr/bin/env perl use strict; use warnings; use feature qw(say switch); my @array = ( [bob => 4.9], [gita => 3.9], [gita => 6.8], [diu => 3.0], ); @array = reverse sort mysort @array; say "$array[0]->[0] $array[0]->[1]"; sub mysort { $a->[1] <=> $b->[1]; } ``` And the output is: ``` gita 6.8. ``` You notice that link to [Perldoc's perllol](http://perldoc.perl.org/perlreftut.html)? I suggest you read it if you've never worked with Perl references before.
``` #!/usr/bin/perl use warnings; use strict; my %hash = ( bob => [ 4.9 ], gita => [ 3.9, 6.8 ], diu => [ 3.0 ], ); my $max_key; my $max_val=0; foreach my $key (keys %hash) { foreach my $val ( @{$hash{$key}} ) { ($max_key, $max_val) = ($key, $val) if $val > $max_val; } } print "$max_key => $max_val\n"; ```
8,108,654
I am trying to find out maximum value in a hash and corresponding key to that maximum value. My hash looks like ``` %hash = ( bob => "4.9", gita => "3.9 , 6.8", diu => "3.0", ); ``` Now I want to find the maximum value in that hash with the key it belongs. Output needed is ``` gita 6.8 ``` I am trying to sort the values in `%hash` in ascending order to get the maximum value like this ``` sub hashValueAscendingNum { $hash{$a} cmp $hash{$b}; } foreach my $highest (sort hashValueAscendingNum(keys(%hash))) { print "\t $hash{$highestMagnitude} \t\t $highest \n"; } ``` I want all the values in the hash to be checked, and the one with maximum value should be returned with its key. How can i do that?
2011/11/13
[ "https://Stackoverflow.com/questions/8108654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009157/" ]
A hash has only a single key and a single value, and each key must be unique. In your original problem you have this: ``` %hash = ( bob => "4.9", gita =>"3.9 , 6,8", diu => "3.0", ); ``` Well, `gita` can't have two values. Nor, can you have two keys in your hash equal to `gita`. Thus, you can't use a simple hash to store your values. There are ways around this though by using references. For example, each element in your hash can contain a [reference to an array](http://perldoc.perl.org/perlreftut.html). Thus, your data structure can look like this: ``` %hash = ( bob => [(4.9)], gita => [(3.9, 6.8)], diu => [(3.0)], ); ``` The `[` and `]` marks a reference to an array. However, this wouldn't really solve your particular problem since you now have to go through each key in the hash, then each element in the array for each key, and sort those. You could create a sorting subroutine, but just because you can say `sort` doesn't make it efficient. Maybe what you need is an array of arrays. This will get rid of the issue you have with `gita` having two values, but make sorting a bit easier. Imagine a structure like this: ``` my @array = ( [bob => 4.9], [gita => 3.9], [gita => 6.8], [diu => 3.0], ); ``` Now, we can do a sort on `@array` depending upon the value of `$array[$x]->[1]`! All we need is for each element of the array `@array` is to compare $a->[1] with $b->[1]. Then, if we do a reverse sort on it, the biggest element will be `$array[0]`. The name is `$array[0]->[0]` and the element is `$array->[0]->[1]`. ``` #! /usr/bin/env perl use strict; use warnings; use feature qw(say switch); my @array = ( [bob => 4.9], [gita => 3.9], [gita => 6.8], [diu => 3.0], ); @array = reverse sort mysort @array; say "$array[0]->[0] $array[0]->[1]"; sub mysort { $a->[1] <=> $b->[1]; } ``` And the output is: ``` gita 6.8. ``` You notice that link to [Perldoc's perllol](http://perldoc.perl.org/perlreftut.html)? I suggest you read it if you've never worked with Perl references before.
You got several good answers. Now a bad one (assuming you fix the decimal separator in the hash): ``` my %hash = (bob => "4.9", gita =>"3.9 , 6.8", diu => "3.0", ); my $max = (map{join" ",@$_[0,1]}sort{$b->[1]-$a->[1]}map{[$_,sort{$b-$a}split(/ , /,$hash{$_})]}keys%hash)[0]; print "$max\n"; ``` Output: ``` gita 6.8 ``` Never do this unless you're deliberately trying to golf and/or obfuscate it though.
424,629
*Акакию Акакиевичу забралось уже за пятьдесят лет. Стало-быть, если бы он и мог назваться молодым человеком, то разве только относительно, то есть в отношении к тому, кому уже было семьдесят лет.* Не могли бы Вы проверить, я правильно понимаю: *если бы он и мог назваться молодым человеком* - придаточное условия *то разве только относительно* - главное предложение (quasi "мог бы назваться молодым только относительно")? Спасибо!
2016/06/17
[ "https://rus.stackexchange.com/questions/424629", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/177434/" ]
Вы в целом понимаете правильно и с чисто грамматических позиций вполне достаточно. Но семантика, тут не совсем обычная для современного языка. Если можно так выразиться, то это абсолютно-условное предложение, т. е. условие придаточного необходимое и достаточное, абсолютно достаточное, оно реально и возможно, а все наполнение усилительными частицами нужно ради соблюдения стиля. Другими словами, по Гоголю получается, что **ничто, кроме указанного условия, не мешает назвать Акакия Акакиевича молодым.** Сейчас бы эту мысль передали куда проще. *Его можно назвать молодым человеком по отношению к человеку старше его* - или что-то подобное. Без понимания всего этого трудно понять и тонкую иронию Гоголя. В современном языке конструкции подобные разбираемым, используются обычно для выражения только необходимого и допустимого, возможного, но не обязательно реализуемого условия. *Если бы я пошел гулять в парк, то разве только на час* - совершенно не очевидно, что говорящий вообще пошел бы туда, он утверждает, что максимальное время его гипотетической прогулки - час. Возможно, с подобным изменением подразумеваемой семантики фразы и связаны ваши сомнения в её грамматике.
Акакию Акакиевичу забралось уже за пятьдесят лет. Стало-быть, если бы он и мог назваться молодым человеком, **то (мог бы называться) разве только относительно**, то есть в отношении к тому, кому уже было семьдесят лет. Да, главное предложение является неполным, содержание восстанавливается из предыдущего текста.
1,208,381
I am wiring a startup script JavaScript function on Page\_Load to fire like so: ``` ScriptManager.RegisterStartupScript(Me, GetType(Page), "page_init", "page_init();", True) ``` This function calls a couple of different functions to setup the page. One of those functions checks the `document.readyState` and makes sure it's `"complete"`. This deals with images and I want to make sure everything has been fully rendered. ``` if (document.readyState == "complete") { ``` Everything works fine, until I need to write a byte array to the outputstream (using either `Response.BinaryWrite` or `Response.OutputStream.Write()` to give a file to a user. After that, the `document.readyState` is always "interactive", until I navigate off of the page and back. I have even used a `setTimeout(myFunction, 1000);` call if `document.readyState` isn't complete to recursively call the function until it is complete. It never reaches "complete". I have researched this myself for quite sometime, and cannot figure out this behavior. Any ideas as to how this is happening?
2009/07/30
[ "https://Stackoverflow.com/questions/1208381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37064/" ]
In order for the ReadyState to flip over to Complete, the server side has to terminate the connection. If you look at your code you probably aren't calling Response.End AFTER the BinaryWrite or WriteToStream method. This is required in order to flush the response and alert the client that everything has been transferred. Note that you can still process data server side after making the Response.End call, you just can't send any more data to the client. A good example of how to do this properly is page 171 of Mastering ASP.Net with C# by A. Russell Jones ([google preview here](http://books.google.com/books?id=hWzFhJFXadYC&pg=PA171&lpg=PA171&dq=response.binarywrite+terminate+connection&source=bl&ots=dNhh9z-RND&sig=YOUiAnCS7-Xl7Oj5_pW3TYE1Asc&hl=en&ei=GJd3StncF9Xktgf1pdCWCQ&sa=X&oi=book_result&ct=result&resnum=5#v=onepage&q=response.binarywrite%20terminate%20connection&f=false)). The nut of it is that you should create your stream, read it into the Byte Array, close the stream, then do a BinaryWrite, and finally call Response.End.
Have you tried calling `Response.Close()` instead of or before `Response.End()`? After comparing them in Reflector, it would appear the two are different.
1,208,381
I am wiring a startup script JavaScript function on Page\_Load to fire like so: ``` ScriptManager.RegisterStartupScript(Me, GetType(Page), "page_init", "page_init();", True) ``` This function calls a couple of different functions to setup the page. One of those functions checks the `document.readyState` and makes sure it's `"complete"`. This deals with images and I want to make sure everything has been fully rendered. ``` if (document.readyState == "complete") { ``` Everything works fine, until I need to write a byte array to the outputstream (using either `Response.BinaryWrite` or `Response.OutputStream.Write()` to give a file to a user. After that, the `document.readyState` is always "interactive", until I navigate off of the page and back. I have even used a `setTimeout(myFunction, 1000);` call if `document.readyState` isn't complete to recursively call the function until it is complete. It never reaches "complete". I have researched this myself for quite sometime, and cannot figure out this behavior. Any ideas as to how this is happening?
2009/07/30
[ "https://Stackoverflow.com/questions/1208381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37064/" ]
In order for the ReadyState to flip over to Complete, the server side has to terminate the connection. If you look at your code you probably aren't calling Response.End AFTER the BinaryWrite or WriteToStream method. This is required in order to flush the response and alert the client that everything has been transferred. Note that you can still process data server side after making the Response.End call, you just can't send any more data to the client. A good example of how to do this properly is page 171 of Mastering ASP.Net with C# by A. Russell Jones ([google preview here](http://books.google.com/books?id=hWzFhJFXadYC&pg=PA171&lpg=PA171&dq=response.binarywrite+terminate+connection&source=bl&ots=dNhh9z-RND&sig=YOUiAnCS7-Xl7Oj5_pW3TYE1Asc&hl=en&ei=GJd3StncF9Xktgf1pdCWCQ&sa=X&oi=book_result&ct=result&resnum=5#v=onepage&q=response.binarywrite%20terminate%20connection&f=false)). The nut of it is that you should create your stream, read it into the Byte Array, close the stream, then do a BinaryWrite, and finally call Response.End.
when writing directly into the stream, you should set the content-length http header to the correct size of the binary data you are sending. It might also be a problem with the content-type (multipart/...) which might confuse the browser.
1,208,381
I am wiring a startup script JavaScript function on Page\_Load to fire like so: ``` ScriptManager.RegisterStartupScript(Me, GetType(Page), "page_init", "page_init();", True) ``` This function calls a couple of different functions to setup the page. One of those functions checks the `document.readyState` and makes sure it's `"complete"`. This deals with images and I want to make sure everything has been fully rendered. ``` if (document.readyState == "complete") { ``` Everything works fine, until I need to write a byte array to the outputstream (using either `Response.BinaryWrite` or `Response.OutputStream.Write()` to give a file to a user. After that, the `document.readyState` is always "interactive", until I navigate off of the page and back. I have even used a `setTimeout(myFunction, 1000);` call if `document.readyState` isn't complete to recursively call the function until it is complete. It never reaches "complete". I have researched this myself for quite sometime, and cannot figure out this behavior. Any ideas as to how this is happening?
2009/07/30
[ "https://Stackoverflow.com/questions/1208381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37064/" ]
I just found out the issue is with an IFrame, which I apologize was a detail left out of the question. More information can be found [here](http://www.atalasoft.com/cs/blogs/jake/archive/2009/06/18/events-to-expect-when-dynamically-loading-iframes-in-javascript.aspx): > > IE (surprisingly gets my vote of > approval here) There is an > onreadystatechange event that fires > whenever the iFrame's readyState > property changes. That readyState > reflects where the download is in the > process. > > > Inline: When you initially set the src > value of the iFrame element, the > readyState changes to loading. When > the file has completely downloaded, > the readyState changes to interactive. > The big difference between IE and the > other browsers is that IE then changes > the readyState property to complete > when the page (or application) is > fully loaded and ready for the user. > > > Attachment: This behaves identically > to the Inline case of IE, **but the > readyState property never changes to > complete.** That wouldn't make much > sense, since the user has to manually > open the file by double-clicking on it > or opening it from some application. > > >
In order for the ReadyState to flip over to Complete, the server side has to terminate the connection. If you look at your code you probably aren't calling Response.End AFTER the BinaryWrite or WriteToStream method. This is required in order to flush the response and alert the client that everything has been transferred. Note that you can still process data server side after making the Response.End call, you just can't send any more data to the client. A good example of how to do this properly is page 171 of Mastering ASP.Net with C# by A. Russell Jones ([google preview here](http://books.google.com/books?id=hWzFhJFXadYC&pg=PA171&lpg=PA171&dq=response.binarywrite+terminate+connection&source=bl&ots=dNhh9z-RND&sig=YOUiAnCS7-Xl7Oj5_pW3TYE1Asc&hl=en&ei=GJd3StncF9Xktgf1pdCWCQ&sa=X&oi=book_result&ct=result&resnum=5#v=onepage&q=response.binarywrite%20terminate%20connection&f=false)). The nut of it is that you should create your stream, read it into the Byte Array, close the stream, then do a BinaryWrite, and finally call Response.End.
1,208,381
I am wiring a startup script JavaScript function on Page\_Load to fire like so: ``` ScriptManager.RegisterStartupScript(Me, GetType(Page), "page_init", "page_init();", True) ``` This function calls a couple of different functions to setup the page. One of those functions checks the `document.readyState` and makes sure it's `"complete"`. This deals with images and I want to make sure everything has been fully rendered. ``` if (document.readyState == "complete") { ``` Everything works fine, until I need to write a byte array to the outputstream (using either `Response.BinaryWrite` or `Response.OutputStream.Write()` to give a file to a user. After that, the `document.readyState` is always "interactive", until I navigate off of the page and back. I have even used a `setTimeout(myFunction, 1000);` call if `document.readyState` isn't complete to recursively call the function until it is complete. It never reaches "complete". I have researched this myself for quite sometime, and cannot figure out this behavior. Any ideas as to how this is happening?
2009/07/30
[ "https://Stackoverflow.com/questions/1208381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37064/" ]
I just found out the issue is with an IFrame, which I apologize was a detail left out of the question. More information can be found [here](http://www.atalasoft.com/cs/blogs/jake/archive/2009/06/18/events-to-expect-when-dynamically-loading-iframes-in-javascript.aspx): > > IE (surprisingly gets my vote of > approval here) There is an > onreadystatechange event that fires > whenever the iFrame's readyState > property changes. That readyState > reflects where the download is in the > process. > > > Inline: When you initially set the src > value of the iFrame element, the > readyState changes to loading. When > the file has completely downloaded, > the readyState changes to interactive. > The big difference between IE and the > other browsers is that IE then changes > the readyState property to complete > when the page (or application) is > fully loaded and ready for the user. > > > Attachment: This behaves identically > to the Inline case of IE, **but the > readyState property never changes to > complete.** That wouldn't make much > sense, since the user has to manually > open the file by double-clicking on it > or opening it from some application. > > >
Have you tried calling `Response.Close()` instead of or before `Response.End()`? After comparing them in Reflector, it would appear the two are different.
1,208,381
I am wiring a startup script JavaScript function on Page\_Load to fire like so: ``` ScriptManager.RegisterStartupScript(Me, GetType(Page), "page_init", "page_init();", True) ``` This function calls a couple of different functions to setup the page. One of those functions checks the `document.readyState` and makes sure it's `"complete"`. This deals with images and I want to make sure everything has been fully rendered. ``` if (document.readyState == "complete") { ``` Everything works fine, until I need to write a byte array to the outputstream (using either `Response.BinaryWrite` or `Response.OutputStream.Write()` to give a file to a user. After that, the `document.readyState` is always "interactive", until I navigate off of the page and back. I have even used a `setTimeout(myFunction, 1000);` call if `document.readyState` isn't complete to recursively call the function until it is complete. It never reaches "complete". I have researched this myself for quite sometime, and cannot figure out this behavior. Any ideas as to how this is happening?
2009/07/30
[ "https://Stackoverflow.com/questions/1208381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37064/" ]
I just found out the issue is with an IFrame, which I apologize was a detail left out of the question. More information can be found [here](http://www.atalasoft.com/cs/blogs/jake/archive/2009/06/18/events-to-expect-when-dynamically-loading-iframes-in-javascript.aspx): > > IE (surprisingly gets my vote of > approval here) There is an > onreadystatechange event that fires > whenever the iFrame's readyState > property changes. That readyState > reflects where the download is in the > process. > > > Inline: When you initially set the src > value of the iFrame element, the > readyState changes to loading. When > the file has completely downloaded, > the readyState changes to interactive. > The big difference between IE and the > other browsers is that IE then changes > the readyState property to complete > when the page (or application) is > fully loaded and ready for the user. > > > Attachment: This behaves identically > to the Inline case of IE, **but the > readyState property never changes to > complete.** That wouldn't make much > sense, since the user has to manually > open the file by double-clicking on it > or opening it from some application. > > >
when writing directly into the stream, you should set the content-length http header to the correct size of the binary data you are sending. It might also be a problem with the content-type (multipart/...) which might confuse the browser.
28,104,439
i have this code. and i have no idea why the while loop is not working. i can't retrieve the data from course db. please help **i tried everything but i cant figure out how.** ``` if(isset($_POST['enroll'])){ $n = 0; foreach($_POST['trainings'] as $textbox){ $strpicture = $_POST['strpicture'][$n]; $stridnumber = $_POST['stridnumber'][$n]; $strfullname = $_POST['strfullname'][$n]; $strtraining =$textbox; //Add Query to Training Masterlist $AddQuery ="INSERT INTO tms_ml (strpicture,stridnumber,strfullname,strtraining) VALUES ('$strpicture','$stridnumber','$strfullname','$strtraining')"; mysql_query($AddQuery, $con); $strcoursestat="OPEN"; //query for training and status training $SearchCourseQuery = "SELECT strtraining FROM course WHERE strtraining like '%".$strtraining."%' AND strcoursestat like '%".$strcoursestat."%'"; $resultcoursequery =mysql_query($SearchCourseQuery); require("dbc.php"); //retrieve data from Course DB while($record = mysql_fetch_array($resultcoursequery)){ //this is echo $sessionnum= $record['strsessnum']; // the part //not working }; $countcourse=mysql_num_rows($resultcoursequery); if($countcourse==0){ echo '</br>' . $strtraining . ' ' . '<b>No Available Schedule for this Training</b>' .'</br>'; } else{ echo '</br>' . $strtraining . ' ' . '<b>Enrolled</b>' .'</br>'; //Add to Training Session $test="ab"; $AddtoSession ="INSERT INTO trn_session(strsessnum)VALUES('$sessionnum')"; mysql_query($AddtoSession, $con); }//else if count $n++; } // for each ``` **EDITED:** hi guys re create my SEARCH QUERY ($SearchCourseQuery) and it Works Fine now. ``` "SELECT * FROM course where strtraining = '$strtraining' AND strcoursestat = '$strcoursestat'"; ``` thank you all for the help!
2015/01/23
[ "https://Stackoverflow.com/questions/28104439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4348561/" ]
You have a typo in your Insert statement: ``` INSERT INTO tms_ml (strpicture,stridnumber,strfullname,strtraining) VALUES ('$strpicture','$stridnumber',$strfullname','$strtraining') ``` Missing quote at `$strfullname`. ``` INSERT INTO tms_ml (strpicture,stridnumber,strfullname,strtraining) VALUES ('$strpicture','$stridnumber','$strfullname','$strtraining') ``` Besides that, the mysql\* extensions are deprecated and you are vulnerable to SQL injections. Consider to use `PDO` or the `mysqli*` extensions and prepared statements.
First off; a foreach in php has an 'index'; which could be determined like so: ``` foreach ($items as $key => $item) { } ``` The key is your index (can be named whatever you like) thought that would be a trick worth knowing for you... i.e you don't need to use the $n variable and increment it. Secondly: What is `mysql_fetch_array($resultcoursequery)` returning?
28,104,439
i have this code. and i have no idea why the while loop is not working. i can't retrieve the data from course db. please help **i tried everything but i cant figure out how.** ``` if(isset($_POST['enroll'])){ $n = 0; foreach($_POST['trainings'] as $textbox){ $strpicture = $_POST['strpicture'][$n]; $stridnumber = $_POST['stridnumber'][$n]; $strfullname = $_POST['strfullname'][$n]; $strtraining =$textbox; //Add Query to Training Masterlist $AddQuery ="INSERT INTO tms_ml (strpicture,stridnumber,strfullname,strtraining) VALUES ('$strpicture','$stridnumber','$strfullname','$strtraining')"; mysql_query($AddQuery, $con); $strcoursestat="OPEN"; //query for training and status training $SearchCourseQuery = "SELECT strtraining FROM course WHERE strtraining like '%".$strtraining."%' AND strcoursestat like '%".$strcoursestat."%'"; $resultcoursequery =mysql_query($SearchCourseQuery); require("dbc.php"); //retrieve data from Course DB while($record = mysql_fetch_array($resultcoursequery)){ //this is echo $sessionnum= $record['strsessnum']; // the part //not working }; $countcourse=mysql_num_rows($resultcoursequery); if($countcourse==0){ echo '</br>' . $strtraining . ' ' . '<b>No Available Schedule for this Training</b>' .'</br>'; } else{ echo '</br>' . $strtraining . ' ' . '<b>Enrolled</b>' .'</br>'; //Add to Training Session $test="ab"; $AddtoSession ="INSERT INTO trn_session(strsessnum)VALUES('$sessionnum')"; mysql_query($AddtoSession, $con); }//else if count $n++; } // for each ``` **EDITED:** hi guys re create my SEARCH QUERY ($SearchCourseQuery) and it Works Fine now. ``` "SELECT * FROM course where strtraining = '$strtraining' AND strcoursestat = '$strcoursestat'"; ``` thank you all for the help!
2015/01/23
[ "https://Stackoverflow.com/questions/28104439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4348561/" ]
You have a typo in your Insert statement: ``` INSERT INTO tms_ml (strpicture,stridnumber,strfullname,strtraining) VALUES ('$strpicture','$stridnumber',$strfullname','$strtraining') ``` Missing quote at `$strfullname`. ``` INSERT INTO tms_ml (strpicture,stridnumber,strfullname,strtraining) VALUES ('$strpicture','$stridnumber','$strfullname','$strtraining') ``` Besides that, the mysql\* extensions are deprecated and you are vulnerable to SQL injections. Consider to use `PDO` or the `mysqli*` extensions and prepared statements.
According to the documentation here. <http://php.net/manual/en/function.mysql-fetch-array.php> You need to add the result\_type: ``` while($record = mysql_fetch_array($resultcoursequery, MYSQL_BOTH)){ echo $sessionnum= $record['strsessnum']; }; ```
71,553,245
Is it possible to see other containers which are running in the same host from the intermediate containers which would be created by `Dockerfile`? I need to connect to my dockerized database, it is already up and running. From my `Dockerfile` How can I connect to it? is it possible or not? `postgres.docker-compose.yml` ============================= this is my `postgres.docker-compose.yml` which is the first container that I run it: ```yaml version: '3.7' services: postgres: image: postgres:13 env_file: - .postgres.env restart: always networks: - take-report networks: take-report: name: take-report ``` A simple container. Please note that I can connect to it outside of `Dockerfile` but I want to connect to this dockerized postgres from This `Dockerfile`: `Dockerfile` ============ ``` # Note: I had issues with npm ci, therefore I did it once in a temp Dockerfile and create a new base image with the installed 3rd party packages and I put this name for it: take-report:dep FROM take-report:dep as build_stage ARG DATABASE_URL ENV DATABASE_URL=$DATABASE_URL # README: Because WORKDIR is set in the take-report:dep I ignore to use it here again # WORKDIR /app COPY prisma ./prisma/ COPY . . RUN npx prisma generate RUN npm run build # Cannot connect to Database from here even due the Database_URL is correct. RUN echo $DATABASE_URL # error message: Error: P1001: Can't reach database server at `postgres`:`5432` RUN npm run prisma:dev RUN npm prune --production FROM node:16.14.0-alpine3.15 WORKDIR /app COPY --from=build_stage /app/node_modules ./node_modules COPY --from=build_stage /app/package*.json ./ COPY --from=build_stage /app/tsconfig*.json ./ COPY --from=build_stage /app/dist ./dist COPY --from=build_stage /app/dist/prisma ./prisma COPY --from=build_stage /app/prisma/schema.prisma ./prisma/schema.prisma # COPY --from=build_stage /app/prisma ./prisma EXPOSE $APP_PORT ``` `docker-compose.yml` ==================== ```yaml version: '3.7' services: take-report: image: take-report:v1 restart: unless-stopped build: context: . dockerfile: Dockerfile args: - DATABASE_URL ports: - ${APP_EXPOSED_PORT}:$APP_PORT env_file: - .env networks: - take-report - traefik_default labels: - "traefik.enable=true" command: npm run start:prod networks: traefik_default: external: true take-report: external: true ``` As you can see I put the `take-report` and `postgres` containers in the same network. In this way they can see each other. Note that the created container by `docker-compose.yml` file can see and connect to the `DATABASE_URL`. So I guess **all I need is to specify the intermediate containers' network that docker creates to build my custom image. In other word I want to some how tell docker to use which external network while building this custom image with written `Dockerfile`.** Is that possible? **In case that something was not clear please tell me to clarify it** Thanks regardless. Edit #1 - Add more info: ======================== I have to say that when I issued `docker-compose -f postgres.docker-compose.yml up` it will creates the `take-report` network for me and I can connect to it in the `docker-compose.yml`. The second info: `docker-compose.yml` can see the postgres because they're in the same network, I meant `take-report` network.
2022/03/21
[ "https://Stackoverflow.com/questions/71553245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8784518/" ]
To elaborate on the comments in the previous answer: This is our Postgres docker-compose.yml: ```yaml version: '3.9' services: db: image: postgres:latest restart: "no" container_name: MyDb volumes: - ./database:/var/lib/postgresql/data ports: - "8002:5432" environment: POSTGRES_PASSWORD: root POSTGRES_USER: root POSTGRES_DB: MyDb networks: my-net: ipv4_address: 172.30.0.12 networks: my-net: external: true name: my-net ``` The Host has a number of subdomains pointing to it and a Nginx proxyserver (also running in a container) is forwarding Db requests to port 5432 on ip 172.30.0.12. (Sorry for the summary. I am working on an article to explain this in more detail. But hope this helps so far)
In your first docker-compose you have the networks setup not as a external network. In the second docker-compose the network with the same name is setup as an external network. I don't know if that works. But you might make the first one also external. You could inspect the network to see of all containers (postgres and take-report) are in the same network. ```sh docker network inspect take-report ``` If you want to access postgres service from take-report service (which is in another docker-compose), you cannot use the service-name but have to go through the IP-address (at least, that's how I do it). So, specify IP addresses in the Services. They should appear on the docker network. Then you can try to access this IP address from intermediate containers. (Also, this I have not tested, but I can't see why this would not work)
71,553,245
Is it possible to see other containers which are running in the same host from the intermediate containers which would be created by `Dockerfile`? I need to connect to my dockerized database, it is already up and running. From my `Dockerfile` How can I connect to it? is it possible or not? `postgres.docker-compose.yml` ============================= this is my `postgres.docker-compose.yml` which is the first container that I run it: ```yaml version: '3.7' services: postgres: image: postgres:13 env_file: - .postgres.env restart: always networks: - take-report networks: take-report: name: take-report ``` A simple container. Please note that I can connect to it outside of `Dockerfile` but I want to connect to this dockerized postgres from This `Dockerfile`: `Dockerfile` ============ ``` # Note: I had issues with npm ci, therefore I did it once in a temp Dockerfile and create a new base image with the installed 3rd party packages and I put this name for it: take-report:dep FROM take-report:dep as build_stage ARG DATABASE_URL ENV DATABASE_URL=$DATABASE_URL # README: Because WORKDIR is set in the take-report:dep I ignore to use it here again # WORKDIR /app COPY prisma ./prisma/ COPY . . RUN npx prisma generate RUN npm run build # Cannot connect to Database from here even due the Database_URL is correct. RUN echo $DATABASE_URL # error message: Error: P1001: Can't reach database server at `postgres`:`5432` RUN npm run prisma:dev RUN npm prune --production FROM node:16.14.0-alpine3.15 WORKDIR /app COPY --from=build_stage /app/node_modules ./node_modules COPY --from=build_stage /app/package*.json ./ COPY --from=build_stage /app/tsconfig*.json ./ COPY --from=build_stage /app/dist ./dist COPY --from=build_stage /app/dist/prisma ./prisma COPY --from=build_stage /app/prisma/schema.prisma ./prisma/schema.prisma # COPY --from=build_stage /app/prisma ./prisma EXPOSE $APP_PORT ``` `docker-compose.yml` ==================== ```yaml version: '3.7' services: take-report: image: take-report:v1 restart: unless-stopped build: context: . dockerfile: Dockerfile args: - DATABASE_URL ports: - ${APP_EXPOSED_PORT}:$APP_PORT env_file: - .env networks: - take-report - traefik_default labels: - "traefik.enable=true" command: npm run start:prod networks: traefik_default: external: true take-report: external: true ``` As you can see I put the `take-report` and `postgres` containers in the same network. In this way they can see each other. Note that the created container by `docker-compose.yml` file can see and connect to the `DATABASE_URL`. So I guess **all I need is to specify the intermediate containers' network that docker creates to build my custom image. In other word I want to some how tell docker to use which external network while building this custom image with written `Dockerfile`.** Is that possible? **In case that something was not clear please tell me to clarify it** Thanks regardless. Edit #1 - Add more info: ======================== I have to say that when I issued `docker-compose -f postgres.docker-compose.yml up` it will creates the `take-report` network for me and I can connect to it in the `docker-compose.yml`. The second info: `docker-compose.yml` can see the postgres because they're in the same network, I meant `take-report` network.
2022/03/21
[ "https://Stackoverflow.com/questions/71553245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8784518/" ]
To elaborate on the comments in the previous answer: This is our Postgres docker-compose.yml: ```yaml version: '3.9' services: db: image: postgres:latest restart: "no" container_name: MyDb volumes: - ./database:/var/lib/postgresql/data ports: - "8002:5432" environment: POSTGRES_PASSWORD: root POSTGRES_USER: root POSTGRES_DB: MyDb networks: my-net: ipv4_address: 172.30.0.12 networks: my-net: external: true name: my-net ``` The Host has a number of subdomains pointing to it and a Nginx proxyserver (also running in a container) is forwarding Db requests to port 5432 on ip 172.30.0.12. (Sorry for the summary. I am working on an article to explain this in more detail. But hope this helps so far)
> > Is it possible to see other containers which are running in the same host from the intermediate containers which would be created by Dockerfile? > > > No. (\*) The biggest technical challenge is that image builds run on the ["default bridge network"](https://docs.docker.com/network/bridge/#use-the-default-bridge-network) where every [Compose network](https://docs.docker.com/compose/networking/) is a ["user-defined bridge network"](https://docs.docker.com/network/bridge/#manage-a-user-defined-bridge). Since the image builds aren't in the same network as the thing you're trying to connect to, they won't be able to connect. You also claim the database is already running. Compose doesn't have any primitives to guarantee that image builds happen in any particular order. So even if the application `depends_on: [the-database]` there's no guarantee the database will be running before the application image is built. > > I need to connect to my dockerized database, it is already up and running. From my `Dockerfile` How can I connect to it? is it possible or not? > > > This doesn't really make sense. Consider a binary like, say, `/usr/bin/psql`: even if you're connecting to different databases with different schemas and credentials, you don't need to rebuild the database client. In the same way, your Docker image shouldn't have "compiled in" the contents of any single database. Imagine running: ```sh # Set up the database and preload data docker-compose up -d db PGHOST=localhost PGPORT=5432 ./populate-db.sh # Build the image docker-compose build # Clean absolutely everything up docker-compose down docker-compose rm -v # Start over, with the prebuilt image but an empty database docker-compose up -d ``` Or, if this sequence sounds contrived, imagine `docker-compose push` the image to a registry and then running it on a different system that doesn't have the database set up yet. The usual approach to this is to run any sort of content generators outside of your image build process and check them into your source tree. If you need to run tasks like migrations you can run them in an entrypoint wrapper script, as the container starts up but before it actually executes the server; [How do you perform Django database migrations when using Docker-Compose?](https://stackoverflow.com/questions/33992867/how-do-you-perform-django-database-migrations-when-using-docker-compose) has some options that are largely not framework-specific. (\*) On a MacOS or Windows host, you might be able to use the magic `host.docker.internal` host name to call back out to the host, which would then be able to reach other containers via their published `ports:`. On a Linux system, building the image on the host network would be a different hack to achieve this. In addition to this not being portable across Docker installations, the other considerations above still apply.
2,322
Consider this situation. I post a legitimate and correct answer to a question and receive a few upvotes. Then the OP realizes that's not what they wanted to ask, and significantly rewrites the question, rendering my answer irrelevant and useless. Ideally the OP would comment on every answer saying "check my edit" but *some people don't know to do that*. This leaves two possibly bad situations: 1. I never know, the answer stays, and the votes don't reflect the usefulness of the answer anymore. 2. All of a sudden I get an influx of downvotes because my answer isn't helpful anymore. *If I'm checking and notice my rep has dropped*, I come back after the fact, edit the answer, and bring it back to the original quality. This is great, but 9 times out of 10, the downvoters never come back and notice the answer has been edited. It might get more upvotes, but it still doesn't reflect the true value of the answer. If we can get notified when the OP gets edited, we can nip it in the bud and go back to edit our answers to match - thus maintaining the quality of the answers on SO.
2009/07/04
[ "https://meta.stackexchange.com/questions/2322", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/44853/" ]
An alternative would be to show clearly that particular answers were written **before** the original question was edited, for example: > > This answer is for a previous version of this question. *Click here* to > notify the user if their answer is no longer relevant. > > > Another option is to display an alert to the downvoter when downvoting an out of date answer. I think the majority of SO users would be glad to edit their answers if they're no longer relevant to an edited question, but without notification it's extremely difficult to check before getting downvoted.
This seems like a highly requested feature, and still doesn't have enough ROI. **Why?** 1. **We like notification, not spam**. which one of those two is more likely to happen? well it depends on the quality of the feature. Users with thousands of posts may have to either spend a lot of time to manage subscriptions, or just get spam. 2. **Users should "play" fair** - changing a major thing in your post after you got upvoted answers can be rude. You can never avoid users from "abusing" a system. 3. **The core functionality is mostly achieved through other activities** i.e by the first down vote or comment. it's clear that it's not fair, and the down voter may never return to change his vote regardless of what you do. if it's a highly ranked post, most chances that you will be know that there was a change quick enough.
2,322
Consider this situation. I post a legitimate and correct answer to a question and receive a few upvotes. Then the OP realizes that's not what they wanted to ask, and significantly rewrites the question, rendering my answer irrelevant and useless. Ideally the OP would comment on every answer saying "check my edit" but *some people don't know to do that*. This leaves two possibly bad situations: 1. I never know, the answer stays, and the votes don't reflect the usefulness of the answer anymore. 2. All of a sudden I get an influx of downvotes because my answer isn't helpful anymore. *If I'm checking and notice my rep has dropped*, I come back after the fact, edit the answer, and bring it back to the original quality. This is great, but 9 times out of 10, the downvoters never come back and notice the answer has been edited. It might get more upvotes, but it still doesn't reflect the true value of the answer. If we can get notified when the OP gets edited, we can nip it in the bud and go back to edit our answers to match - thus maintaining the quality of the answers on SO.
2009/07/04
[ "https://meta.stackexchange.com/questions/2322", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/44853/" ]
An alternative would be to show clearly that particular answers were written **before** the original question was edited, for example: > > This answer is for a previous version of this question. *Click here* to > notify the user if their answer is no longer relevant. > > > Another option is to display an alert to the downvoter when downvoting an out of date answer. I think the majority of SO users would be glad to edit their answers if they're no longer relevant to an edited question, but without notification it's extremely difficult to check before getting downvoted.
Simply sending everyone a reminder each time a question is updated, will be a cure that is worse than the original problem. Most of the time I answer a question, it gets edited later (often several times). And of these edits, 9 out of 10 will not invalidate the existing answers. All in all I agree that it is annoying to see your answer being invalidated from time to time, but receiving tons of notifications over words put between `backticks` would be more annoying for me. Hence I suggest we don't simply send notifications when the question is updated, but either do something more advanced, or don't do anything at all. Here are two options I could think of: 1. **Major edit indication**: Next to the edit summary, make a checkbox indicating a 'Major Edit', the reversed of what they have in wikipedia. When a major edit is made, the relevant users get a notification. 2. **Targeted advice**: Try to detect whether an edit is likely to require different answers. If this is detected, briefly show text to the user with the hint to notify those whose answer is now outdated.
2,322
Consider this situation. I post a legitimate and correct answer to a question and receive a few upvotes. Then the OP realizes that's not what they wanted to ask, and significantly rewrites the question, rendering my answer irrelevant and useless. Ideally the OP would comment on every answer saying "check my edit" but *some people don't know to do that*. This leaves two possibly bad situations: 1. I never know, the answer stays, and the votes don't reflect the usefulness of the answer anymore. 2. All of a sudden I get an influx of downvotes because my answer isn't helpful anymore. *If I'm checking and notice my rep has dropped*, I come back after the fact, edit the answer, and bring it back to the original quality. This is great, but 9 times out of 10, the downvoters never come back and notice the answer has been edited. It might get more upvotes, but it still doesn't reflect the true value of the answer. If we can get notified when the OP gets edited, we can nip it in the bud and go back to edit our answers to match - thus maintaining the quality of the answers on SO.
2009/07/04
[ "https://meta.stackexchange.com/questions/2322", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/44853/" ]
I've had similar [experiences to Cletus](https://meta.stackexchange.com/questions/2322/notify-us-when-the-question-has-been-edited-after-posting-an-answer/2324#2324) where the answer I posted was the first and correct, but over time the question changes and all of a sudden you can get hammered because you were unable to keep up with the changing requirements of the question. This can definitely get very annoying. This would also be incredible useful for those of us who monitor questions to close. If this was combined with the ability to remove a close vote, it could allow us to vote a question to close when it doesn't meet standards, and when it is revised, we would get notified and be able to then remove our close vote if we felt it was an improvement.
I currently have a large number of posts bookmarked so I can monitor them. In each case, I have posted an answer based on what I thought the OP wanted. However, the question was interpreted differently by other posters. Of course, I could have waited for the OP to clarify the question before answering. However, I have found that I have a high rate of success correctly interpreting the original meaning. And I may not be around when, if ever, the question is clarified. I used to star them and use the favorites tab to monitor them, but I really don't want these cluttering up my *real* favorites. Using browser bookmarks means I have to manually follow up which is a pain. Having the ability to subscribe to posts is probably redundant since that is effectively what favorites is, but I'd really like to have some mechanism to monitor activity on questions I've answered (without having to star them). **Possible Solution** Maybe the answer tab could work similar to the favorites tab so that the tab and individual answers get highlighted when there is new activity on the question. I don't think notification of favorites activity goes to the inbox so it wouldn't be *spam*. **Another Possible Solution** Add the ability to categorize favorites. There is [a feature request](https://meta.stackexchange.com/questions/75944/favorites-improvements) that suggests several improvements to favorites. One could use favorites to receive notification on any question and then use personal tags to keep those favorites organized. I think this solution would *kill two requests with one feature*.
2,322
Consider this situation. I post a legitimate and correct answer to a question and receive a few upvotes. Then the OP realizes that's not what they wanted to ask, and significantly rewrites the question, rendering my answer irrelevant and useless. Ideally the OP would comment on every answer saying "check my edit" but *some people don't know to do that*. This leaves two possibly bad situations: 1. I never know, the answer stays, and the votes don't reflect the usefulness of the answer anymore. 2. All of a sudden I get an influx of downvotes because my answer isn't helpful anymore. *If I'm checking and notice my rep has dropped*, I come back after the fact, edit the answer, and bring it back to the original quality. This is great, but 9 times out of 10, the downvoters never come back and notice the answer has been edited. It might get more upvotes, but it still doesn't reflect the true value of the answer. If we can get notified when the OP gets edited, we can nip it in the bud and go back to edit our answers to match - thus maintaining the quality of the answers on SO.
2009/07/04
[ "https://meta.stackexchange.com/questions/2322", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/44853/" ]
An alternative would be to show clearly that particular answers were written **before** the original question was edited, for example: > > This answer is for a previous version of this question. *Click here* to > notify the user if their answer is no longer relevant. > > > Another option is to display an alert to the downvoter when downvoting an out of date answer. I think the majority of SO users would be glad to edit their answers if they're no longer relevant to an edited question, but without notification it's extremely difficult to check before getting downvoted.
Wrong solution because you are trying to address the wrong problem. Changing the question out from under good answers is simply **rude** and should be discouraged. I wrote an [expansive version of this argument](https://meta.stackexchange.com/questions/49821/when-editing-the-question-option-to-notify-all-answer-authors/49831#49831) on [a later question](https://meta.stackexchange.com/questions/49821/when-editing-the-question-option-to-notify-all-answer-authors).
2,322
Consider this situation. I post a legitimate and correct answer to a question and receive a few upvotes. Then the OP realizes that's not what they wanted to ask, and significantly rewrites the question, rendering my answer irrelevant and useless. Ideally the OP would comment on every answer saying "check my edit" but *some people don't know to do that*. This leaves two possibly bad situations: 1. I never know, the answer stays, and the votes don't reflect the usefulness of the answer anymore. 2. All of a sudden I get an influx of downvotes because my answer isn't helpful anymore. *If I'm checking and notice my rep has dropped*, I come back after the fact, edit the answer, and bring it back to the original quality. This is great, but 9 times out of 10, the downvoters never come back and notice the answer has been edited. It might get more upvotes, but it still doesn't reflect the true value of the answer. If we can get notified when the OP gets edited, we can nip it in the bud and go back to edit our answers to match - thus maintaining the quality of the answers on SO.
2009/07/04
[ "https://meta.stackexchange.com/questions/2322", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/44853/" ]
This is a good suggestion. I've been downvoted before simply because the question was edited changing the validity of my answer. Most people tend to realize this is whats happened but some don't. It would be good if there were such a notification so you could modify or delete your answer, as appropriate.
I've had similar [experiences to Cletus](https://meta.stackexchange.com/questions/2322/notify-us-when-the-question-has-been-edited-after-posting-an-answer/2324#2324) where the answer I posted was the first and correct, but over time the question changes and all of a sudden you can get hammered because you were unable to keep up with the changing requirements of the question. This can definitely get very annoying. This would also be incredible useful for those of us who monitor questions to close. If this was combined with the ability to remove a close vote, it could allow us to vote a question to close when it doesn't meet standards, and when it is revised, we would get notified and be able to then remove our close vote if we felt it was an improvement.
2,322
Consider this situation. I post a legitimate and correct answer to a question and receive a few upvotes. Then the OP realizes that's not what they wanted to ask, and significantly rewrites the question, rendering my answer irrelevant and useless. Ideally the OP would comment on every answer saying "check my edit" but *some people don't know to do that*. This leaves two possibly bad situations: 1. I never know, the answer stays, and the votes don't reflect the usefulness of the answer anymore. 2. All of a sudden I get an influx of downvotes because my answer isn't helpful anymore. *If I'm checking and notice my rep has dropped*, I come back after the fact, edit the answer, and bring it back to the original quality. This is great, but 9 times out of 10, the downvoters never come back and notice the answer has been edited. It might get more upvotes, but it still doesn't reflect the true value of the answer. If we can get notified when the OP gets edited, we can nip it in the bud and go back to edit our answers to match - thus maintaining the quality of the answers on SO.
2009/07/04
[ "https://meta.stackexchange.com/questions/2322", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/44853/" ]
An alternative would be to show clearly that particular answers were written **before** the original question was edited, for example: > > This answer is for a previous version of this question. *Click here* to > notify the user if their answer is no longer relevant. > > > Another option is to display an alert to the downvoter when downvoting an out of date answer. I think the majority of SO users would be glad to edit their answers if they're no longer relevant to an edited question, but without notification it's extremely difficult to check before getting downvoted.
I currently have a large number of posts bookmarked so I can monitor them. In each case, I have posted an answer based on what I thought the OP wanted. However, the question was interpreted differently by other posters. Of course, I could have waited for the OP to clarify the question before answering. However, I have found that I have a high rate of success correctly interpreting the original meaning. And I may not be around when, if ever, the question is clarified. I used to star them and use the favorites tab to monitor them, but I really don't want these cluttering up my *real* favorites. Using browser bookmarks means I have to manually follow up which is a pain. Having the ability to subscribe to posts is probably redundant since that is effectively what favorites is, but I'd really like to have some mechanism to monitor activity on questions I've answered (without having to star them). **Possible Solution** Maybe the answer tab could work similar to the favorites tab so that the tab and individual answers get highlighted when there is new activity on the question. I don't think notification of favorites activity goes to the inbox so it wouldn't be *spam*. **Another Possible Solution** Add the ability to categorize favorites. There is [a feature request](https://meta.stackexchange.com/questions/75944/favorites-improvements) that suggests several improvements to favorites. One could use favorites to receive notification on any question and then use personal tags to keep those favorites organized. I think this solution would *kill two requests with one feature*.
2,322
Consider this situation. I post a legitimate and correct answer to a question and receive a few upvotes. Then the OP realizes that's not what they wanted to ask, and significantly rewrites the question, rendering my answer irrelevant and useless. Ideally the OP would comment on every answer saying "check my edit" but *some people don't know to do that*. This leaves two possibly bad situations: 1. I never know, the answer stays, and the votes don't reflect the usefulness of the answer anymore. 2. All of a sudden I get an influx of downvotes because my answer isn't helpful anymore. *If I'm checking and notice my rep has dropped*, I come back after the fact, edit the answer, and bring it back to the original quality. This is great, but 9 times out of 10, the downvoters never come back and notice the answer has been edited. It might get more upvotes, but it still doesn't reflect the true value of the answer. If we can get notified when the OP gets edited, we can nip it in the bud and go back to edit our answers to match - thus maintaining the quality of the answers on SO.
2009/07/04
[ "https://meta.stackexchange.com/questions/2322", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/44853/" ]
I've had similar [experiences to Cletus](https://meta.stackexchange.com/questions/2322/notify-us-when-the-question-has-been-edited-after-posting-an-answer/2324#2324) where the answer I posted was the first and correct, but over time the question changes and all of a sudden you can get hammered because you were unable to keep up with the changing requirements of the question. This can definitely get very annoying. This would also be incredible useful for those of us who monitor questions to close. If this was combined with the ability to remove a close vote, it could allow us to vote a question to close when it doesn't meet standards, and when it is revised, we would get notified and be able to then remove our close vote if we felt it was an improvement.
This seems like a highly requested feature, and still doesn't have enough ROI. **Why?** 1. **We like notification, not spam**. which one of those two is more likely to happen? well it depends on the quality of the feature. Users with thousands of posts may have to either spend a lot of time to manage subscriptions, or just get spam. 2. **Users should "play" fair** - changing a major thing in your post after you got upvoted answers can be rude. You can never avoid users from "abusing" a system. 3. **The core functionality is mostly achieved through other activities** i.e by the first down vote or comment. it's clear that it's not fair, and the down voter may never return to change his vote regardless of what you do. if it's a highly ranked post, most chances that you will be know that there was a change quick enough.
2,322
Consider this situation. I post a legitimate and correct answer to a question and receive a few upvotes. Then the OP realizes that's not what they wanted to ask, and significantly rewrites the question, rendering my answer irrelevant and useless. Ideally the OP would comment on every answer saying "check my edit" but *some people don't know to do that*. This leaves two possibly bad situations: 1. I never know, the answer stays, and the votes don't reflect the usefulness of the answer anymore. 2. All of a sudden I get an influx of downvotes because my answer isn't helpful anymore. *If I'm checking and notice my rep has dropped*, I come back after the fact, edit the answer, and bring it back to the original quality. This is great, but 9 times out of 10, the downvoters never come back and notice the answer has been edited. It might get more upvotes, but it still doesn't reflect the true value of the answer. If we can get notified when the OP gets edited, we can nip it in the bud and go back to edit our answers to match - thus maintaining the quality of the answers on SO.
2009/07/04
[ "https://meta.stackexchange.com/questions/2322", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/44853/" ]
Wrong solution because you are trying to address the wrong problem. Changing the question out from under good answers is simply **rude** and should be discouraged. I wrote an [expansive version of this argument](https://meta.stackexchange.com/questions/49821/when-editing-the-question-option-to-notify-all-answer-authors/49831#49831) on [a later question](https://meta.stackexchange.com/questions/49821/when-editing-the-question-option-to-notify-all-answer-authors).
This seems like a highly requested feature, and still doesn't have enough ROI. **Why?** 1. **We like notification, not spam**. which one of those two is more likely to happen? well it depends on the quality of the feature. Users with thousands of posts may have to either spend a lot of time to manage subscriptions, or just get spam. 2. **Users should "play" fair** - changing a major thing in your post after you got upvoted answers can be rude. You can never avoid users from "abusing" a system. 3. **The core functionality is mostly achieved through other activities** i.e by the first down vote or comment. it's clear that it's not fair, and the down voter may never return to change his vote regardless of what you do. if it's a highly ranked post, most chances that you will be know that there was a change quick enough.
2,322
Consider this situation. I post a legitimate and correct answer to a question and receive a few upvotes. Then the OP realizes that's not what they wanted to ask, and significantly rewrites the question, rendering my answer irrelevant and useless. Ideally the OP would comment on every answer saying "check my edit" but *some people don't know to do that*. This leaves two possibly bad situations: 1. I never know, the answer stays, and the votes don't reflect the usefulness of the answer anymore. 2. All of a sudden I get an influx of downvotes because my answer isn't helpful anymore. *If I'm checking and notice my rep has dropped*, I come back after the fact, edit the answer, and bring it back to the original quality. This is great, but 9 times out of 10, the downvoters never come back and notice the answer has been edited. It might get more upvotes, but it still doesn't reflect the true value of the answer. If we can get notified when the OP gets edited, we can nip it in the bud and go back to edit our answers to match - thus maintaining the quality of the answers on SO.
2009/07/04
[ "https://meta.stackexchange.com/questions/2322", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/44853/" ]
An alternative would be to show clearly that particular answers were written **before** the original question was edited, for example: > > This answer is for a previous version of this question. *Click here* to > notify the user if their answer is no longer relevant. > > > Another option is to display an alert to the downvoter when downvoting an out of date answer. I think the majority of SO users would be glad to edit their answers if they're no longer relevant to an edited question, but without notification it's extremely difficult to check before getting downvoted.
We are not going to implement automatic notifications on edits after you post an answer. If you would like to opt-in to notifications for this, please use the [follow post](https://meta.stackexchange.com/q/345661/51) feature.
2,322
Consider this situation. I post a legitimate and correct answer to a question and receive a few upvotes. Then the OP realizes that's not what they wanted to ask, and significantly rewrites the question, rendering my answer irrelevant and useless. Ideally the OP would comment on every answer saying "check my edit" but *some people don't know to do that*. This leaves two possibly bad situations: 1. I never know, the answer stays, and the votes don't reflect the usefulness of the answer anymore. 2. All of a sudden I get an influx of downvotes because my answer isn't helpful anymore. *If I'm checking and notice my rep has dropped*, I come back after the fact, edit the answer, and bring it back to the original quality. This is great, but 9 times out of 10, the downvoters never come back and notice the answer has been edited. It might get more upvotes, but it still doesn't reflect the true value of the answer. If we can get notified when the OP gets edited, we can nip it in the bud and go back to edit our answers to match - thus maintaining the quality of the answers on SO.
2009/07/04
[ "https://meta.stackexchange.com/questions/2322", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/44853/" ]
This is a good suggestion. I've been downvoted before simply because the question was edited changing the validity of my answer. Most people tend to realize this is whats happened but some don't. It would be good if there were such a notification so you could modify or delete your answer, as appropriate.
We are not going to implement automatic notifications on edits after you post an answer. If you would like to opt-in to notifications for this, please use the [follow post](https://meta.stackexchange.com/q/345661/51) feature.
15,347,973
I have a list of length 30,000 with data frames in it that have a x and y column. The data frame is sparse, so not each value of x exists. All x values are between 1 and 200. I want to convert this list to a single data frame which has for each possible x value a column and each row should represent all y values of a list entry (if a x value does not exist, the entry should be 0). I have a solution which works (see below) but it's very, very slow and I think there must be a faster (and probably also more elegant way) to do so. My current solution (which is slow) is: ``` dat <- matrix(numeric(0), 30000, 200) for(i in seq(along=whaledatas)) { for(j in row.names(whaledatas[[i]])) dat[i, whaledatas[[i]][j,"x"]] <- whaledatas[[i]][j,"y"] } dfData <- data.frame(dat, files$label) dfData[is.na(dfData)] <- 0 ```
2013/03/11
[ "https://Stackoverflow.com/questions/15347973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55070/" ]
Here's an answer that takes reasonable amount of time: ``` # function to create dummy data my_sampler <- function(idx) { x <- sample(200, sample(50:100, 1)) y <- sample(length(x)) data.frame(x,y) } # create list of 30000 data.frames in.d <- lapply(1:30000, function(x) my_sampler(x)) ``` **Solution:** Using `data.table` ``` require(data.table) system.time(out.d <- do.call(rbind, lapply(in.d, function(x) { setattr(x, 'class', c("data.table", "data.frame")) # mnel's suggestion setkey(x, "x") x[J(1:200)]$y }))) # user system elapsed # 47.111 0.343 51.283 > dim(out.d) # [1] 30000 200 # final step: replace NA with 0 out.d[is.na(out.d)] <- 0 ``` **Edit:** As @regetz shows, assigning final matrix and then replacing selected entries where x occurs with y-values is clever! A small variation of @regetz's solution: ``` m <- matrix(0.0, nrow=30000, ncol=200) system.time(for( i in 1:nrow(m)) { m[i, in.d[[i]][["x"]]] <- in.d[[i]][["y"]] }) # user system elapsed # 1.496 0.003 1.511 ``` This seems to be even faster than @regetz's (shown below): ``` > system.time(dat <- datify(in.d, xmax=200)) # user system elapsed # 2.966 0.015 2.993 ```
I would use a `data.table` solution , something like this : ``` whaledatas <- lapply(1:30000,function(x)data.frame(x=1:200,y=1:200)) library(data.table) dtt <- rbindlist(whaledatas) ```
15,347,973
I have a list of length 30,000 with data frames in it that have a x and y column. The data frame is sparse, so not each value of x exists. All x values are between 1 and 200. I want to convert this list to a single data frame which has for each possible x value a column and each row should represent all y values of a list entry (if a x value does not exist, the entry should be 0). I have a solution which works (see below) but it's very, very slow and I think there must be a faster (and probably also more elegant way) to do so. My current solution (which is slow) is: ``` dat <- matrix(numeric(0), 30000, 200) for(i in seq(along=whaledatas)) { for(j in row.names(whaledatas[[i]])) dat[i, whaledatas[[i]][j,"x"]] <- whaledatas[[i]][j,"y"] } dfData <- data.frame(dat, files$label) dfData[is.na(dfData)] <- 0 ```
2013/03/11
[ "https://Stackoverflow.com/questions/15347973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55070/" ]
Here's an answer that takes reasonable amount of time: ``` # function to create dummy data my_sampler <- function(idx) { x <- sample(200, sample(50:100, 1)) y <- sample(length(x)) data.frame(x,y) } # create list of 30000 data.frames in.d <- lapply(1:30000, function(x) my_sampler(x)) ``` **Solution:** Using `data.table` ``` require(data.table) system.time(out.d <- do.call(rbind, lapply(in.d, function(x) { setattr(x, 'class', c("data.table", "data.frame")) # mnel's suggestion setkey(x, "x") x[J(1:200)]$y }))) # user system elapsed # 47.111 0.343 51.283 > dim(out.d) # [1] 30000 200 # final step: replace NA with 0 out.d[is.na(out.d)] <- 0 ``` **Edit:** As @regetz shows, assigning final matrix and then replacing selected entries where x occurs with y-values is clever! A small variation of @regetz's solution: ``` m <- matrix(0.0, nrow=30000, ncol=200) system.time(for( i in 1:nrow(m)) { m[i, in.d[[i]][["x"]]] <- in.d[[i]][["y"]] }) # user system elapsed # 1.496 0.003 1.511 ``` This seems to be even faster than @regetz's (shown below): ``` > system.time(dat <- datify(in.d, xmax=200)) # user system elapsed # 2.966 0.015 2.993 ```
First, here is a small example of a list of data frames: ``` # create some sample data whaledatas <- list( data.frame(x=1:3, y=11:13), data.frame(x=6:10, y=16:20) ) ``` I think this does the same thing as the `for` loop in the original question? ``` # combine into single data frame whaledatas.all <- do.call("rbind", whaledatas) # change this to 200! kept small here for illustration... XMAX <- 10 # create output matrix dat <- matrix(0.0, length(whaledatas), XMAX) # create index vector for dat rows i <- rep(1:length(whaledatas), sapply(whaledatas, nrow)) # populate dat dat[cbind(i, whaledatas.all[["x"]])] <- whaledatas.all[["y"]] ``` **Edit** The `rbind` gets horrendously slow as the number of the inputs increases. This version (wrapped in a function for convenience) avoids it, and runs much faster: ``` datify <- function(x, xmax=200) { dat <- matrix(0.0, length(x), xmax) for (i in seq_along(x)) { this.df <- x[[i]] coords <- cbind(rep(i, nrow(this.df)), this.df[["x"]]) dat[coords] <- this.df[["y"]] } dat } ``` Note that we started with all zeros in `dat`, so no need to fix that after the fact... ``` > datify(whaledatas, xmax=10) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 11 12 13 0 0 0 0 0 0 0 [2,] 0 0 0 0 0 16 17 18 19 20 ``` Timing on 30k-length list of sample data frames, generated using Arun's `my_sampler` function: ``` set.seed(99) in.d <- lapply(1:30000, function(x) my_sampler(x)) system.time(dat <- datify(in.d, xmax=200)) ## user system elapsed ## 1.317 0.011 1.328 ```
627
So how much reputation you need before you can create tags? How to discuss whether or not a `tag` is valid? Maybe I think it is but other members of this site will find it is not. In this particular case: I would like to create the tag `mercy` because mercy is one of the qualities of the Lord - He is very merciful but there many ways He has shown that mercy and everything related to that could be tagged as such. the question below is one example where I would use it: [Vishnu and His mercy in His hands](https://hinduism.stackexchange.com/questions/15087/vishnu-and-his-mercy-in-his-hands)
2016/09/22
[ "https://hinduism.meta.stackexchange.com/questions/627", "https://hinduism.meta.stackexchange.com", "https://hinduism.meta.stackexchange.com/users/3294/" ]
According to [this](https://hinduism.stackexchange.com/help/privileges) link in Help Center pages on this site i.e. Hinduism SE , One should have minimum of 150 reputation , to avail the privilege of creating and adding tags to the site. Also please check out rest the Help section to know more about other privileges and reputations.
> > You need 1500 reputation now to create new tags. > > > Keep in mind that many seemingly obvious tags may be named different > than you expect, to avoid ambiguity. For example, access seems like it > should be an obvious tag. However, it is not used because it was often > attached to questions covering both security permissions and a certain > notorious database platform. Instead, the tags authorization or > permissions should be used for the former, and ms-access for the > latter. These names avoid ambiguity, and there is zero additional > benefit to also using "access" in either case. > > > Also remember that the point of tags on Stack Exchange is not to > summarize your question, but rather to sort it into a set of > well-defined categories. Tags are how your question connects to an > audience of users qualified to answer it. These users will have > certain tags marked as 'interesting' or subscribe to the rss feeds for > their tags. If you create a new tag, that tag is guaranteed to not > help attract any of those users. > > > A good rule of thumb is to check the auto-suggest prompts when tagging > your question. Any tag with a number less than 10 (100 on Stack > Oveflow itself) after it's name is more than likely wrong. If you feel > you have a fairly common topic (take 'mssql' for example) and you see > a very small number for that tag, try an alternate name (like > 'sql-server'). > > > [Source](https://meta.stackexchange.com/questions/4876/how-can-i-create-a-tag)
3,372,668
I want to declare a class c++ style in a objective-c header, but i get an error "error: expected '=', ',', ';', 'asm' or '\_\_ attribute \_\_' before 'CPPClass'" Here is code from the .h file. ``` class CPPClass; @interface OBJCClass : NSObject { CPPClass* m_pCPPObject; } @end ``` if i implement it objective-c style `@class CPPClass` i get an error when defining it, saying that it can't find the interface declaration. Is there anyway of doing this, otherwise, all the objective-c classes that import my header file with the imported c++ header must also be .mm files. ps. i've have renamed the m file to mm.
2010/07/30
[ "https://Stackoverflow.com/questions/3372668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/406842/" ]
Declare the cpp class only when compiling C++. Use a typedef to void otherwise: ``` #ifdef __cplusplus class CPPClass; #else typedef void CPPClass; #endif ``` This way, non C++ compilation units see the instance variable as a void pointer. Since all pointers are of the same size, the type of the instance variable does not matter.
Rename any files that include it as having .mm extensions. This will tell the compiler to compile with the `-ObjC++` flag.
14,334
In the anime *Hunter x Hunter*, Alluka Zoldyck is considered as a girl by Killua, shown when they leave their estate and were accompanied by four butlers. Killua shouted to Gotoh and said that he needs a female butler to join them because Alluka is a girl. However, I am confused because Milluki address Alluka as a brother, in the episode when he wished to Nanika to kill the tourist photographer. He clearly told the the tourist that he was just taking his brothers for a walk. In addition, the [Hunter Wiki](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck) acknowledged Alluka as a male. What is Alluka's actual gender?
2014/10/08
[ "https://anime.stackexchange.com/questions/14334", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/2309/" ]
Actually, the *Hunter x Hunter* wiki [addresses this](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck#Gender_confusion), and is quite accurate in its assessment, though the references cite the wrong volumes (but correct chapters). > > There is considerable confusion about Alluka's gender. Two of Alluka's brothers, Illumi and Milluki, refer to Alluka as their brother. But Killua, the closest brother of Alluka, specifically states that Alluka is a "girl" and refers to Alluka as his sister multiple times. This inconsistency can be explained by Killua's intimate and understanding bond with Alluka, hence he would know and care that Alluka is mentally female, versus Illumi's cold and dehumanizing attitude towards Alluka. **While Alluka is most likely biologically male, Killua's interactions show that Alluka's psyche may be female.** > > > Everyone (except Killua) addresses Alluka by her biological gender, which appears to be male. While she is quite small, she shows no female development. However, she is very sensitive, gentle, and reserved, and has a very feminine side. Being that Killua is the only one who dares to actually interact with Alluka as a person, he would be the best one to understand that she probably is more feminine inside. This does seem a bit odd to me; even if someone I knew were closer to "she" in his head, unless they specifically asked, I'd probably still say "he". But perhaps either Alluka did ask this of Killua, or Killua just took it upon himself because he knew Alluka so well. Unfortunately, since it's never explicitly stated, this is somewhat assumption, but realistically it's the only explanation that makes sense since Killua is the only one to refer to Alluka as female.
He is physically a male, and mentally female. It is the reason why Killua referred to him as "she". This is stated in the databooks and also by the canon writers. So in other words, Alluka is transgendered. Though, I believe people have the right to think of him as whatever they like, male or female.
14,334
In the anime *Hunter x Hunter*, Alluka Zoldyck is considered as a girl by Killua, shown when they leave their estate and were accompanied by four butlers. Killua shouted to Gotoh and said that he needs a female butler to join them because Alluka is a girl. However, I am confused because Milluki address Alluka as a brother, in the episode when he wished to Nanika to kill the tourist photographer. He clearly told the the tourist that he was just taking his brothers for a walk. In addition, the [Hunter Wiki](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck) acknowledged Alluka as a male. What is Alluka's actual gender?
2014/10/08
[ "https://anime.stackexchange.com/questions/14334", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/2309/" ]
Actually, the *Hunter x Hunter* wiki [addresses this](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck#Gender_confusion), and is quite accurate in its assessment, though the references cite the wrong volumes (but correct chapters). > > There is considerable confusion about Alluka's gender. Two of Alluka's brothers, Illumi and Milluki, refer to Alluka as their brother. But Killua, the closest brother of Alluka, specifically states that Alluka is a "girl" and refers to Alluka as his sister multiple times. This inconsistency can be explained by Killua's intimate and understanding bond with Alluka, hence he would know and care that Alluka is mentally female, versus Illumi's cold and dehumanizing attitude towards Alluka. **While Alluka is most likely biologically male, Killua's interactions show that Alluka's psyche may be female.** > > > Everyone (except Killua) addresses Alluka by her biological gender, which appears to be male. While she is quite small, she shows no female development. However, she is very sensitive, gentle, and reserved, and has a very feminine side. Being that Killua is the only one who dares to actually interact with Alluka as a person, he would be the best one to understand that she probably is more feminine inside. This does seem a bit odd to me; even if someone I knew were closer to "she" in his head, unless they specifically asked, I'd probably still say "he". But perhaps either Alluka did ask this of Killua, or Killua just took it upon himself because he knew Alluka so well. Unfortunately, since it's never explicitly stated, this is somewhat assumption, but realistically it's the only explanation that makes sense since Killua is the only one to refer to Alluka as female.
Alluka is male. He just dresses like a girl. From [Alluka](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck#Gender_Ambiguity) article on Hunter x Hunter Wiki (emphasis mine): > > There is conflicting information regarding Alluka's gender. > > > **The official data book lists Alluka's gender as male**, and two of Alluka's brothers, Illumi and Milluki, refer to Alluka as their brother. > > > However, Killua, the person closest to Alluka, specifically states that Alluka is a girl and refers to Alluka as his sister multiple times. While Alluka may have been designated male at birth, Killua's interactions show that Alluka may identify as female. > > > This inconsistency may be due to Killua's intimate and understanding bond with Alluka, hence he would know and care that Alluka identifies as female, versus Illumi and Milluki's cold and dehumanizing attitude toward Alluka. > > > In the episode showing Alluka in his childhood, we can see that he used to dress like a boy. He ended up looking like a girl, because he played with doll too much that his parent decided to dress him up like a girl.
14,334
In the anime *Hunter x Hunter*, Alluka Zoldyck is considered as a girl by Killua, shown when they leave their estate and were accompanied by four butlers. Killua shouted to Gotoh and said that he needs a female butler to join them because Alluka is a girl. However, I am confused because Milluki address Alluka as a brother, in the episode when he wished to Nanika to kill the tourist photographer. He clearly told the the tourist that he was just taking his brothers for a walk. In addition, the [Hunter Wiki](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck) acknowledged Alluka as a male. What is Alluka's actual gender?
2014/10/08
[ "https://anime.stackexchange.com/questions/14334", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/2309/" ]
Actually, the *Hunter x Hunter* wiki [addresses this](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck#Gender_confusion), and is quite accurate in its assessment, though the references cite the wrong volumes (but correct chapters). > > There is considerable confusion about Alluka's gender. Two of Alluka's brothers, Illumi and Milluki, refer to Alluka as their brother. But Killua, the closest brother of Alluka, specifically states that Alluka is a "girl" and refers to Alluka as his sister multiple times. This inconsistency can be explained by Killua's intimate and understanding bond with Alluka, hence he would know and care that Alluka is mentally female, versus Illumi's cold and dehumanizing attitude towards Alluka. **While Alluka is most likely biologically male, Killua's interactions show that Alluka's psyche may be female.** > > > Everyone (except Killua) addresses Alluka by her biological gender, which appears to be male. While she is quite small, she shows no female development. However, she is very sensitive, gentle, and reserved, and has a very feminine side. Being that Killua is the only one who dares to actually interact with Alluka as a person, he would be the best one to understand that she probably is more feminine inside. This does seem a bit odd to me; even if someone I knew were closer to "she" in his head, unless they specifically asked, I'd probably still say "he". But perhaps either Alluka did ask this of Killua, or Killua just took it upon himself because he knew Alluka so well. Unfortunately, since it's never explicitly stated, this is somewhat assumption, but realistically it's the only explanation that makes sense since Killua is the only one to refer to Alluka as female.
I've always played with two theories: 1. It could be the case that the family refer to Alluka as male to distance themselves from her, denying the fact that she's female to dehumanize her, or to further disassociate her from the family in some way. 2. Or it could very well be that, as Alluka's exact origin is unknown, she isn't strictly human and doesn't possess what we would call a conventional gender, but rather, her gender is simply non-existent, like a Nen beast. Personally, I favor the latter, or a mix of the two. These are all just speculation, of course, but it's interesting to think about nonetheless.
14,334
In the anime *Hunter x Hunter*, Alluka Zoldyck is considered as a girl by Killua, shown when they leave their estate and were accompanied by four butlers. Killua shouted to Gotoh and said that he needs a female butler to join them because Alluka is a girl. However, I am confused because Milluki address Alluka as a brother, in the episode when he wished to Nanika to kill the tourist photographer. He clearly told the the tourist that he was just taking his brothers for a walk. In addition, the [Hunter Wiki](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck) acknowledged Alluka as a male. What is Alluka's actual gender?
2014/10/08
[ "https://anime.stackexchange.com/questions/14334", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/2309/" ]
Actually, the *Hunter x Hunter* wiki [addresses this](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck#Gender_confusion), and is quite accurate in its assessment, though the references cite the wrong volumes (but correct chapters). > > There is considerable confusion about Alluka's gender. Two of Alluka's brothers, Illumi and Milluki, refer to Alluka as their brother. But Killua, the closest brother of Alluka, specifically states that Alluka is a "girl" and refers to Alluka as his sister multiple times. This inconsistency can be explained by Killua's intimate and understanding bond with Alluka, hence he would know and care that Alluka is mentally female, versus Illumi's cold and dehumanizing attitude towards Alluka. **While Alluka is most likely biologically male, Killua's interactions show that Alluka's psyche may be female.** > > > Everyone (except Killua) addresses Alluka by her biological gender, which appears to be male. While she is quite small, she shows no female development. However, she is very sensitive, gentle, and reserved, and has a very feminine side. Being that Killua is the only one who dares to actually interact with Alluka as a person, he would be the best one to understand that she probably is more feminine inside. This does seem a bit odd to me; even if someone I knew were closer to "she" in his head, unless they specifically asked, I'd probably still say "he". But perhaps either Alluka did ask this of Killua, or Killua just took it upon himself because he knew Alluka so well. Unfortunately, since it's never explicitly stated, this is somewhat assumption, but realistically it's the only explanation that makes sense since Killua is the only one to refer to Alluka as female.
Here is my assumption: When Alluka was born, her mother didn't take care of her, she let the butlers to take care of her (like bathing her, etc), and because their mother always thought that all her children must be male, so she thinks that Alluka is male too, especially because she is cold to her and never bathe her, so she doesn't know that Alluka is actually female, and the butlers are too afraid to tell their mother that Alluka is female. While Killua is the one who really cares for her, and knows her the most. So even thought in the birth-biodata and everywhere, Alluka is stated as a male, but Killua knows the truth, and so the butlers who ever took Alluka to bath also have known that. It's just my hypothesis after watching the anime. I think if this hypothesis is true, this story will be a very nice scene, because then it will be stated that "Even the writer of the story doesn't know about Alluka's gender, but her brother knows it because of how he always set an eye on her."
14,334
In the anime *Hunter x Hunter*, Alluka Zoldyck is considered as a girl by Killua, shown when they leave their estate and were accompanied by four butlers. Killua shouted to Gotoh and said that he needs a female butler to join them because Alluka is a girl. However, I am confused because Milluki address Alluka as a brother, in the episode when he wished to Nanika to kill the tourist photographer. He clearly told the the tourist that he was just taking his brothers for a walk. In addition, the [Hunter Wiki](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck) acknowledged Alluka as a male. What is Alluka's actual gender?
2014/10/08
[ "https://anime.stackexchange.com/questions/14334", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/2309/" ]
Alluka is male. He just dresses like a girl. From [Alluka](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck#Gender_Ambiguity) article on Hunter x Hunter Wiki (emphasis mine): > > There is conflicting information regarding Alluka's gender. > > > **The official data book lists Alluka's gender as male**, and two of Alluka's brothers, Illumi and Milluki, refer to Alluka as their brother. > > > However, Killua, the person closest to Alluka, specifically states that Alluka is a girl and refers to Alluka as his sister multiple times. While Alluka may have been designated male at birth, Killua's interactions show that Alluka may identify as female. > > > This inconsistency may be due to Killua's intimate and understanding bond with Alluka, hence he would know and care that Alluka identifies as female, versus Illumi and Milluki's cold and dehumanizing attitude toward Alluka. > > > In the episode showing Alluka in his childhood, we can see that he used to dress like a boy. He ended up looking like a girl, because he played with doll too much that his parent decided to dress him up like a girl.
He is physically a male, and mentally female. It is the reason why Killua referred to him as "she". This is stated in the databooks and also by the canon writers. So in other words, Alluka is transgendered. Though, I believe people have the right to think of him as whatever they like, male or female.
14,334
In the anime *Hunter x Hunter*, Alluka Zoldyck is considered as a girl by Killua, shown when they leave their estate and were accompanied by four butlers. Killua shouted to Gotoh and said that he needs a female butler to join them because Alluka is a girl. However, I am confused because Milluki address Alluka as a brother, in the episode when he wished to Nanika to kill the tourist photographer. He clearly told the the tourist that he was just taking his brothers for a walk. In addition, the [Hunter Wiki](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck) acknowledged Alluka as a male. What is Alluka's actual gender?
2014/10/08
[ "https://anime.stackexchange.com/questions/14334", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/2309/" ]
I've always played with two theories: 1. It could be the case that the family refer to Alluka as male to distance themselves from her, denying the fact that she's female to dehumanize her, or to further disassociate her from the family in some way. 2. Or it could very well be that, as Alluka's exact origin is unknown, she isn't strictly human and doesn't possess what we would call a conventional gender, but rather, her gender is simply non-existent, like a Nen beast. Personally, I favor the latter, or a mix of the two. These are all just speculation, of course, but it's interesting to think about nonetheless.
He is physically a male, and mentally female. It is the reason why Killua referred to him as "she". This is stated in the databooks and also by the canon writers. So in other words, Alluka is transgendered. Though, I believe people have the right to think of him as whatever they like, male or female.
14,334
In the anime *Hunter x Hunter*, Alluka Zoldyck is considered as a girl by Killua, shown when they leave their estate and were accompanied by four butlers. Killua shouted to Gotoh and said that he needs a female butler to join them because Alluka is a girl. However, I am confused because Milluki address Alluka as a brother, in the episode when he wished to Nanika to kill the tourist photographer. He clearly told the the tourist that he was just taking his brothers for a walk. In addition, the [Hunter Wiki](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck) acknowledged Alluka as a male. What is Alluka's actual gender?
2014/10/08
[ "https://anime.stackexchange.com/questions/14334", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/2309/" ]
Alluka is male. He just dresses like a girl. From [Alluka](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck#Gender_Ambiguity) article on Hunter x Hunter Wiki (emphasis mine): > > There is conflicting information regarding Alluka's gender. > > > **The official data book lists Alluka's gender as male**, and two of Alluka's brothers, Illumi and Milluki, refer to Alluka as their brother. > > > However, Killua, the person closest to Alluka, specifically states that Alluka is a girl and refers to Alluka as his sister multiple times. While Alluka may have been designated male at birth, Killua's interactions show that Alluka may identify as female. > > > This inconsistency may be due to Killua's intimate and understanding bond with Alluka, hence he would know and care that Alluka identifies as female, versus Illumi and Milluki's cold and dehumanizing attitude toward Alluka. > > > In the episode showing Alluka in his childhood, we can see that he used to dress like a boy. He ended up looking like a girl, because he played with doll too much that his parent decided to dress him up like a girl.
Here is my assumption: When Alluka was born, her mother didn't take care of her, she let the butlers to take care of her (like bathing her, etc), and because their mother always thought that all her children must be male, so she thinks that Alluka is male too, especially because she is cold to her and never bathe her, so she doesn't know that Alluka is actually female, and the butlers are too afraid to tell their mother that Alluka is female. While Killua is the one who really cares for her, and knows her the most. So even thought in the birth-biodata and everywhere, Alluka is stated as a male, but Killua knows the truth, and so the butlers who ever took Alluka to bath also have known that. It's just my hypothesis after watching the anime. I think if this hypothesis is true, this story will be a very nice scene, because then it will be stated that "Even the writer of the story doesn't know about Alluka's gender, but her brother knows it because of how he always set an eye on her."
14,334
In the anime *Hunter x Hunter*, Alluka Zoldyck is considered as a girl by Killua, shown when they leave their estate and were accompanied by four butlers. Killua shouted to Gotoh and said that he needs a female butler to join them because Alluka is a girl. However, I am confused because Milluki address Alluka as a brother, in the episode when he wished to Nanika to kill the tourist photographer. He clearly told the the tourist that he was just taking his brothers for a walk. In addition, the [Hunter Wiki](http://hunterxhunter.wikia.com/wiki/Alluka_Zoldyck) acknowledged Alluka as a male. What is Alluka's actual gender?
2014/10/08
[ "https://anime.stackexchange.com/questions/14334", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/2309/" ]
I've always played with two theories: 1. It could be the case that the family refer to Alluka as male to distance themselves from her, denying the fact that she's female to dehumanize her, or to further disassociate her from the family in some way. 2. Or it could very well be that, as Alluka's exact origin is unknown, she isn't strictly human and doesn't possess what we would call a conventional gender, but rather, her gender is simply non-existent, like a Nen beast. Personally, I favor the latter, or a mix of the two. These are all just speculation, of course, but it's interesting to think about nonetheless.
Here is my assumption: When Alluka was born, her mother didn't take care of her, she let the butlers to take care of her (like bathing her, etc), and because their mother always thought that all her children must be male, so she thinks that Alluka is male too, especially because she is cold to her and never bathe her, so she doesn't know that Alluka is actually female, and the butlers are too afraid to tell their mother that Alluka is female. While Killua is the one who really cares for her, and knows her the most. So even thought in the birth-biodata and everywhere, Alluka is stated as a male, but Killua knows the truth, and so the butlers who ever took Alluka to bath also have known that. It's just my hypothesis after watching the anime. I think if this hypothesis is true, this story will be a very nice scene, because then it will be stated that "Even the writer of the story doesn't know about Alluka's gender, but her brother knows it because of how he always set an eye on her."
39,004,540
I'm trying to make a simple test in python, but I'm not able to figure it out how to accomplish the mocking process. This is the class and def code: ``` class FileRemoveOp(...) @apply_defaults def __init__( self, source_conn_keys, source_conn_id='conn_default', *args, **kwargs): super(v4FileRemoveOperator, self).__init__(*args, **kwargs) self.source_conn_keys = source_conn_keys self.source_conn_id = source_conn_id def execute (self, context) source_conn = Connection(conn_id) try: for source_conn_key in self.source_keys: if not source_conn.check_for_key(source_conn_key): logging.info("The source key does not exist") source_conn.remove_file(source_conn_key,'') finally: logging.info("Remove operation successful.") ``` And this is my test for the execute function: ``` @mock.patch('main.Connection') def test_remove_execute(self,MockConn): mock_coon = MockConn.return_value mock_coon.value = #I'm not sure what to put here# remove_operator = FileRemoveOp(...) remove_operator.execute(self) ``` Since the **execute** method try to make a connection, I need to mock that, I don't want to make a real connection, just return something mock. How can I make that? I'm used to do testing in Java but I never did on python..
2016/08/17
[ "https://Stackoverflow.com/questions/39004540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5335185/" ]
First it is very important to understand that you always need to Mock where it the thing you are trying to mock out is used as stated in the `unittest.mock` documentation. > > The basic principle is that you patch where an object is looked up, > which is not necessarily the same place as where it is defined. > > > Next what you would need to do is to return a `MagicMock` instance as `return_value` of the patched object. So to summarize this you would need to use the following sequence. * Patch Object * prepare `MagicMock` to be used * return the `MagicMock` we've just created as `return_value` Here a quick example of a project. **connection.py (Class we would like to Mock)** ``` class Connection(object): def execute(self): return "Connection to server made" ``` **file.py (Where the Class is used)** ``` from project.connection import Connection class FileRemoveOp(object): def __init__(self, foo): self.foo = foo def execute(self): conn = Connection() result = conn.execute() return result ``` **tests/test\_file.py** ``` import unittest from unittest.mock import patch, MagicMock from project.file import FileRemoveOp class TestFileRemoveOp(unittest.TestCase): def setUp(self): self.fileremoveop = FileRemoveOp('foobar') @patch('project.file.Connection') def test_execute(self, connection_mock): # Create a new MagickMock instance which will be the # `return_value` of our patched object connection_instance = MagicMock() connection_instance.execute.return_value = "testing" # Return the above created `connection_instance` connection_mock.return_value = connection_instance result = self.fileremoveop.execute() expected = "testing" self.assertEqual(result, expected) def test_not_mocked(self): # No mocking involved will execute the `Connection.execute` method result = self.fileremoveop.execute() expected = "Connection to server made" self.assertEqual(result, expected) ```
I found that this simple solution works in python3: you can substitute a whole class before it is being imported for the first time. Say I have to mock class 'Manager' from real.manager ``` class MockManager: ... import real.manager real.manager.Manager = MockManager ``` It is possible to do this substitution in **init**.py if there is no better place. It may work in python2 too but I did not check.
6,703,491
I am working with servlets. When my user logs in, my application is setting his userId and deviceId in a session variable. Some other part of my application now needs the list of online people and their userId/ deviceId. Note that a user may have simultaneous logins with 2 devices, so we have 2 deviceIds for the same userId. How should I approach this situation ? I am not willing to use database for tracking the login/ logout functionalities
2011/07/15
[ "https://Stackoverflow.com/questions/6703491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629768/" ]
Store this information also in HttpServletContext's attribute. This context is global per servlet and can be accsessible by all sessions. You even can do more. Using HttpSessionAttributeListener you can be notified every time the attribure is added, so if you want to create some kind of monitor application it may be more responsive.
In addition to Alex's response. The header attribute you are looking for is user-agent. Following is the code snippet of accessing browser type from request. ((javax.servlet.http.HttpServletRequest)pageContext.getRequest()).getHeader("user-agent")
6,703,491
I am working with servlets. When my user logs in, my application is setting his userId and deviceId in a session variable. Some other part of my application now needs the list of online people and their userId/ deviceId. Note that a user may have simultaneous logins with 2 devices, so we have 2 deviceIds for the same userId. How should I approach this situation ? I am not willing to use database for tracking the login/ logout functionalities
2011/07/15
[ "https://Stackoverflow.com/questions/6703491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629768/" ]
Store this information also in HttpServletContext's attribute. This context is global per servlet and can be accsessible by all sessions. You even can do more. Using HttpSessionAttributeListener you can be notified every time the attribure is added, so if you want to create some kind of monitor application it may be more responsive.
In addition to Alex and Suken's responses, assuming the user has a single session you could store the deviceId's in a Map: ``` String userAgent = (see Suken's response) String deviceId = request.getParameter("REQUEST_PARAMETER_DEVICE_ID"); Map<String, String> devices = request.getSession().getAttribute("SESSION_ATTRIBUTE_DEVICES"); if (devices == null) { devices = new HashMap<String, String>(); request.getSession().setAttribute("SESSION_ATTRIBUTE_DEVICES", devices); } devices.put(userAgent, deviceId); ``` This makes sure the multiple devices remain visible and are not overwritten. You still need to expose them like Alex explained if you want to access them at application level.
6,703,491
I am working with servlets. When my user logs in, my application is setting his userId and deviceId in a session variable. Some other part of my application now needs the list of online people and their userId/ deviceId. Note that a user may have simultaneous logins with 2 devices, so we have 2 deviceIds for the same userId. How should I approach this situation ? I am not willing to use database for tracking the login/ logout functionalities
2011/07/15
[ "https://Stackoverflow.com/questions/6703491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629768/" ]
In addition to Alex's response. The header attribute you are looking for is user-agent. Following is the code snippet of accessing browser type from request. ((javax.servlet.http.HttpServletRequest)pageContext.getRequest()).getHeader("user-agent")
In addition to Alex and Suken's responses, assuming the user has a single session you could store the deviceId's in a Map: ``` String userAgent = (see Suken's response) String deviceId = request.getParameter("REQUEST_PARAMETER_DEVICE_ID"); Map<String, String> devices = request.getSession().getAttribute("SESSION_ATTRIBUTE_DEVICES"); if (devices == null) { devices = new HashMap<String, String>(); request.getSession().setAttribute("SESSION_ATTRIBUTE_DEVICES", devices); } devices.put(userAgent, deviceId); ``` This makes sure the multiple devices remain visible and are not overwritten. You still need to expose them like Alex explained if you want to access them at application level.
7,667,588
On os x Lion (10.7.1), DiskImageMounter is the program used to open dmg files so that the user can install new programs. When I try to open images on my system attached to my home network they do not open. When I connect to the tethered network from my cell phone I can open them using the mac utility. What is wrong with my router and/or modem? I have a netgear router and and arris modem.
2011/10/05
[ "https://Stackoverflow.com/questions/7667588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629014/" ]
In this line here: ``` my $scrubbed_hash = map { defined $hash_ref->{$_} ? ($_ => $hash_ref->{$_}) : () } keys %{$hash_ref}; ``` You are assigning a list from `map` into the scalar `$scrubbed_hash`. `map` in scalar context will return the number of elements in the list (10). Rather than assigning to a scalar, assign to a plural hash: ``` sub scrub_hash{ my($self,$hash_ref) = @_; my %scrubbed_hash = map { defined $hash_ref->{$_} ? ($_ => $hash_ref->{$_}) : () } keys %{$hash_ref}; print STDERR "[scrub]". $_."\n" for values %scrubbed_hash; } ``` If you really wanted to use a scalar for `$scrubbed_hash` you will need to wrap the map statement with `{map {...} args}` which will construct an anonymous hash out of the list. To filter out the elements in place, you could use the `delete` function: ``` my %hash = (foo => 1, bar => undef, baz => 2); defined $hash{$_} or delete $hash{$_} for keys %hash; print join ', ' => keys %hash; # foo, baz ``` --- per the update: The `scrub_empty_params` method should look something like this: ``` sub scrub_empty_params { my ($self, $hash) = @_; {map {defined $$hash{$_} ? ($_ => $$hash{$_}) : ()} keys %$hash} } ``` If that is not working for you, then it may be that your values are defined, but have a length of 0. ``` sub scrub_empty_params { my ($self, $hash) = @_; {map {(defined $$hash{$_} and length $$hash{$_}) ? ($_ => $$hash{$_}) : ()} keys %$hash} } ``` You might want to remove a bit of boiler plate from your API by creating a different `->Vars()` method that returns a filtered hash: ``` sub clean_vars { my ($self) = @_; $self->scrub_empty_params($self->Vars) } ```
Try this: ``` my %scrubbed_hash = map { $_ => $hash_ref->{ $_ } } grep { defined $hash_ref->{$_} } keys %{$hash_ref}; ```
4,492,388
I was hoping someone can help me with this. I have been running myself crazy with this. I have a situation where I load the DataTables grid (awesome piece by the way!) and all is great. Then I go to search and I run into problems. The data being populated in the grid is coming from two different database tables (which is fine) but when someone executes a search I have no way of knowing where to go and get the data. I would need to know what criteria the search is about (i.e. title or contact). I see what when the search is called from the server via the default search box there are variables like "sSearch\_0" which are all unset, how do those get set? Here is the initialization code for the table: ``` oTable = $('#example').dataTable({ "bJQueryUI": true, "bFilter": true, "sPaginationType": "full_numbers", "bPaginate " : true, "bServerSide" : true, "sAjaxSource" : "php/tabledata.php", "aoColumnDefs": [ { "bSortable": false, "aTargets": [ 0,6,8 ] }, { "sClass": "tdCenter", "aTargets": [ 0,1,2,3,4,5,6,7,8 ] } ], "fnServerData": function ( sSource, aoData, fnCallback ) { aoData.push( { "name": "userid", "value": userid } ); $.getJSON( sSource, aoData, function (json) { fnCallback(json) }); } ``` }); I have looked into options for adding data to the "fnServerData " and actually use that for the first initialization server call but am unsure how to use that for a subsequent server call. I have tried to use "fnFilter" but I do not see that executing a server call for more data. At this point I do not see any other way to execute a server call besides the default search box and I see some way of knowing which column the search is for. Can someone help me here and point me in the right direction?
2010/12/20
[ "https://Stackoverflow.com/questions/4492388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483287/" ]
If you are getting data from the server for the DataTables plugin, you have to set bServerSide to true, set the sAjaxSource to the appropriate URL, and ideally configure fnServerData if you need to do any callbacks. If you use server-side processing, all sorting, filtering, and paging needs to be handled by you on the server. If you configure DataTables correctly, it will request data from the server any time there is a paging, filtering, or sorting event. [DataTables server-side API documentation](http://datatables.net/usage/server-side) [PHP example of server-side processing](http://datatables.net/examples/server_side/server_side.html)
For the benefit of all who would refer this question, here is what I have implemented. **Client Side (JavaScript)** Execute fnFilter upon pressing Enter key. ``` $(tableId + " thead input").keypress( function () { if (event.which == 13) { event.preventDefault(); oTable.fnFilter( this.value, $("thead input").index(this) ); } } ); ``` **Server Side (Ruby)** Find the sSearch\_(int) param hash, and retrieve the column index from the key. Get the column names from an array and build the search string. ``` def column_search search_string = [] params.keys.map {|x| x if params[x].present? and x.include? "sSearch_"}.compact.each do |search| index = search.split("_").last.to_i search_string << "#{columns[index]} ilike '%#{params[search]}%'" end search_string.join(' and ') end ```
39,871
I've started to teach myself how to play the piano, and one of the difficulties I've found is trying to get both hands to do things at once. I either forget one hand entirely, or have one hand trying to mimic the other. This reminded me of many years ago when I was taught to play the viola. For many weeks, we did not use the bow, instead focusing on getting the left hand to do the things it was supposed to, and learning to read music. In hindsight, this makes sense to me, as it's often important to get used to some fundamentals before attempting to do everything at once. So I was wondering, when learning the piano, is it better to learn each hand on their own, or muddle through the difficulties of synchronizing them from the beginning? Or, if there are arguments for both methods, what are the pros/cons of each? What problems may develop, or what difficulties might be avoided? Or is there perhaps a happy medium that has proven the most successful? For my personal musical background, I have about nine years' experience with the viola, though I haven't played it in about five years (stopped after high school). I also play the guitar, but never learned to read music for it.
2015/12/01
[ "https://music.stackexchange.com/questions/39871", "https://music.stackexchange.com", "https://music.stackexchange.com/users/24978/" ]
From my experience, beginning players (who start from not knowing how to read music at all) will play hands separately and then put them together. After you've gotten over some of the initial difficulty of just reading the music, I believe it's encouraged universally to learn/practice both at once. Of course, you can play separately to suss out some details, but on the whole, both hands should be played together. The faster you get used to playing and reading both lines-- difficult at first-- the better you will be equipped to handle more pieces that come your way. There is only a very tiny amount of piano works that are written for one hand, so really, it's in your best interest to just dive in. The happy medium, in my opinion, is a 90-10 split. You start out playing with both hands (and pedal, don't forget those feet!). Then from playing, you figure out what you need to work on and separate as needed. This should mostly be from the technical standpoint, because to work on the overall interpretation, you really need all the parts together and playing each part individually isn't really going to help you much in the long run. I suppose, if you were working on a piece that was in the outer reaches of your technique, the split might become more even, but even then I don't think it should reach more than 60-40. I'm originally a pianist, and then I got to the carillon, where similar to the organ, your feet move around a lot. It was hard for me learning an extra "line" (my feet), and it was always tempting to just practice the feet separately because it was so difficult for me and it slowed down my playing greatly. However, you move differently depending on what your hands AND feet are doing, so I became resigned to the fact that yes, no matter how excruciating, I need to play everything at once (and I do, so I'm intermediate sight-reader now). It's okay to play one at first to figure out what the melody is doing and what things you should emphasize, and just figure out the overall placement, but again, the piece is most improved when you play the entire piece, no matter how slowly at first, with all its parts and trappings.
There are some beginning piano books that help one get the hang of integrating the two hands. Here's what a piece in such a book might look like: A melody is presented that straddles middle C. (The hands are in the basic position where both thumbs play middle C.) As the melody goes above middle C, the right hand becomes active, but the left hand stays in position, at the ready. Within a couple of bars, the melody passes to the left hand, while the right hand rests. There are other ways for the two hands to take turns, that was just an example. As you progress with this approach, things will get gradually more complex. I don't think you need to confine yourself to working with a book of this type, but it can be helpful to work with such a book alongside whatever other material you're working with. It's a relatively painless way to get both hands working together towards a common cause. You can find books that take this approach by browsing through the beginning piano books in a music shop.
39,871
I've started to teach myself how to play the piano, and one of the difficulties I've found is trying to get both hands to do things at once. I either forget one hand entirely, or have one hand trying to mimic the other. This reminded me of many years ago when I was taught to play the viola. For many weeks, we did not use the bow, instead focusing on getting the left hand to do the things it was supposed to, and learning to read music. In hindsight, this makes sense to me, as it's often important to get used to some fundamentals before attempting to do everything at once. So I was wondering, when learning the piano, is it better to learn each hand on their own, or muddle through the difficulties of synchronizing them from the beginning? Or, if there are arguments for both methods, what are the pros/cons of each? What problems may develop, or what difficulties might be avoided? Or is there perhaps a happy medium that has proven the most successful? For my personal musical background, I have about nine years' experience with the viola, though I haven't played it in about five years (stopped after high school). I also play the guitar, but never learned to read music for it.
2015/12/01
[ "https://music.stackexchange.com/questions/39871", "https://music.stackexchange.com", "https://music.stackexchange.com/users/24978/" ]
When I first started learning piano I also used to practice one hand at a time. I think it is important because then in the end it's all about coordination and if you want your hands to be well coordinated you first need each hand to know what it has to do. Putting it all together is then a completely different story, you'll have to focus on the coordination and not on the single hand anymore plus you'll have to read 2 staff at a time (which might be tricky for someone which is not used to that), but indeed the practice that you gained playing with separate hands will help. With experience and practice you'll do that more quickly and start putting it all together soon, however I still give a shot at each hand separately, I think it helps a lot. Of course with increasing difficulty of the piece you want to play you'll spend much more time practicing with two hands together. At times you'll have to focus on a small amount of bars when you'll have some difficult phrase (and then there are many ways which might help studying a single piece depending on the technique involved), which is also recommended when there are some particularly difficult parts in the piece (but I think this applies to the viola as well).
I cannot gauge your piano level very well, but if you are having difficulties playing both hands at the same time, then the piece is may be too difficult for your level. For piano players that are beyond the elementary level, I believe most players usually start learning the song both hands at the same time. This does help you get to learn the timing of the right and left hand right from the get go, instead of having to piece them together later on. Learning each separately and then piecing together later may actually be slower (depends on the piece) because of complex interweaving melodies, etc... However, the practice is often done separately as needed. My piano teacher used to say if you cannot play the one hand alone, you definitely cannot play it properly with two hands. When practicing one-handedly, it will often reveal mistakes that you don't really notice while playing with two hands. For elementary players, (at least from my experience), usually the learning process is just: * right handed songs; * primarily right handed songs with some added notes on the bass clef * more difficult songs with a more involved bass line for the left hand That's why as I said earlier, perhaps if you are having difficulties of left and right handed songs, then maybe you are playing songs with a bass line that is too difficult at the moment for you. One thing you can do to improve independent motor control with your hands is practice your left and right brain. The left brain controls the right hand and right brain for left hand. One exercise I was taught is to try rubbing your right hand on your thigh in a forward and backward motion (relative to a sitting position), and with your left hand do a upward and downward motion in a fist. Switch it up to have right hand as a fist, and left hand doing the rubbing. I know it sounds and looks retarded, but some people actually have difficulty because it involves independent directional motion.
39,871
I've started to teach myself how to play the piano, and one of the difficulties I've found is trying to get both hands to do things at once. I either forget one hand entirely, or have one hand trying to mimic the other. This reminded me of many years ago when I was taught to play the viola. For many weeks, we did not use the bow, instead focusing on getting the left hand to do the things it was supposed to, and learning to read music. In hindsight, this makes sense to me, as it's often important to get used to some fundamentals before attempting to do everything at once. So I was wondering, when learning the piano, is it better to learn each hand on their own, or muddle through the difficulties of synchronizing them from the beginning? Or, if there are arguments for both methods, what are the pros/cons of each? What problems may develop, or what difficulties might be avoided? Or is there perhaps a happy medium that has proven the most successful? For my personal musical background, I have about nine years' experience with the viola, though I haven't played it in about five years (stopped after high school). I also play the guitar, but never learned to read music for it.
2015/12/01
[ "https://music.stackexchange.com/questions/39871", "https://music.stackexchange.com", "https://music.stackexchange.com/users/24978/" ]
It's very normal to have issues playing with both hands at first, but if you're finding yourself completely unable to do so at all, then maybe you're attempting to play music that's too hard for you. This is a common problem for people that have significant experience on one instrument and then start another. It feels embarrassing to go all the way back to basics and play stuff that you feel like is meant for 5-year-olds, but it really has to be done. You're gonna play some Mary Had A Little Lamb, with the melody in the right hand, and single whole notes in the left. There are some method books out there that have slightly more dignified music, if that helps. Some struggle is good (it's the only way to grow), but hitting a wall isn't productive.
That depends on the piece sometimes. My old teacher used to say practice one separately until you've got it down then "see" them together. Honestly, I'd recommend practicing one measure at a time by repeating one until you've got it and then move on. Lastly, play from the beginning after a few measures to smooth over any rough spots :)
39,871
I've started to teach myself how to play the piano, and one of the difficulties I've found is trying to get both hands to do things at once. I either forget one hand entirely, or have one hand trying to mimic the other. This reminded me of many years ago when I was taught to play the viola. For many weeks, we did not use the bow, instead focusing on getting the left hand to do the things it was supposed to, and learning to read music. In hindsight, this makes sense to me, as it's often important to get used to some fundamentals before attempting to do everything at once. So I was wondering, when learning the piano, is it better to learn each hand on their own, or muddle through the difficulties of synchronizing them from the beginning? Or, if there are arguments for both methods, what are the pros/cons of each? What problems may develop, or what difficulties might be avoided? Or is there perhaps a happy medium that has proven the most successful? For my personal musical background, I have about nine years' experience with the viola, though I haven't played it in about five years (stopped after high school). I also play the guitar, but never learned to read music for it.
2015/12/01
[ "https://music.stackexchange.com/questions/39871", "https://music.stackexchange.com", "https://music.stackexchange.com/users/24978/" ]
When I was taking piano lessons I learned each piece three times: Once with the right hand, once with the left hand, and the third time putting both together. After a while, the third "learning" came a lot more quickly, and after a few years I would start to slowly sight read both parts together. Today I will still practice the hard pieces one handed from time to time, especially when the timing is really disconnected between the two hands and I need at least one to go on automatic pilot. There are some pieces (*Leyenda* by Albeniz comes to mind) where the two parts are so intertwined it never makes sense to try to learn them alone. Usually that's clear from the beginning when it's the case.
From my experience, beginning players (who start from not knowing how to read music at all) will play hands separately and then put them together. After you've gotten over some of the initial difficulty of just reading the music, I believe it's encouraged universally to learn/practice both at once. Of course, you can play separately to suss out some details, but on the whole, both hands should be played together. The faster you get used to playing and reading both lines-- difficult at first-- the better you will be equipped to handle more pieces that come your way. There is only a very tiny amount of piano works that are written for one hand, so really, it's in your best interest to just dive in. The happy medium, in my opinion, is a 90-10 split. You start out playing with both hands (and pedal, don't forget those feet!). Then from playing, you figure out what you need to work on and separate as needed. This should mostly be from the technical standpoint, because to work on the overall interpretation, you really need all the parts together and playing each part individually isn't really going to help you much in the long run. I suppose, if you were working on a piece that was in the outer reaches of your technique, the split might become more even, but even then I don't think it should reach more than 60-40. I'm originally a pianist, and then I got to the carillon, where similar to the organ, your feet move around a lot. It was hard for me learning an extra "line" (my feet), and it was always tempting to just practice the feet separately because it was so difficult for me and it slowed down my playing greatly. However, you move differently depending on what your hands AND feet are doing, so I became resigned to the fact that yes, no matter how excruciating, I need to play everything at once (and I do, so I'm intermediate sight-reader now). It's okay to play one at first to figure out what the melody is doing and what things you should emphasize, and just figure out the overall placement, but again, the piece is most improved when you play the entire piece, no matter how slowly at first, with all its parts and trappings.
39,871
I've started to teach myself how to play the piano, and one of the difficulties I've found is trying to get both hands to do things at once. I either forget one hand entirely, or have one hand trying to mimic the other. This reminded me of many years ago when I was taught to play the viola. For many weeks, we did not use the bow, instead focusing on getting the left hand to do the things it was supposed to, and learning to read music. In hindsight, this makes sense to me, as it's often important to get used to some fundamentals before attempting to do everything at once. So I was wondering, when learning the piano, is it better to learn each hand on their own, or muddle through the difficulties of synchronizing them from the beginning? Or, if there are arguments for both methods, what are the pros/cons of each? What problems may develop, or what difficulties might be avoided? Or is there perhaps a happy medium that has proven the most successful? For my personal musical background, I have about nine years' experience with the viola, though I haven't played it in about five years (stopped after high school). I also play the guitar, but never learned to read music for it.
2015/12/01
[ "https://music.stackexchange.com/questions/39871", "https://music.stackexchange.com", "https://music.stackexchange.com/users/24978/" ]
When I was taking piano lessons I learned each piece three times: Once with the right hand, once with the left hand, and the third time putting both together. After a while, the third "learning" came a lot more quickly, and after a few years I would start to slowly sight read both parts together. Today I will still practice the hard pieces one handed from time to time, especially when the timing is really disconnected between the two hands and I need at least one to go on automatic pilot. There are some pieces (*Leyenda* by Albeniz comes to mind) where the two parts are so intertwined it never makes sense to try to learn them alone. Usually that's clear from the beginning when it's the case.
That depends on the piece sometimes. My old teacher used to say practice one separately until you've got it down then "see" them together. Honestly, I'd recommend practicing one measure at a time by repeating one until you've got it and then move on. Lastly, play from the beginning after a few measures to smooth over any rough spots :)