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
49,064,157
I am having difficulty running the below simple script from crontab: ``` #!/bin/bash notify-send "battery.sh working" ``` The permissions of the file are `rwxr-xr-x` and its running fine with either of the commands `bash battery.sh` and `sh battery.sh`. In my crontab, I have tried running it with both `bash` and `sh`, with absolute as well as local path. My current crontab looks as follows: ``` * * * * * /home/marpangal/battery.sh * * * * * sh battery.sh * * * * * bash battery.sh * * * * * sh /home/marpangal/battery.sh * * * * * bash /home/marpangal/battery.sh ``` However the cron does not execute the script and I get no message from notify-send.
2018/03/02
[ "https://Stackoverflow.com/questions/49064157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7116413/" ]
It's not legit, but browsers are extremely forgiving and will still try to render something as best as they can, even if the HTML you give it is technically wrong.
**Is this legit?** No. Although browser show perfectly but W3C Validator will not permit you write this way. You will get error if you go with your code in validation engine. Validator will show you message like following. "**Error:** Element div not allowed as child of element ol in this context." Also see here: `https://html.spec.whatwg.org/#toc-dom` in "**Semantics, structure, and APIs of HTML documents**" section to get overall idea.
7,870,945
I have a table that stores the versions as under ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') Select * From @tblVersion VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` My requirement is that I need to sort them so that the output will be ``` VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.3.109.1 1.4.8.66 1.4.11.14.7 ``` But if do a simple order by it does not work as expected ``` Select VersionNumber From @tblVersion Order By VersionNumber VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` Help needed
2011/10/24
[ "https://Stackoverflow.com/questions/7870945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111663/" ]
If you are using SQL Server 2008 or later, you can leverage the hierarchyID data type: ``` select * from @tblVersion order by CAST('/'+REPLACE(VersionNumber,'.','/')+'/' as hierarchyID) ```
Implementation of Brain's Solution ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') --Select * From @tblVersion ;With CTE AS ( Select Rn = Row_Number() Over(Order By (Select 1)) ,VersionNumber From @tblVersion ) ,CTESplit AS ( SELECT F1.Rn, F1.VersionNumber, VersionSort = Case When Len(O.VersionSort) = 1 Then '000' + O.VersionSort When Len(O.VersionSort) = 2 Then '00' + O.VersionSort When Len(O.VersionSort) = 3 Then '0' + O.VersionSort When Len(O.VersionSort) = 4 Then O.VersionSort End FROM ( SELECT *, cast('<X>'+replace(F.VersionNumber,'.','</X><X>')+'</X>' as XML) as xmlfilter from CTE F )F1 CROSS APPLY ( SELECT fdata.D.value('.','varchar(50)') as VersionSort FROM f1.xmlfilter.nodes('X') as fdata(D)) O ) ,CTE3 As( Select --Rn --, VersionNumber ,SortableVersion = Stuff( (Select '.' + Cast(VersionSort As Varchar(100)) From CTESplit c2 Where c2.Rn = c1.Rn For Xml Path('')),1,1,'') From CTESplit c1 Group By c1.Rn,c1.VersionNumber ) Select VersionNumber From CTE3 Order By SortableVersion ```
7,870,945
I have a table that stores the versions as under ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') Select * From @tblVersion VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` My requirement is that I need to sort them so that the output will be ``` VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.3.109.1 1.4.8.66 1.4.11.14.7 ``` But if do a simple order by it does not work as expected ``` Select VersionNumber From @tblVersion Order By VersionNumber VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` Help needed
2011/10/24
[ "https://Stackoverflow.com/questions/7870945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111663/" ]
If you are on SQL Server 2005 or later and the number of possible fields in version numbers is fixed, you could try the following approach: ``` SELECT t.* FROM @tblVersion t CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, 1), 0)) v1 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v1.v + 1), 0)) v2 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v2.v + 1), 0)) v3 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v3.v + 1), 0)) v4 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v4.v + 1), 0)) v5 ORDER BY CAST(SUBSTRING(t.VersionNumber, v1.v, v2.v - v1.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v2.v, v3.v - v2.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v3.v, v4.v - v3.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v4.v, v5.v - v4.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v5.v, 999) AS int) ``` All fields of a version number are extracted one by one and converted to integers, which are then used for sorting. (Basically, [@Brian](https://stackoverflow.com/questions/7870945/version-number-sorting-in-sql-server/7871016#7871016)'s idea, as it turns out.)
I cannot see the solution using standard sorting etc, but I think you need the UDF that adds the "0" symbols before each symbol, like ``` 001.003.001 001.003.002.005 001.004.001.007.012 001.004.011.014.007 001.004.003.109.001 001.004.008.066 ``` and then sort by these changed values
7,870,945
I have a table that stores the versions as under ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') Select * From @tblVersion VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` My requirement is that I need to sort them so that the output will be ``` VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.3.109.1 1.4.8.66 1.4.11.14.7 ``` But if do a simple order by it does not work as expected ``` Select VersionNumber From @tblVersion Order By VersionNumber VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` Help needed
2011/10/24
[ "https://Stackoverflow.com/questions/7870945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111663/" ]
Implementation of Brain's Solution ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') --Select * From @tblVersion ;With CTE AS ( Select Rn = Row_Number() Over(Order By (Select 1)) ,VersionNumber From @tblVersion ) ,CTESplit AS ( SELECT F1.Rn, F1.VersionNumber, VersionSort = Case When Len(O.VersionSort) = 1 Then '000' + O.VersionSort When Len(O.VersionSort) = 2 Then '00' + O.VersionSort When Len(O.VersionSort) = 3 Then '0' + O.VersionSort When Len(O.VersionSort) = 4 Then O.VersionSort End FROM ( SELECT *, cast('<X>'+replace(F.VersionNumber,'.','</X><X>')+'</X>' as XML) as xmlfilter from CTE F )F1 CROSS APPLY ( SELECT fdata.D.value('.','varchar(50)') as VersionSort FROM f1.xmlfilter.nodes('X') as fdata(D)) O ) ,CTE3 As( Select --Rn --, VersionNumber ,SortableVersion = Stuff( (Select '.' + Cast(VersionSort As Varchar(100)) From CTESplit c2 Where c2.Rn = c1.Rn For Xml Path('')),1,1,'') From CTESplit c1 Group By c1.Rn,c1.VersionNumber ) Select VersionNumber From CTE3 Order By SortableVersion ```
If you are on SQL Server 2005 or later and the number of possible fields in version numbers is fixed, you could try the following approach: ``` SELECT t.* FROM @tblVersion t CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, 1), 0)) v1 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v1.v + 1), 0)) v2 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v2.v + 1), 0)) v3 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v3.v + 1), 0)) v4 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v4.v + 1), 0)) v5 ORDER BY CAST(SUBSTRING(t.VersionNumber, v1.v, v2.v - v1.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v2.v, v3.v - v2.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v3.v, v4.v - v3.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v4.v, v5.v - v4.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v5.v, 999) AS int) ``` All fields of a version number are extracted one by one and converted to integers, which are then used for sorting. (Basically, [@Brian](https://stackoverflow.com/questions/7870945/version-number-sorting-in-sql-server/7871016#7871016)'s idea, as it turns out.)
7,870,945
I have a table that stores the versions as under ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') Select * From @tblVersion VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` My requirement is that I need to sort them so that the output will be ``` VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.3.109.1 1.4.8.66 1.4.11.14.7 ``` But if do a simple order by it does not work as expected ``` Select VersionNumber From @tblVersion Order By VersionNumber VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` Help needed
2011/10/24
[ "https://Stackoverflow.com/questions/7870945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111663/" ]
If you are on SQL Server 2005 or later and the number of possible fields in version numbers is fixed, you could try the following approach: ``` SELECT t.* FROM @tblVersion t CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, 1), 0)) v1 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v1.v + 1), 0)) v2 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v2.v + 1), 0)) v3 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v3.v + 1), 0)) v4 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v4.v + 1), 0)) v5 ORDER BY CAST(SUBSTRING(t.VersionNumber, v1.v, v2.v - v1.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v2.v, v3.v - v2.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v3.v, v4.v - v3.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v4.v, v5.v - v4.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v5.v, 999) AS int) ``` All fields of a version number are extracted one by one and converted to integers, which are then used for sorting. (Basically, [@Brian](https://stackoverflow.com/questions/7870945/version-number-sorting-in-sql-server/7871016#7871016)'s idea, as it turns out.)
Check these helps you Select \* From @tblVersion order by replace(VersionNumber,'.','')
7,870,945
I have a table that stores the versions as under ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') Select * From @tblVersion VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` My requirement is that I need to sort them so that the output will be ``` VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.3.109.1 1.4.8.66 1.4.11.14.7 ``` But if do a simple order by it does not work as expected ``` Select VersionNumber From @tblVersion Order By VersionNumber VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` Help needed
2011/10/24
[ "https://Stackoverflow.com/questions/7870945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111663/" ]
If you are using SQL Server 2008 or later, you can leverage the hierarchyID data type: ``` select * from @tblVersion order by CAST('/'+REPLACE(VersionNumber,'.','/')+'/' as hierarchyID) ```
Check these helps you Select \* From @tblVersion order by replace(VersionNumber,'.','')
7,870,945
I have a table that stores the versions as under ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') Select * From @tblVersion VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` My requirement is that I need to sort them so that the output will be ``` VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.3.109.1 1.4.8.66 1.4.11.14.7 ``` But if do a simple order by it does not work as expected ``` Select VersionNumber From @tblVersion Order By VersionNumber VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` Help needed
2011/10/24
[ "https://Stackoverflow.com/questions/7870945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111663/" ]
If you are using SQL Server 2008 or later, you can leverage the hierarchyID data type: ``` select * from @tblVersion order by CAST('/'+REPLACE(VersionNumber,'.','/')+'/' as hierarchyID) ```
If you are on SQL Server 2005 or later and the number of possible fields in version numbers is fixed, you could try the following approach: ``` SELECT t.* FROM @tblVersion t CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, 1), 0)) v1 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v1.v + 1), 0)) v2 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v2.v + 1), 0)) v3 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v3.v + 1), 0)) v4 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v4.v + 1), 0)) v5 ORDER BY CAST(SUBSTRING(t.VersionNumber, v1.v, v2.v - v1.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v2.v, v3.v - v2.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v3.v, v4.v - v3.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v4.v, v5.v - v4.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v5.v, 999) AS int) ``` All fields of a version number are extracted one by one and converted to integers, which are then used for sorting. (Basically, [@Brian](https://stackoverflow.com/questions/7870945/version-number-sorting-in-sql-server/7871016#7871016)'s idea, as it turns out.)
7,870,945
I have a table that stores the versions as under ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') Select * From @tblVersion VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` My requirement is that I need to sort them so that the output will be ``` VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.3.109.1 1.4.8.66 1.4.11.14.7 ``` But if do a simple order by it does not work as expected ``` Select VersionNumber From @tblVersion Order By VersionNumber VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` Help needed
2011/10/24
[ "https://Stackoverflow.com/questions/7870945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111663/" ]
This is generally called natural sort and there is no easy way to do it in SQL Server. Generally the data needs to be broken into fields or to fixed length segments of a field. It can be sorted on those field(s) for the desired order. ``` VersionNumber VersionSort 1.3.1 0001.0003.0001 1.3.2.5 0001.0003.0002.0005 1.4.1.7.12 0001.0004.0001.0007.0012 1.4.11.14.7 0001.0004.0011.0014.0007 1.4.3.109.1 0001.0004.0003.0109.0001 1.4.8.66 0001.0004.0008.0066 ```
If you are on SQL Server 2005 or later and the number of possible fields in version numbers is fixed, you could try the following approach: ``` SELECT t.* FROM @tblVersion t CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, 1), 0)) v1 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v1.v + 1), 0)) v2 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v2.v + 1), 0)) v3 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v3.v + 1), 0)) v4 CROSS APPLY (SELECT v = NULLIF(CHARINDEX('.', '.' + t.VersionNumber, v4.v + 1), 0)) v5 ORDER BY CAST(SUBSTRING(t.VersionNumber, v1.v, v2.v - v1.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v2.v, v3.v - v2.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v3.v, v4.v - v3.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v4.v, v5.v - v4.v - 1) AS int), CAST(SUBSTRING(t.VersionNumber, v5.v, 999) AS int) ``` All fields of a version number are extracted one by one and converted to integers, which are then used for sorting. (Basically, [@Brian](https://stackoverflow.com/questions/7870945/version-number-sorting-in-sql-server/7871016#7871016)'s idea, as it turns out.)
7,870,945
I have a table that stores the versions as under ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') Select * From @tblVersion VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` My requirement is that I need to sort them so that the output will be ``` VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.3.109.1 1.4.8.66 1.4.11.14.7 ``` But if do a simple order by it does not work as expected ``` Select VersionNumber From @tblVersion Order By VersionNumber VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` Help needed
2011/10/24
[ "https://Stackoverflow.com/questions/7870945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111663/" ]
Implementation of Brain's Solution ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') --Select * From @tblVersion ;With CTE AS ( Select Rn = Row_Number() Over(Order By (Select 1)) ,VersionNumber From @tblVersion ) ,CTESplit AS ( SELECT F1.Rn, F1.VersionNumber, VersionSort = Case When Len(O.VersionSort) = 1 Then '000' + O.VersionSort When Len(O.VersionSort) = 2 Then '00' + O.VersionSort When Len(O.VersionSort) = 3 Then '0' + O.VersionSort When Len(O.VersionSort) = 4 Then O.VersionSort End FROM ( SELECT *, cast('<X>'+replace(F.VersionNumber,'.','</X><X>')+'</X>' as XML) as xmlfilter from CTE F )F1 CROSS APPLY ( SELECT fdata.D.value('.','varchar(50)') as VersionSort FROM f1.xmlfilter.nodes('X') as fdata(D)) O ) ,CTE3 As( Select --Rn --, VersionNumber ,SortableVersion = Stuff( (Select '.' + Cast(VersionSort As Varchar(100)) From CTESplit c2 Where c2.Rn = c1.Rn For Xml Path('')),1,1,'') From CTESplit c1 Group By c1.Rn,c1.VersionNumber ) Select VersionNumber From CTE3 Order By SortableVersion ```
Check these helps you Select \* From @tblVersion order by replace(VersionNumber,'.','')
7,870,945
I have a table that stores the versions as under ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') Select * From @tblVersion VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` My requirement is that I need to sort them so that the output will be ``` VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.3.109.1 1.4.8.66 1.4.11.14.7 ``` But if do a simple order by it does not work as expected ``` Select VersionNumber From @tblVersion Order By VersionNumber VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` Help needed
2011/10/24
[ "https://Stackoverflow.com/questions/7870945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111663/" ]
This is generally called natural sort and there is no easy way to do it in SQL Server. Generally the data needs to be broken into fields or to fixed length segments of a field. It can be sorted on those field(s) for the desired order. ``` VersionNumber VersionSort 1.3.1 0001.0003.0001 1.3.2.5 0001.0003.0002.0005 1.4.1.7.12 0001.0004.0001.0007.0012 1.4.11.14.7 0001.0004.0011.0014.0007 1.4.3.109.1 0001.0004.0003.0109.0001 1.4.8.66 0001.0004.0008.0066 ```
Check these helps you Select \* From @tblVersion order by replace(VersionNumber,'.','')
7,870,945
I have a table that stores the versions as under ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') Select * From @tblVersion VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` My requirement is that I need to sort them so that the output will be ``` VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.3.109.1 1.4.8.66 1.4.11.14.7 ``` But if do a simple order by it does not work as expected ``` Select VersionNumber From @tblVersion Order By VersionNumber VersionNumber 1.3.1 1.3.2.5 1.4.1.7.12 1.4.11.14.7 1.4.3.109.1 1.4.8.66 ``` Help needed
2011/10/24
[ "https://Stackoverflow.com/questions/7870945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111663/" ]
Implementation of Brain's Solution ``` Declare @tblVersion table(VersionNumber varchar(100)) Insert into @tblVersion Values('1.3.1') Insert into @tblVersion Values('1.3.2.5') Insert into @tblVersion Values('1.4.1.7.12') Insert into @tblVersion Values('1.4.11.14.7') Insert into @tblVersion Values('1.4.3.109.1') Insert into @tblVersion Values('1.4.8.66') --Select * From @tblVersion ;With CTE AS ( Select Rn = Row_Number() Over(Order By (Select 1)) ,VersionNumber From @tblVersion ) ,CTESplit AS ( SELECT F1.Rn, F1.VersionNumber, VersionSort = Case When Len(O.VersionSort) = 1 Then '000' + O.VersionSort When Len(O.VersionSort) = 2 Then '00' + O.VersionSort When Len(O.VersionSort) = 3 Then '0' + O.VersionSort When Len(O.VersionSort) = 4 Then O.VersionSort End FROM ( SELECT *, cast('<X>'+replace(F.VersionNumber,'.','</X><X>')+'</X>' as XML) as xmlfilter from CTE F )F1 CROSS APPLY ( SELECT fdata.D.value('.','varchar(50)') as VersionSort FROM f1.xmlfilter.nodes('X') as fdata(D)) O ) ,CTE3 As( Select --Rn --, VersionNumber ,SortableVersion = Stuff( (Select '.' + Cast(VersionSort As Varchar(100)) From CTESplit c2 Where c2.Rn = c1.Rn For Xml Path('')),1,1,'') From CTESplit c1 Group By c1.Rn,c1.VersionNumber ) Select VersionNumber From CTE3 Order By SortableVersion ```
I cannot see the solution using standard sorting etc, but I think you need the UDF that adds the "0" symbols before each symbol, like ``` 001.003.001 001.003.002.005 001.004.001.007.012 001.004.011.014.007 001.004.003.109.001 001.004.008.066 ``` and then sort by these changed values
2,865,662
So I know that set $S=\{(x,y,z)| x,y,z\in \mathbb{Z}\}$ is a subset of vector space $\mathbb{R}^3$. Specifically, it is worded in our lecture that it is a " subset of $(\mathbb{R}^3, \oplus, \odot)$ , where $\oplus$ and $\odot$ are the usual vector addition and scalar multiplication." My teacher has stated in our lecture that this set $S$ is not a subspace of $\mathbb{R}^3$. But from what I can tell $S$ is: 1. Closed under addition 2. Closed under multiplication 3. Contains a zero vector $(0,0,0)$ How is it not a subspace of $\mathbb{R}^3$, what am I missing?
2018/07/28
[ "https://math.stackexchange.com/questions/2865662", "https://math.stackexchange.com", "https://math.stackexchange.com/users/580225/" ]
$(1,0,0)$ belongs to $S$. Scale this by the real scalar $1/2$ and obtain $(1/2,0,0)$ which is not in $S$. Hence $S$ is not a subspace.
It is not closed under multiplication. Take $\lambda=\sqrt{2}$ and any vector $v=(a,b,c)\in S$. Since $a,b,c\in \Bbb Z$ then $a\sqrt{2}, b\sqrt{2}, c\sqrt{2}\notin \Bbb Z$. Then $\lambda\cdot v \notin S$.
2,865,662
So I know that set $S=\{(x,y,z)| x,y,z\in \mathbb{Z}\}$ is a subset of vector space $\mathbb{R}^3$. Specifically, it is worded in our lecture that it is a " subset of $(\mathbb{R}^3, \oplus, \odot)$ , where $\oplus$ and $\odot$ are the usual vector addition and scalar multiplication." My teacher has stated in our lecture that this set $S$ is not a subspace of $\mathbb{R}^3$. But from what I can tell $S$ is: 1. Closed under addition 2. Closed under multiplication 3. Contains a zero vector $(0,0,0)$ How is it not a subspace of $\mathbb{R}^3$, what am I missing?
2018/07/28
[ "https://math.stackexchange.com/questions/2865662", "https://math.stackexchange.com", "https://math.stackexchange.com/users/580225/" ]
It is not closed under multiplication. Take $\lambda=\sqrt{2}$ and any vector $v=(a,b,c)\in S$. Since $a,b,c\in \Bbb Z$ then $a\sqrt{2}, b\sqrt{2}, c\sqrt{2}\notin \Bbb Z$. Then $\lambda\cdot v \notin S$.
Edit: User Randall pointed out that I misread the question. (I assumed S was under some invalid field.) First lets look at the definition of a subspace: 1. All products and sums composed of elements within the subspace also are in the subspace. 2. All elements in the subspace must be able to be scaled by the vector space surrounding the subspace. 3. 0 is also an element of the subspace. You remembered rule 1 and 3 however, it's clear S is violating rule 2. In order for S to be a subset of $R^3$, all elements within S that are scaled by any number within R are also an element of S.
2,865,662
So I know that set $S=\{(x,y,z)| x,y,z\in \mathbb{Z}\}$ is a subset of vector space $\mathbb{R}^3$. Specifically, it is worded in our lecture that it is a " subset of $(\mathbb{R}^3, \oplus, \odot)$ , where $\oplus$ and $\odot$ are the usual vector addition and scalar multiplication." My teacher has stated in our lecture that this set $S$ is not a subspace of $\mathbb{R}^3$. But from what I can tell $S$ is: 1. Closed under addition 2. Closed under multiplication 3. Contains a zero vector $(0,0,0)$ How is it not a subspace of $\mathbb{R}^3$, what am I missing?
2018/07/28
[ "https://math.stackexchange.com/questions/2865662", "https://math.stackexchange.com", "https://math.stackexchange.com/users/580225/" ]
$(1,0,0)$ belongs to $S$. Scale this by the real scalar $1/2$ and obtain $(1/2,0,0)$ which is not in $S$. Hence $S$ is not a subspace.
Edit: User Randall pointed out that I misread the question. (I assumed S was under some invalid field.) First lets look at the definition of a subspace: 1. All products and sums composed of elements within the subspace also are in the subspace. 2. All elements in the subspace must be able to be scaled by the vector space surrounding the subspace. 3. 0 is also an element of the subspace. You remembered rule 1 and 3 however, it's clear S is violating rule 2. In order for S to be a subset of $R^3$, all elements within S that are scaled by any number within R are also an element of S.
22,711,375
I started learning C++ using a ebook and got interupted by a few lines, which I think are a bit outdated. Anyway, what I am trying to do is using a preprocessor directive as a function parameter which isnt working: ``` #define TitleLabelId 1000; //.... hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` This gives me an compile error, while this will give me a correct result: ``` HMENU hm = (HMENU)TitleLabelId; hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` I tried to outsource the Label Text aswell but unfortunateley it didnt work either using the following directive: ``` #define TitleText L"Blob Color War"; ``` Is it anything with the syntax I have overseen? Thanks in advance!
2014/03/28
[ "https://Stackoverflow.com/questions/22711375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985798/" ]
I was getting the same error but I could not even start the hive shell. After trying the very useful hive debug command: ``` hive -hiveconf hive.root.logger=DEBUG,console ``` I was able to see that Hive could not find a valid Kerberos TGT. You will see in the debug info something about SASL negotiation failed and no valid Kerberos TGT. My solution was to run ``` kinit ``` before running the hive CLI.
If it is in local machine, looks like you have another terminal opened with hive shell/session. You can have only one session using embedded derby data base. Close all other hive sessions and try.
22,711,375
I started learning C++ using a ebook and got interupted by a few lines, which I think are a bit outdated. Anyway, what I am trying to do is using a preprocessor directive as a function parameter which isnt working: ``` #define TitleLabelId 1000; //.... hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` This gives me an compile error, while this will give me a correct result: ``` HMENU hm = (HMENU)TitleLabelId; hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` I tried to outsource the Label Text aswell but unfortunateley it didnt work either using the following directive: ``` #define TitleText L"Blob Color War"; ``` Is it anything with the syntax I have overseen? Thanks in advance!
2014/03/28
[ "https://Stackoverflow.com/questions/22711375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985798/" ]
Looks like problem with your metastore. If you are using the default hive metastore embedded derby. Lock file would be there in case of abnormal exit. if you remove that lock file this issue would be solved ``` rm metastore_db/*.lck ```
Restarting the virtual machine or system should also release the lock.
22,711,375
I started learning C++ using a ebook and got interupted by a few lines, which I think are a bit outdated. Anyway, what I am trying to do is using a preprocessor directive as a function parameter which isnt working: ``` #define TitleLabelId 1000; //.... hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` This gives me an compile error, while this will give me a correct result: ``` HMENU hm = (HMENU)TitleLabelId; hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` I tried to outsource the Label Text aswell but unfortunateley it didnt work either using the following directive: ``` #define TitleText L"Blob Color War"; ``` Is it anything with the syntax I have overseen? Thanks in advance!
2014/03/28
[ "https://Stackoverflow.com/questions/22711375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985798/" ]
Being a newbie i got the same set of errors. It was found that one of the daemons in my case namenode was not initiated. On installing hadoop it would be wise to make it a habit to hit he following commands : ps -ef | grep "namenode" ps -ef | grep "datanode" ps -ef | grep "tracker" One needs to check the relevant log if any of the daemon is not working.
I was facing the same issue--used the below steps to resolve it: 1. Create an file hive-site.xml and input the details (for Local/Prod mode). Make sure the below location exist /home/hadoop/bhishm/warehouse Example: ``` <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <configuration> <property> <name>hive.metastore.warehouse.dir</name> <value>/home/hadoop/bhishm/warehouse</value> <description> Local or HDFS directory where Hive keeps table contents. </description> </property> <property> <name>hive.metastore.local</name> <value>true</value> <description> Use false if a production metastore server is used. </description> </property> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:derby:;databaseName=/home/hadoop/bhishm/warehouse/metastore_db;create=true</value> <description> The JDBC connection URL. </description> </property> </configuration> ``` 2. Edit the hive-env.sh--> add the java path as the first line after reducing memory usage: Example: ``` # Hive Client memory usage can be an issue if a large number of clients # are running at the same time. The flags below have been useful in # reducing memory usage: # The java implementation to use. Required. export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk ``` 3. Run the hive query.
22,711,375
I started learning C++ using a ebook and got interupted by a few lines, which I think are a bit outdated. Anyway, what I am trying to do is using a preprocessor directive as a function parameter which isnt working: ``` #define TitleLabelId 1000; //.... hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` This gives me an compile error, while this will give me a correct result: ``` HMENU hm = (HMENU)TitleLabelId; hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` I tried to outsource the Label Text aswell but unfortunateley it didnt work either using the following directive: ``` #define TitleText L"Blob Color War"; ``` Is it anything with the syntax I have overseen? Thanks in advance!
2014/03/28
[ "https://Stackoverflow.com/questions/22711375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985798/" ]
``` hive> show databases; FAILED: Error in metadata: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.metastore.HiveMetaStoreClient FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask ``` To resolve this issue start the hadoop services first. ``` $ start-all.sh ``` Then I run ``` hive> show database; ``` It works fine for me.
When I used jdk 11, I deploymented hive on my master node and then those exceptions were thrown. Many methods I have tried but useless. Eventually I changed the version of jdk from 11 to 8, which used in master node. Then I started the hive successfully.
22,711,375
I started learning C++ using a ebook and got interupted by a few lines, which I think are a bit outdated. Anyway, what I am trying to do is using a preprocessor directive as a function parameter which isnt working: ``` #define TitleLabelId 1000; //.... hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` This gives me an compile error, while this will give me a correct result: ``` HMENU hm = (HMENU)TitleLabelId; hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` I tried to outsource the Label Text aswell but unfortunateley it didnt work either using the following directive: ``` #define TitleText L"Blob Color War"; ``` Is it anything with the syntax I have overseen? Thanks in advance!
2014/03/28
[ "https://Stackoverflow.com/questions/22711375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985798/" ]
I was getting the same error but I could not even start the hive shell. After trying the very useful hive debug command: ``` hive -hiveconf hive.root.logger=DEBUG,console ``` I was able to see that Hive could not find a valid Kerberos TGT. You will see in the debug info something about SASL negotiation failed and no valid Kerberos TGT. My solution was to run ``` kinit ``` before running the hive CLI.
I was facing the same issue--used the below steps to resolve it: 1. Create an file hive-site.xml and input the details (for Local/Prod mode). Make sure the below location exist /home/hadoop/bhishm/warehouse Example: ``` <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <configuration> <property> <name>hive.metastore.warehouse.dir</name> <value>/home/hadoop/bhishm/warehouse</value> <description> Local or HDFS directory where Hive keeps table contents. </description> </property> <property> <name>hive.metastore.local</name> <value>true</value> <description> Use false if a production metastore server is used. </description> </property> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:derby:;databaseName=/home/hadoop/bhishm/warehouse/metastore_db;create=true</value> <description> The JDBC connection URL. </description> </property> </configuration> ``` 2. Edit the hive-env.sh--> add the java path as the first line after reducing memory usage: Example: ``` # Hive Client memory usage can be an issue if a large number of clients # are running at the same time. The flags below have been useful in # reducing memory usage: # The java implementation to use. Required. export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk ``` 3. Run the hive query.
22,711,375
I started learning C++ using a ebook and got interupted by a few lines, which I think are a bit outdated. Anyway, what I am trying to do is using a preprocessor directive as a function parameter which isnt working: ``` #define TitleLabelId 1000; //.... hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` This gives me an compile error, while this will give me a correct result: ``` HMENU hm = (HMENU)TitleLabelId; hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` I tried to outsource the Label Text aswell but unfortunateley it didnt work either using the following directive: ``` #define TitleText L"Blob Color War"; ``` Is it anything with the syntax I have overseen? Thanks in advance!
2014/03/28
[ "https://Stackoverflow.com/questions/22711375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985798/" ]
Looks like problem with your metastore. If you are using the default hive metastore embedded derby. Lock file would be there in case of abnormal exit. if you remove that lock file this issue would be solved ``` rm metastore_db/*.lck ```
I was facing the same issue there are some important point's that could be resolve this problem. **1.Put the following at the beginning of hive-site.xml** ``` <property> <name>system:java.io.tmpdir</name> <value>/tmp/hive/java</value> </property> <property> <name>system:user.name</name> <value>${user.name}</value> </property> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:derby:,databaseName=$HIVE_HOME/metastore_db;create=true</value> <description>JDBC connect string for a JDBC metastore </description> </property> ``` this is set relative path in absolute URI and configuring Metastore where the database is stored **2.Remove `$HIVE_HOME/metastore_db` But Be aware, this will remove your schema completely!** **3.Now,You must Initialize Derby database.By default, Hive uses Derby database** > > $HIVE\_HOME/bin/schematool -initSchema -dbType derby > > > also I suppose that your environment variable has been set correctly ,if not please check them that are looking like below: ``` export HADOOP_HOME=/usr/local/hadoop export PATH=$PATH:$HADOOP_HOME/bin export PATH=$PATH:$HADOOP_HOME/sbin export HIVE_HOME=/usr/lib/hive export PATH=$PATH:$HIVE_HOME/bin ``` and then run `hive` command and type `show databases;`
22,711,375
I started learning C++ using a ebook and got interupted by a few lines, which I think are a bit outdated. Anyway, what I am trying to do is using a preprocessor directive as a function parameter which isnt working: ``` #define TitleLabelId 1000; //.... hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` This gives me an compile error, while this will give me a correct result: ``` HMENU hm = (HMENU)TitleLabelId; hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` I tried to outsource the Label Text aswell but unfortunateley it didnt work either using the following directive: ``` #define TitleText L"Blob Color War"; ``` Is it anything with the syntax I have overseen? Thanks in advance!
2014/03/28
[ "https://Stackoverflow.com/questions/22711375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985798/" ]
The answer is located in <http://www.cloudera.com/content/cloudera-content/cloudera-docs/CDH5/5.0/CDH5-Installation-Guide/cdh5ig_hive_schema_tool.html> To suppress the schema check and allow the metastore to implicitly modify the schema, you need to set the hive.metastore.schema.verification configuration property to false in hive-site.xml.
I was facing the same issue there are some important point's that could be resolve this problem. **1.Put the following at the beginning of hive-site.xml** ``` <property> <name>system:java.io.tmpdir</name> <value>/tmp/hive/java</value> </property> <property> <name>system:user.name</name> <value>${user.name}</value> </property> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:derby:,databaseName=$HIVE_HOME/metastore_db;create=true</value> <description>JDBC connect string for a JDBC metastore </description> </property> ``` this is set relative path in absolute URI and configuring Metastore where the database is stored **2.Remove `$HIVE_HOME/metastore_db` But Be aware, this will remove your schema completely!** **3.Now,You must Initialize Derby database.By default, Hive uses Derby database** > > $HIVE\_HOME/bin/schematool -initSchema -dbType derby > > > also I suppose that your environment variable has been set correctly ,if not please check them that are looking like below: ``` export HADOOP_HOME=/usr/local/hadoop export PATH=$PATH:$HADOOP_HOME/bin export PATH=$PATH:$HADOOP_HOME/sbin export HIVE_HOME=/usr/lib/hive export PATH=$PATH:$HIVE_HOME/bin ``` and then run `hive` command and type `show databases;`
22,711,375
I started learning C++ using a ebook and got interupted by a few lines, which I think are a bit outdated. Anyway, what I am trying to do is using a preprocessor directive as a function parameter which isnt working: ``` #define TitleLabelId 1000; //.... hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` This gives me an compile error, while this will give me a correct result: ``` HMENU hm = (HMENU)TitleLabelId; hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` I tried to outsource the Label Text aswell but unfortunateley it didnt work either using the following directive: ``` #define TitleText L"Blob Color War"; ``` Is it anything with the syntax I have overseen? Thanks in advance!
2014/03/28
[ "https://Stackoverflow.com/questions/22711375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985798/" ]
``` rm metastore_db/*.lck ``` It works for me, too. It can be found in your `home/user` directory. You can use the `locate` command to find it: `locate metastore_db` After removing the lock files, close the current session. Call hive shell in new session
this could due to more than one "metastore\_db". Remove "metastore\_db", restart hadoop cluster and open hive shell from $HIVE\_HOME/bin folder
22,711,375
I started learning C++ using a ebook and got interupted by a few lines, which I think are a bit outdated. Anyway, what I am trying to do is using a preprocessor directive as a function parameter which isnt working: ``` #define TitleLabelId 1000; //.... hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` This gives me an compile error, while this will give me a correct result: ``` HMENU hm = (HMENU)TitleLabelId; hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` I tried to outsource the Label Text aswell but unfortunateley it didnt work either using the following directive: ``` #define TitleText L"Blob Color War"; ``` Is it anything with the syntax I have overseen? Thanks in advance!
2014/03/28
[ "https://Stackoverflow.com/questions/22711375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985798/" ]
This could be an issue with the metastore like sachinjose described or a connection issue. Run hive console in debug mode like so: `hive -hiveconf hive.root.logger=DEBUG,console` Then execute a simple query like `show tables;` and see what happens. I ran into this issue after restarting a namenode and it was due to the wrong host being set in the configuration files (ec2 generates new private IP/hostname when restarted).
If it is in local machine, looks like you have another terminal opened with hive shell/session. You can have only one session using embedded derby data base. Close all other hive sessions and try.
22,711,375
I started learning C++ using a ebook and got interupted by a few lines, which I think are a bit outdated. Anyway, what I am trying to do is using a preprocessor directive as a function parameter which isnt working: ``` #define TitleLabelId 1000; //.... hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` This gives me an compile error, while this will give me a correct result: ``` HMENU hm = (HMENU)TitleLabelId; hTitleText = CreateWindow(L"STATIC", L"Test Text", WS_VISIBLE | WS_CHILD, 0, 0, 300, 20, hWnd, (HMENU)TitleLabelId, hInst, NULL); ``` I tried to outsource the Label Text aswell but unfortunateley it didnt work either using the following directive: ``` #define TitleText L"Blob Color War"; ``` Is it anything with the syntax I have overseen? Thanks in advance!
2014/03/28
[ "https://Stackoverflow.com/questions/22711375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985798/" ]
The answer is located in <http://www.cloudera.com/content/cloudera-content/cloudera-docs/CDH5/5.0/CDH5-Installation-Guide/cdh5ig_hive_schema_tool.html> To suppress the schema check and allow the metastore to implicitly modify the schema, you need to set the hive.metastore.schema.verification configuration property to false in hive-site.xml.
I was facing the same issue--used the below steps to resolve it: 1. Create an file hive-site.xml and input the details (for Local/Prod mode). Make sure the below location exist /home/hadoop/bhishm/warehouse Example: ``` <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <configuration> <property> <name>hive.metastore.warehouse.dir</name> <value>/home/hadoop/bhishm/warehouse</value> <description> Local or HDFS directory where Hive keeps table contents. </description> </property> <property> <name>hive.metastore.local</name> <value>true</value> <description> Use false if a production metastore server is used. </description> </property> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:derby:;databaseName=/home/hadoop/bhishm/warehouse/metastore_db;create=true</value> <description> The JDBC connection URL. </description> </property> </configuration> ``` 2. Edit the hive-env.sh--> add the java path as the first line after reducing memory usage: Example: ``` # Hive Client memory usage can be an issue if a large number of clients # are running at the same time. The flags below have been useful in # reducing memory usage: # The java implementation to use. Required. export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk ``` 3. Run the hive query.
5,175,810
> > **Possible Duplicate:** > > [How to avoid scientific notation for large numbers in javascript?](https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript) > > > Hi All, Doing something like this ``` alert(999999999999999999999999999999999999999999999999); ``` results in this ![Javascript Popup 1e+48](https://i.stack.imgur.com/YQVoz.png) How to i stop converting a number to a string from saying 1e+XX or Infinity?
2011/03/03
[ "https://Stackoverflow.com/questions/5175810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/531746/" ]
You're close: ``` validates_length_of :some_field, :within => 0..10, :allow_blank => true ``` You can change the zero minimum size, since it will only be triggered when there is some input. See also the validation [docs](http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_length_of).
Maybe it's a nil value instead of an empty string that it gets validated against ? ``` irb(main):006:0> ''.length => 0 irb(main):007:0> nil.length NoMethodError: You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.length from (irb):7 ```
5,175,810
> > **Possible Duplicate:** > > [How to avoid scientific notation for large numbers in javascript?](https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript) > > > Hi All, Doing something like this ``` alert(999999999999999999999999999999999999999999999999); ``` results in this ![Javascript Popup 1e+48](https://i.stack.imgur.com/YQVoz.png) How to i stop converting a number to a string from saying 1e+XX or Infinity?
2011/03/03
[ "https://Stackoverflow.com/questions/5175810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/531746/" ]
You can pass `:allow_blank` as an option to allow this: ``` validates_length_of :some_field, :within => 0..10, :allow_blank => true ```
Maybe it's a nil value instead of an empty string that it gets validated against ? ``` irb(main):006:0> ''.length => 0 irb(main):007:0> nil.length NoMethodError: You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.length from (irb):7 ```
5,175,810
> > **Possible Duplicate:** > > [How to avoid scientific notation for large numbers in javascript?](https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript) > > > Hi All, Doing something like this ``` alert(999999999999999999999999999999999999999999999999); ``` results in this ![Javascript Popup 1e+48](https://i.stack.imgur.com/YQVoz.png) How to i stop converting a number to a string from saying 1e+XX or Infinity?
2011/03/03
[ "https://Stackoverflow.com/questions/5175810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/531746/" ]
try: validates\_length\_of :some\_field, :within => [0..10], :if => :some\_field?
Maybe it's a nil value instead of an empty string that it gets validated against ? ``` irb(main):006:0> ''.length => 0 irb(main):007:0> nil.length NoMethodError: You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.length from (irb):7 ```
5,175,810
> > **Possible Duplicate:** > > [How to avoid scientific notation for large numbers in javascript?](https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript) > > > Hi All, Doing something like this ``` alert(999999999999999999999999999999999999999999999999); ``` results in this ![Javascript Popup 1e+48](https://i.stack.imgur.com/YQVoz.png) How to i stop converting a number to a string from saying 1e+XX or Infinity?
2011/03/03
[ "https://Stackoverflow.com/questions/5175810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/531746/" ]
You're close: ``` validates_length_of :some_field, :within => 0..10, :allow_blank => true ``` You can change the zero minimum size, since it will only be triggered when there is some input. See also the validation [docs](http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_length_of).
You can pass `:allow_blank` as an option to allow this: ``` validates_length_of :some_field, :within => 0..10, :allow_blank => true ```
5,175,810
> > **Possible Duplicate:** > > [How to avoid scientific notation for large numbers in javascript?](https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript) > > > Hi All, Doing something like this ``` alert(999999999999999999999999999999999999999999999999); ``` results in this ![Javascript Popup 1e+48](https://i.stack.imgur.com/YQVoz.png) How to i stop converting a number to a string from saying 1e+XX or Infinity?
2011/03/03
[ "https://Stackoverflow.com/questions/5175810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/531746/" ]
You're close: ``` validates_length_of :some_field, :within => 0..10, :allow_blank => true ``` You can change the zero minimum size, since it will only be triggered when there is some input. See also the validation [docs](http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_length_of).
try: validates\_length\_of :some\_field, :within => [0..10], :if => :some\_field?
6,884,690
Is there a PHP function that replaces `-` with `_` (underscores) ? Like ``` my-name ``` with ``` my_name ```
2011/07/30
[ "https://Stackoverflow.com/questions/6884690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/870873/" ]
`str_replace('-', '_', $name)`
There's, but it's not called replace\_hyphen, it's str\_replace `str_replace('-', '_', $str);`
6,884,690
Is there a PHP function that replaces `-` with `_` (underscores) ? Like ``` my-name ``` with ``` my_name ```
2011/07/30
[ "https://Stackoverflow.com/questions/6884690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/870873/" ]
You need to use the return of str\_replace! ``` $name = str_replace('-', '_', $name); ```
There's, but it's not called replace\_hyphen, it's str\_replace `str_replace('-', '_', $str);`
6,884,690
Is there a PHP function that replaces `-` with `_` (underscores) ? Like ``` my-name ``` with ``` my_name ```
2011/07/30
[ "https://Stackoverflow.com/questions/6884690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/870873/" ]
`str_replace('-', '_', $name)`
Use this ``` str_replace("-", "_", "my-name"); ```
6,884,690
Is there a PHP function that replaces `-` with `_` (underscores) ? Like ``` my-name ``` with ``` my_name ```
2011/07/30
[ "https://Stackoverflow.com/questions/6884690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/870873/" ]
`str_replace('-', '_', $name)`
You need to use the return of str\_replace! ``` $name = str_replace('-', '_', $name); ```
6,884,690
Is there a PHP function that replaces `-` with `_` (underscores) ? Like ``` my-name ``` with ``` my_name ```
2011/07/30
[ "https://Stackoverflow.com/questions/6884690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/870873/" ]
You need to use the return of str\_replace! ``` $name = str_replace('-', '_', $name); ```
Use this ``` str_replace("-", "_", "my-name"); ```
68,763,252
I've built an ASP.net core Single tenant Web API that requires a token from Azure, I have also built a single tenant SPA via react that uses Azure to login Via MSAL-Brower. I want to use the token provided from azure when I log in to authenticate my client SPA to call my API. The token request comes back successfully but when I go to fetch I receive an error on my api stating that > > Did not match: validationParameters.ValidAudience: 'System.String' or validationParameters.ValidAudiences: 'System.String'. > > > I requested a token via MSAL Client method **acquireTokenSilent** with the scope of permissions established on Azure. Ive tried it all, Ive changed the ClientId and ResourceId in both the Client and the Web API. ``` const PostToDataBase = () => { const authenticationModule: AzureAuthenticationContext = new AzureAuthenticationContext(); const account = authenticationModule.myMSALObj.getAllAccounts()[0] const endpoint = { endpoint:"https://localhost:44309/api/values", scopes:[], // redacted for SO resourceId : "" // redacted for SO } async function postValues(value:string){ if(value.length < 1){ console.log("Value can not be null!") return; } console.log(account) if(account ){ console.log("acquiring token") authenticationModule.myMSALObj.acquireTokenSilent({ scopes: endpoint.scopes, account: account }).then(response => { console.log("token acquired posting to server") const headers = new Headers(); const bearer = `Bearer ${response.accessToken}`; headers.append("Authorization", bearer); headers.append("Content-Type", "'application/json'") const options = { method: "POST", headers: headers, bodyInit: JSON.stringify(value) }; return fetch(endpoint.endpoint, options) .then(response => console.log(response)) .catch(error => console.log(error)); }).catch(err => { console.error(err) if(err instanceof InteractionRequiredAuthError){ if(account ){ authenticationModule.myMSALObj.acquireTokenPopup({ scopes: endpoint.scopes }).then(response => { const headers = new Headers(); const bearer = `Bearer ${response.accessToken}`; headers.append("Authorization", bearer); const options = { method: "POST", headers: headers, body: value }; return fetch(endpoint.endpoint, options) .then(response => response.json()) .catch(error => console.log(error)); }).catch(err => console.error(err)) } } }) } } async function getValues(){ console.log(account) if(account ){ console.log("acquiring token") authenticationModule.myMSALObj.acquireTokenSilent({ scopes: endpoint.scopes, account: account }).then(response => { console.log("token acquired posting to server") const headers = new Headers(); const bearer = `Bearer ${response.accessToken}`; headers.append("Authorization", bearer); headers.append("Content-Type", "'application/json'") const options = { method: "GET", headers: headers }; return fetch(endpoint.endpoint, options) .then(response => response.json()) .then(res => setValues(res)) .catch(error => console.log(error)); }).catch(err => { console.error(err) if(err instanceof InteractionRequiredAuthError){ if(account ){ authenticationModule.myMSALObj.acquireTokenPopup({ scopes: endpoint.scopes }).then(response => { const headers = new Headers(); const bearer = `Bearer ${response.accessToken}`; headers.append("Authorization", bearer); const options = { method: "GET", headers: headers, }; return fetch(endpoint.endpoint, options) .then(response => response.json()) .then(res => setValues(res)) .catch(error => console.log(error)); }).catch(err => console.error(err)) } } }) } } const [values, setValues] = useState([]); const [inputValue, setInput] = useState(""); useEffect(() => { // async function getinit(){ // const values = await fetch("https://localhost:44309/api/values") // .then(res => res.json()) // .catch(e => // console.error(e)) // setValues(values) // console.log(values) // } getValues() }, [ getValues]) return ( <div> {values === undefined ? <p>no values to show</p> : values.map((n,i)=>( <p key={i}>{n}</p>))} <form> <input name="inputValues" value={inputValue} onChange={(e)=> setInput(e.target.value)} required></input> </form> <button onClick={() => postValues(inputValue)}>Post to Server</button> </div> ) } export default PostToDataBase ``` This is functional component that makes a call to the api, this pages is only accessible after the user logs in. ``` using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Authentication.JwtBearer; namespace McQuillingWebAPI { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //change to client url in production services.AddCors(o => o.AddPolicy("MyPolicy", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(opt => { opt.Audience = Configuration["AAD:ResourceId"]; opt.Authority = $"{Configuration["AAD:Instance"]}{Configuration["AAD:TenantId"]}"; }); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("MyPolicy"); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } ``` This is my startup class where I configure middleware for Authentication ``` using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Microsoft.Identity.Web.Resource; namespace McQuillingWebAPI.Controllers { [Authorize] [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [Authorize] [HttpPost] public IActionResult Post([FromBody] string value) { return Ok("Posted"); } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } } ``` this is one of the generated controllers that I'm testing authentication with
2021/08/12
[ "https://Stackoverflow.com/questions/68763252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3576722/" ]
This will work only in the recent versions of python ``` y = { key: y[key] for key in x if key in y} ``` For earlier versions you can check [collections.OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict)
Iterate over the keys and values of x and check if the key exists within y. ``` y = {key: y[key] for key, value in x.items() if key in y} ```
13,499,817
I have a few buttons in my app whose alpha is currently set to zero. These buttons are completely non-responsive, but as soon as I increase their alpha, they begin to respond. Is this expected behavior?
2012/11/21
[ "https://Stackoverflow.com/questions/13499817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199882/" ]
As per [Apple's documentation](http://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instm/UIView/hitTest:withEvent:) for `UIView`'s `hitTest:withEvent:` method: > > This method ignores view objects that are hidden, that have disabled > user interactions, or have an alpha level less than 0.01. > > > So any `UIView` that has alpha lower than 0.01 will be ignored by the touch events processing system, i.e. will **not** receive touch.
When the alpha is 0 they are unresponsive, as alpha = 0 is like hidden = YES and you can't click a hidden button.
13,499,817
I have a few buttons in my app whose alpha is currently set to zero. These buttons are completely non-responsive, but as soon as I increase their alpha, they begin to respond. Is this expected behavior?
2012/11/21
[ "https://Stackoverflow.com/questions/13499817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199882/" ]
I'm a little late to the game but you could always set the UIButton background color to clearcolor. This would keep them active. In my case, I am pulsating a button to give it a glowing effect but to do this, I must set it's background to clear, then add a UIIMageView as a subview and add the effect to the image, NOT the button. Hope this helps anyone else with this problem.
When the alpha is 0 they are unresponsive, as alpha = 0 is like hidden = YES and you can't click a hidden button.
13,499,817
I have a few buttons in my app whose alpha is currently set to zero. These buttons are completely non-responsive, but as soon as I increase their alpha, they begin to respond. Is this expected behavior?
2012/11/21
[ "https://Stackoverflow.com/questions/13499817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199882/" ]
As per [Apple's documentation](http://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instm/UIView/hitTest:withEvent:) for `UIView`'s `hitTest:withEvent:` method: > > This method ignores view objects that are hidden, that have disabled > user interactions, or have an alpha level less than 0.01. > > > So any `UIView` that has alpha lower than 0.01 will be ignored by the touch events processing system, i.e. will **not** receive touch.
I'm a little late to the game but you could always set the UIButton background color to clearcolor. This would keep them active. In my case, I am pulsating a button to give it a glowing effect but to do this, I must set it's background to clear, then add a UIIMageView as a subview and add the effect to the image, NOT the button. Hope this helps anyone else with this problem.
13,499,817
I have a few buttons in my app whose alpha is currently set to zero. These buttons are completely non-responsive, but as soon as I increase their alpha, they begin to respond. Is this expected behavior?
2012/11/21
[ "https://Stackoverflow.com/questions/13499817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199882/" ]
As per [Apple's documentation](http://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instm/UIView/hitTest:withEvent:) for `UIView`'s `hitTest:withEvent:` method: > > This method ignores view objects that are hidden, that have disabled > user interactions, or have an alpha level less than 0.01. > > > So any `UIView` that has alpha lower than 0.01 will be ignored by the touch events processing system, i.e. will **not** receive touch.
Yes, the least alpha amount should be `3.0 / 255.0` for touch event to not be ignored.
13,499,817
I have a few buttons in my app whose alpha is currently set to zero. These buttons are completely non-responsive, but as soon as I increase their alpha, they begin to respond. Is this expected behavior?
2012/11/21
[ "https://Stackoverflow.com/questions/13499817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199882/" ]
I'm a little late to the game but you could always set the UIButton background color to clearcolor. This would keep them active. In my case, I am pulsating a button to give it a glowing effect but to do this, I must set it's background to clear, then add a UIIMageView as a subview and add the effect to the image, NOT the button. Hope this helps anyone else with this problem.
Yes, the least alpha amount should be `3.0 / 255.0` for touch event to not be ignored.
59,212,771
I am creating two docker containers one front end and another one is .net core API. But when i call the API from the front end, I am getting an exception as follows, > > SocketException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > HttpRequestException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > I have also added a docker compose file to enable multi-container deployment but of no use. This is yml file as follows, ``` services: dockerdemofrontend: image: ${DOCKER_REGISTRY-}dockerdemofrontend build: context: . dockerfile: DockerDemoFrontEnd/Dockerfile dockerdemoapi: image: ${DOCKER_REGISTRY-}dockerdemoapi build: context: . dockerfile: DockerDemoAPI/Dockerfile ``` I am feeling like those two networks are different. We need to do something in order to get these two talking. Please help me in this regard.
2019/12/06
[ "https://Stackoverflow.com/questions/59212771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945784/" ]
I had this error with a clean install on MacOS X (Mojave), and after trial and error discovered that the main user who is running flutter debug needs to be an admin user. Clue was the line: ``` log: Must be admin to run 'stream' command ``` when running from command line. After this VS Code and command line work.
Try to change flutter channel to beta using "flutter channel beta". it worked for me to fix issue which is because flutter version is updated to "v1.12.13+hotfix.5".
59,212,771
I am creating two docker containers one front end and another one is .net core API. But when i call the API from the front end, I am getting an exception as follows, > > SocketException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > HttpRequestException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > I have also added a docker compose file to enable multi-container deployment but of no use. This is yml file as follows, ``` services: dockerdemofrontend: image: ${DOCKER_REGISTRY-}dockerdemofrontend build: context: . dockerfile: DockerDemoFrontEnd/Dockerfile dockerdemoapi: image: ${DOCKER_REGISTRY-}dockerdemoapi build: context: . dockerfile: DockerDemoAPI/Dockerfile ``` I am feeling like those two networks are different. We need to do something in order to get these two talking. Please help me in this regard.
2019/12/06
[ "https://Stackoverflow.com/questions/59212771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945784/" ]
I ended reinstalling flutter sdk. Ubuntu 16.04 VSCODE
Try to downgrade the libglvnd package to version 1.2.0 in arch linux.
59,212,771
I am creating two docker containers one front end and another one is .net core API. But when i call the API from the front end, I am getting an exception as follows, > > SocketException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > HttpRequestException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > I have also added a docker compose file to enable multi-container deployment but of no use. This is yml file as follows, ``` services: dockerdemofrontend: image: ${DOCKER_REGISTRY-}dockerdemofrontend build: context: . dockerfile: DockerDemoFrontEnd/Dockerfile dockerdemoapi: image: ${DOCKER_REGISTRY-}dockerdemoapi build: context: . dockerfile: DockerDemoAPI/Dockerfile ``` I am feeling like those two networks are different. We need to do something in order to get these two talking. Please help me in this regard.
2019/12/06
[ "https://Stackoverflow.com/questions/59212771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945784/" ]
Run `flutter clean`. This works for me.
Started with Flutter 12. It seems that the user must be admin now. Rolling back to a previous Flutter version will do for now. ``` flutter version v1.9.1+hotfix.6 ```
59,212,771
I am creating two docker containers one front end and another one is .net core API. But when i call the API from the front end, I am getting an exception as follows, > > SocketException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > HttpRequestException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > I have also added a docker compose file to enable multi-container deployment but of no use. This is yml file as follows, ``` services: dockerdemofrontend: image: ${DOCKER_REGISTRY-}dockerdemofrontend build: context: . dockerfile: DockerDemoFrontEnd/Dockerfile dockerdemoapi: image: ${DOCKER_REGISTRY-}dockerdemoapi build: context: . dockerfile: DockerDemoAPI/Dockerfile ``` I am feeling like those two networks are different. We need to do something in order to get these two talking. Please help me in this regard.
2019/12/06
[ "https://Stackoverflow.com/questions/59212771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945784/" ]
Run `flutter clean`. This works for me.
I ended reinstalling flutter sdk. Ubuntu 16.04 VSCODE
59,212,771
I am creating two docker containers one front end and another one is .net core API. But when i call the API from the front end, I am getting an exception as follows, > > SocketException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > HttpRequestException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > I have also added a docker compose file to enable multi-container deployment but of no use. This is yml file as follows, ``` services: dockerdemofrontend: image: ${DOCKER_REGISTRY-}dockerdemofrontend build: context: . dockerfile: DockerDemoFrontEnd/Dockerfile dockerdemoapi: image: ${DOCKER_REGISTRY-}dockerdemoapi build: context: . dockerfile: DockerDemoAPI/Dockerfile ``` I am feeling like those two networks are different. We need to do something in order to get these two talking. Please help me in this regard.
2019/12/06
[ "https://Stackoverflow.com/questions/59212771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945784/" ]
I ended reinstalling flutter sdk. Ubuntu 16.04 VSCODE
Started with Flutter 12. It seems that the user must be admin now. Rolling back to a previous Flutter version will do for now. ``` flutter version v1.9.1+hotfix.6 ```
59,212,771
I am creating two docker containers one front end and another one is .net core API. But when i call the API from the front end, I am getting an exception as follows, > > SocketException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > HttpRequestException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > I have also added a docker compose file to enable multi-container deployment but of no use. This is yml file as follows, ``` services: dockerdemofrontend: image: ${DOCKER_REGISTRY-}dockerdemofrontend build: context: . dockerfile: DockerDemoFrontEnd/Dockerfile dockerdemoapi: image: ${DOCKER_REGISTRY-}dockerdemoapi build: context: . dockerfile: DockerDemoAPI/Dockerfile ``` I am feeling like those two networks are different. We need to do something in order to get these two talking. Please help me in this regard.
2019/12/06
[ "https://Stackoverflow.com/questions/59212771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945784/" ]
Run `flutter clean`. This works for me.
I had this error with a clean install on MacOS X (Mojave), and after trial and error discovered that the main user who is running flutter debug needs to be an admin user. Clue was the line: ``` log: Must be admin to run 'stream' command ``` when running from command line. After this VS Code and command line work.
59,212,771
I am creating two docker containers one front end and another one is .net core API. But when i call the API from the front end, I am getting an exception as follows, > > SocketException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > HttpRequestException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > I have also added a docker compose file to enable multi-container deployment but of no use. This is yml file as follows, ``` services: dockerdemofrontend: image: ${DOCKER_REGISTRY-}dockerdemofrontend build: context: . dockerfile: DockerDemoFrontEnd/Dockerfile dockerdemoapi: image: ${DOCKER_REGISTRY-}dockerdemoapi build: context: . dockerfile: DockerDemoAPI/Dockerfile ``` I am feeling like those two networks are different. We need to do something in order to get these two talking. Please help me in this regard.
2019/12/06
[ "https://Stackoverflow.com/questions/59212771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945784/" ]
Build always works on my VS code normally. Updating to the latest Flutter 1.12 also started showing this and most times, my code either shows up on my device first before showing that debug has started or the program just quits. Any fix with VS code because I am not an Android Studio fan.
This started occuring after i updated xcode to 14.1. Simple Restarting mac works with `flutter clean`
59,212,771
I am creating two docker containers one front end and another one is .net core API. But when i call the API from the front end, I am getting an exception as follows, > > SocketException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > HttpRequestException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > I have also added a docker compose file to enable multi-container deployment but of no use. This is yml file as follows, ``` services: dockerdemofrontend: image: ${DOCKER_REGISTRY-}dockerdemofrontend build: context: . dockerfile: DockerDemoFrontEnd/Dockerfile dockerdemoapi: image: ${DOCKER_REGISTRY-}dockerdemoapi build: context: . dockerfile: DockerDemoAPI/Dockerfile ``` I am feeling like those two networks are different. We need to do something in order to get these two talking. Please help me in this regard.
2019/12/06
[ "https://Stackoverflow.com/questions/59212771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945784/" ]
I had this error with a clean install on MacOS X (Mojave), and after trial and error discovered that the main user who is running flutter debug needs to be an admin user. Clue was the line: ``` log: Must be admin to run 'stream' command ``` when running from command line. After this VS Code and command line work.
I ended reinstalling flutter sdk. Ubuntu 16.04 VSCODE
59,212,771
I am creating two docker containers one front end and another one is .net core API. But when i call the API from the front end, I am getting an exception as follows, > > SocketException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > HttpRequestException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > I have also added a docker compose file to enable multi-container deployment but of no use. This is yml file as follows, ``` services: dockerdemofrontend: image: ${DOCKER_REGISTRY-}dockerdemofrontend build: context: . dockerfile: DockerDemoFrontEnd/Dockerfile dockerdemoapi: image: ${DOCKER_REGISTRY-}dockerdemoapi build: context: . dockerfile: DockerDemoAPI/Dockerfile ``` I am feeling like those two networks are different. We need to do something in order to get these two talking. Please help me in this regard.
2019/12/06
[ "https://Stackoverflow.com/questions/59212771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945784/" ]
Build always works on my VS code normally. Updating to the latest Flutter 1.12 also started showing this and most times, my code either shows up on my device first before showing that debug has started or the program just quits. Any fix with VS code because I am not an Android Studio fan.
Try to change flutter channel to beta using "flutter channel beta". it worked for me to fix issue which is because flutter version is updated to "v1.12.13+hotfix.5".
59,212,771
I am creating two docker containers one front end and another one is .net core API. But when i call the API from the front end, I am getting an exception as follows, > > SocketException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > HttpRequestException: Cannot assign requested address > System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken) > > > I have also added a docker compose file to enable multi-container deployment but of no use. This is yml file as follows, ``` services: dockerdemofrontend: image: ${DOCKER_REGISTRY-}dockerdemofrontend build: context: . dockerfile: DockerDemoFrontEnd/Dockerfile dockerdemoapi: image: ${DOCKER_REGISTRY-}dockerdemoapi build: context: . dockerfile: DockerDemoAPI/Dockerfile ``` I am feeling like those two networks are different. We need to do something in order to get these two talking. Please help me in this regard.
2019/12/06
[ "https://Stackoverflow.com/questions/59212771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5945784/" ]
I had this error with a clean install on MacOS X (Mojave), and after trial and error discovered that the main user who is running flutter debug needs to be an admin user. Clue was the line: ``` log: Must be admin to run 'stream' command ``` when running from command line. After this VS Code and command line work.
Try to downgrade the libglvnd package to version 1.2.0 in arch linux.
18,126,683
So I have a Bing Map control, a GeoCordWatcher getting gps lat and lon, a timer for position intervals and a RouteQuery maker turning the GPS cords into a path for the map. The points are correct, +- a couple of meters. The problem is that if I am near an intersection or a side street it when the route query runs it takes me off on a half mile expedition that I never went on. I have tried using both default accuracy and high accuracy but I get the same results. Actually seems to be worse with high accuracy. Has anyone else had this issue? ``` RouteQuery rq = new RouteQuery(); List<GeoCoordinate> cords = new List<GeoCoordinate>(); foreach (classes.PositionObj posObj in waypoints) { cords.Add(new GeoCoordinate(Convert.ToDouble(posObj.Lattitude), Convert.ToDouble(posObj.Longitude))); } rq.Waypoints = cords; rq.QueryCompleted += rw_QueryCompleted; rq.QueryAsync(); void rw_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e) { try { if (e.Error == null) { Route myroute = e.Result; mapRoute = new MapRoute(myroute); mapRoute.Color = (Color)Application.Current.Resources["PhoneAccentColor"]; myMap.AddRoute(mapRoute); } } catch (Exception error) { MessageBox.Show(error.Message); MessageBox.Show(error.StackTrace); leaveFeedback(error.StackTrace); } } ```
2013/08/08
[ "https://Stackoverflow.com/questions/18126683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051392/" ]
> > but I'd like to use the android java std lib for a project of mine > > > I have no idea why you think that would work, any more than trying to use a Windows DLL on Linux. > > Is there any way to get the source code (in a jar or otherwise) for the android.jar so I can hook it up to the IDE so I can nicely browse the source code of the standard library? > > > The source code for Android is at [the Android Open Source Project](http://source.android.com/). The source code for the `android.jar` is mostly in the `platform_frameworks_base` repo ([GitHub mirror](https://github.com/android/platform_frameworks_base)), but the JAR is really an output of a firmware build.
As you use eclipse, use > > jadclipse > > > which extrach any jar that in eclipse, u can view any source code with out download and also without internet. It has also export source code, As a developer It help u most times. :-> [link to download](http://marketplace.eclipse.org/content/jadclipse)
18,126,683
So I have a Bing Map control, a GeoCordWatcher getting gps lat and lon, a timer for position intervals and a RouteQuery maker turning the GPS cords into a path for the map. The points are correct, +- a couple of meters. The problem is that if I am near an intersection or a side street it when the route query runs it takes me off on a half mile expedition that I never went on. I have tried using both default accuracy and high accuracy but I get the same results. Actually seems to be worse with high accuracy. Has anyone else had this issue? ``` RouteQuery rq = new RouteQuery(); List<GeoCoordinate> cords = new List<GeoCoordinate>(); foreach (classes.PositionObj posObj in waypoints) { cords.Add(new GeoCoordinate(Convert.ToDouble(posObj.Lattitude), Convert.ToDouble(posObj.Longitude))); } rq.Waypoints = cords; rq.QueryCompleted += rw_QueryCompleted; rq.QueryAsync(); void rw_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e) { try { if (e.Error == null) { Route myroute = e.Result; mapRoute = new MapRoute(myroute); mapRoute.Color = (Color)Application.Current.Resources["PhoneAccentColor"]; myMap.AddRoute(mapRoute); } } catch (Exception error) { MessageBox.Show(error.Message); MessageBox.Show(error.StackTrace); leaveFeedback(error.StackTrace); } } ```
2013/08/08
[ "https://Stackoverflow.com/questions/18126683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051392/" ]
> > but I'd like to use the android java std lib for a project of mine > > > I have no idea why you think that would work, any more than trying to use a Windows DLL on Linux. > > Is there any way to get the source code (in a jar or otherwise) for the android.jar so I can hook it up to the IDE so I can nicely browse the source code of the standard library? > > > The source code for Android is at [the Android Open Source Project](http://source.android.com/). The source code for the `android.jar` is mostly in the `platform_frameworks_base` repo ([GitHub mirror](https://github.com/android/platform_frameworks_base)), but the JAR is really an output of a firmware build.
Unpacking the *jar* is way more than you need to worry about. Android is *open source*, so you can get everything you need online. To start, you can browse most of the source on [Android's GitHub account](https://github.com/android), or download the source tree on the [Android Open Source Project website](http://source.android.com). You can also view most (if not all) sources on [GrepCode](http://grepcode.com/project/repository.grepcode.com/java/ext/com.google.android/android). If you really want to go through the trouble of extracting the *jar* and decompiling the source, you can use [JD-GUI](http://java.decompiler.free.fr/?q=jdgui).
18,126,683
So I have a Bing Map control, a GeoCordWatcher getting gps lat and lon, a timer for position intervals and a RouteQuery maker turning the GPS cords into a path for the map. The points are correct, +- a couple of meters. The problem is that if I am near an intersection or a side street it when the route query runs it takes me off on a half mile expedition that I never went on. I have tried using both default accuracy and high accuracy but I get the same results. Actually seems to be worse with high accuracy. Has anyone else had this issue? ``` RouteQuery rq = new RouteQuery(); List<GeoCoordinate> cords = new List<GeoCoordinate>(); foreach (classes.PositionObj posObj in waypoints) { cords.Add(new GeoCoordinate(Convert.ToDouble(posObj.Lattitude), Convert.ToDouble(posObj.Longitude))); } rq.Waypoints = cords; rq.QueryCompleted += rw_QueryCompleted; rq.QueryAsync(); void rw_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e) { try { if (e.Error == null) { Route myroute = e.Result; mapRoute = new MapRoute(myroute); mapRoute.Color = (Color)Application.Current.Resources["PhoneAccentColor"]; myMap.AddRoute(mapRoute); } } catch (Exception error) { MessageBox.Show(error.Message); MessageBox.Show(error.StackTrace); leaveFeedback(error.StackTrace); } } ```
2013/08/08
[ "https://Stackoverflow.com/questions/18126683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051392/" ]
In your Android SDK root directory, go to the `sources` folder. Here you will find the source files for the different platforms you have downloaded. Note: This gives you the Java code for Android libraries such as `Activity`
As you use eclipse, use > > jadclipse > > > which extrach any jar that in eclipse, u can view any source code with out download and also without internet. It has also export source code, As a developer It help u most times. :-> [link to download](http://marketplace.eclipse.org/content/jadclipse)
18,126,683
So I have a Bing Map control, a GeoCordWatcher getting gps lat and lon, a timer for position intervals and a RouteQuery maker turning the GPS cords into a path for the map. The points are correct, +- a couple of meters. The problem is that if I am near an intersection or a side street it when the route query runs it takes me off on a half mile expedition that I never went on. I have tried using both default accuracy and high accuracy but I get the same results. Actually seems to be worse with high accuracy. Has anyone else had this issue? ``` RouteQuery rq = new RouteQuery(); List<GeoCoordinate> cords = new List<GeoCoordinate>(); foreach (classes.PositionObj posObj in waypoints) { cords.Add(new GeoCoordinate(Convert.ToDouble(posObj.Lattitude), Convert.ToDouble(posObj.Longitude))); } rq.Waypoints = cords; rq.QueryCompleted += rw_QueryCompleted; rq.QueryAsync(); void rw_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e) { try { if (e.Error == null) { Route myroute = e.Result; mapRoute = new MapRoute(myroute); mapRoute.Color = (Color)Application.Current.Resources["PhoneAccentColor"]; myMap.AddRoute(mapRoute); } } catch (Exception error) { MessageBox.Show(error.Message); MessageBox.Show(error.StackTrace); leaveFeedback(error.StackTrace); } } ```
2013/08/08
[ "https://Stackoverflow.com/questions/18126683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051392/" ]
In your Android SDK root directory, go to the `sources` folder. Here you will find the source files for the different platforms you have downloaded. Note: This gives you the Java code for Android libraries such as `Activity`
Unpacking the *jar* is way more than you need to worry about. Android is *open source*, so you can get everything you need online. To start, you can browse most of the source on [Android's GitHub account](https://github.com/android), or download the source tree on the [Android Open Source Project website](http://source.android.com). You can also view most (if not all) sources on [GrepCode](http://grepcode.com/project/repository.grepcode.com/java/ext/com.google.android/android). If you really want to go through the trouble of extracting the *jar* and decompiling the source, you can use [JD-GUI](http://java.decompiler.free.fr/?q=jdgui).
18,126,683
So I have a Bing Map control, a GeoCordWatcher getting gps lat and lon, a timer for position intervals and a RouteQuery maker turning the GPS cords into a path for the map. The points are correct, +- a couple of meters. The problem is that if I am near an intersection or a side street it when the route query runs it takes me off on a half mile expedition that I never went on. I have tried using both default accuracy and high accuracy but I get the same results. Actually seems to be worse with high accuracy. Has anyone else had this issue? ``` RouteQuery rq = new RouteQuery(); List<GeoCoordinate> cords = new List<GeoCoordinate>(); foreach (classes.PositionObj posObj in waypoints) { cords.Add(new GeoCoordinate(Convert.ToDouble(posObj.Lattitude), Convert.ToDouble(posObj.Longitude))); } rq.Waypoints = cords; rq.QueryCompleted += rw_QueryCompleted; rq.QueryAsync(); void rw_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e) { try { if (e.Error == null) { Route myroute = e.Result; mapRoute = new MapRoute(myroute); mapRoute.Color = (Color)Application.Current.Resources["PhoneAccentColor"]; myMap.AddRoute(mapRoute); } } catch (Exception error) { MessageBox.Show(error.Message); MessageBox.Show(error.StackTrace); leaveFeedback(error.StackTrace); } } ```
2013/08/08
[ "https://Stackoverflow.com/questions/18126683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051392/" ]
Unpacking the *jar* is way more than you need to worry about. Android is *open source*, so you can get everything you need online. To start, you can browse most of the source on [Android's GitHub account](https://github.com/android), or download the source tree on the [Android Open Source Project website](http://source.android.com). You can also view most (if not all) sources on [GrepCode](http://grepcode.com/project/repository.grepcode.com/java/ext/com.google.android/android). If you really want to go through the trouble of extracting the *jar* and decompiling the source, you can use [JD-GUI](http://java.decompiler.free.fr/?q=jdgui).
As you use eclipse, use > > jadclipse > > > which extrach any jar that in eclipse, u can view any source code with out download and also without internet. It has also export source code, As a developer It help u most times. :-> [link to download](http://marketplace.eclipse.org/content/jadclipse)
20,448,337
I have an Excel sheet with data only in the first column, where each cell *starts* with the character H, G, I, B, H, E, S, C, or none of the above. I would like to write a command so that in the second column, one of four things will happen: 1. If the cell in the first column starts with H, G, or I, then the cell in the second column is assigned H 2. If the cell in the first column starts with B or E, then the cell in the second column is assigned E 3. If the cell in the first column starts with T, S, or C, then the cell in the second column is assigned C 4. If the cell in the first column starts with none of the above, then the cell in the second column remains blank I found that this command does part of the problem: `=IF(OR(B25="H"; B25="G"; B25="I");"H";"") & IF(OR(B25="B"; B25="E");"E";"") & IF(OR(B25="T"; B25="S"; B25="C");"C";"")` However, this only works if the first column only contains one character. I would like to tailor this command so that it does not require there to only be one character in the first column, but that it simply *starts with* the character. I hope this makes sense. Please let me know if you have any advice!! :O)
2013/12/08
[ "https://Stackoverflow.com/questions/20448337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Maybe the "LEFT()"-Function is what you are looking for. Something like "LEFT(A1,1)" should give you the first Character of the String in Cell A1. More information: <http://office.microsoft.com/en-us/excel-help/left-leftb-functions-HP005209153.aspx> EDIT: Wow, this community is always impressing me. (Too fast for me ;))
try this: `=IF(OR(LEFT(AB25,1)="H"; LEFT(AB25,1)="G"; LEFT(AB25,1)="I");"H";"") & IF(OR(LEFT(AB25,1)="B"; LEFT(AB25,1)="E");"E";"") & IF(OR(LEFT(AB25,1)="T"; LEFT(AB25,1)="S"; LEFT(AB25,1)="C");"C";"")`
20,448,337
I have an Excel sheet with data only in the first column, where each cell *starts* with the character H, G, I, B, H, E, S, C, or none of the above. I would like to write a command so that in the second column, one of four things will happen: 1. If the cell in the first column starts with H, G, or I, then the cell in the second column is assigned H 2. If the cell in the first column starts with B or E, then the cell in the second column is assigned E 3. If the cell in the first column starts with T, S, or C, then the cell in the second column is assigned C 4. If the cell in the first column starts with none of the above, then the cell in the second column remains blank I found that this command does part of the problem: `=IF(OR(B25="H"; B25="G"; B25="I");"H";"") & IF(OR(B25="B"; B25="E");"E";"") & IF(OR(B25="T"; B25="S"; B25="C");"C";"")` However, this only works if the first column only contains one character. I would like to tailor this command so that it does not require there to only be one character in the first column, but that it simply *starts with* the character. I hope this makes sense. Please let me know if you have any advice!! :O)
2013/12/08
[ "https://Stackoverflow.com/questions/20448337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Maybe the "LEFT()"-Function is what you are looking for. Something like "LEFT(A1,1)" should give you the first Character of the String in Cell A1. More information: <http://office.microsoft.com/en-us/excel-help/left-leftb-functions-HP005209153.aspx> EDIT: Wow, this community is always impressing me. (Too fast for me ;))
Create a small table elsewhere in in the workbook. Let's give it the named range "MyLookup" for the sake of example. This table simply maps the input values to the desired output values, like so: ``` MyLookup: Input Output H H G H I H B E E E etc... ``` Now use this very simple formula to get your result: ``` =IFERROR(VLOOKUP(LEFT(B25,1),MyLookup,2,FALSE),"") ``` Make sense?
602,200
Let's consider that we have a Newton's cradle in vacuum: [![enter image description here](https://i.stack.imgur.com/NPea6.jpg)](https://i.stack.imgur.com/NPea6.jpg) Considering that each ball has a mass of 100g or 0.1 kg we release the ball and at the time of contact, the ball has a final velocity of 1 m/s. So the momentum will be: $$p = mv = 1\*0.1 = 0.1 kg m/s$$ If the momentum is conserved, the ball at the other side should also come out with a speed of **1 m/s**. Then it will come back with an equal magnitude of momentum and the first ball should again move back at 1 m/s. Note that there is another effect at play here, which is the 'pendulum effect' which reverses the direction of the momentum but perfectly conserves its magnitude. And this process should keep going. But since the collision is inelastic, the kinetic energy will not be conserved and even in a vacuum some energy will be lost in the form of heat, but not as sound because it is in a vacuum. But according to the law of conservation of momentum, the momentum should still be conserved even if the kinetic energy is not. But the problem here is that since some kinetic energy is lost, the speed of the balls should gradually decrease. At one point the balls should stop moving, and so they will have 0 velocity. And if that happens, the momentum will become 0, even though we started out with 0.1 kg m/s. Doesn't this seem to violate the law of conservation of momentum? I can't seem to make sense of it
2020/12/22
[ "https://physics.stackexchange.com/questions/602200", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/281732/" ]
I think that to understand your misunderstanding we have to consider the conditions for conservation of momentum: momentum is conserved so long as there is no net external force acting on the system in question. Considering the simple case in a vacuum, even friction between balls or between the strings and the post is acting. There may even be other forces that aren't listed here that you could think of. But in essence, this is why momentum is not conserved in this case: because it is not ideal. Hence, energy is being dissipated away as heat or sound (if we insert a medium), causing the balls to lose energy and therefore velocity/linear momentum.
You seem to dismiss the fact that conservation of momentum means conservation of momentum **vector**. If you consider the initial state right before the first collision, on the left hand side, the initial momentum is 0.1 kg m/s in the direction horizonatl to the right. Once the last ball on the right is moving up the momentum is already changed. It will change both in magnitude, decreasing to zero and in direction, gaining a vertical component. Then there is a point where its momentum is zero and then the motion is reversed. So you have a continous change in momentum way before you see the effects of friction or other kind of dissipative effects. Why the momentum is not conserved? The condition for conservation is to have no external forces and this is not the case here. You can only expect conservation if you take the states just before collision and just after collision between two balls. Or even before the first collision and right before the last ball starts to rise. But after that the tension in the string and gravity act to change the momentum.
602,200
Let's consider that we have a Newton's cradle in vacuum: [![enter image description here](https://i.stack.imgur.com/NPea6.jpg)](https://i.stack.imgur.com/NPea6.jpg) Considering that each ball has a mass of 100g or 0.1 kg we release the ball and at the time of contact, the ball has a final velocity of 1 m/s. So the momentum will be: $$p = mv = 1\*0.1 = 0.1 kg m/s$$ If the momentum is conserved, the ball at the other side should also come out with a speed of **1 m/s**. Then it will come back with an equal magnitude of momentum and the first ball should again move back at 1 m/s. Note that there is another effect at play here, which is the 'pendulum effect' which reverses the direction of the momentum but perfectly conserves its magnitude. And this process should keep going. But since the collision is inelastic, the kinetic energy will not be conserved and even in a vacuum some energy will be lost in the form of heat, but not as sound because it is in a vacuum. But according to the law of conservation of momentum, the momentum should still be conserved even if the kinetic energy is not. But the problem here is that since some kinetic energy is lost, the speed of the balls should gradually decrease. At one point the balls should stop moving, and so they will have 0 velocity. And if that happens, the momentum will become 0, even though we started out with 0.1 kg m/s. Doesn't this seem to violate the law of conservation of momentum? I can't seem to make sense of it
2020/12/22
[ "https://physics.stackexchange.com/questions/602200", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/281732/" ]
I think that to understand your misunderstanding we have to consider the conditions for conservation of momentum: momentum is conserved so long as there is no net external force acting on the system in question. Considering the simple case in a vacuum, even friction between balls or between the strings and the post is acting. There may even be other forces that aren't listed here that you could think of. But in essence, this is why momentum is not conserved in this case: because it is not ideal. Hence, energy is being dissipated away as heat or sound (if we insert a medium), causing the balls to lose energy and therefore velocity/linear momentum.
Let's simplify a bit more. Suppose there are only two balls, and they are made of wet clay. One balls swings toward the other and sticks - totally inelastic. You have probably already done the math for collisions like this. Momentum is conserved, kinetic energy is not. Both balls have the same velocity afterward. The outcome is the velocity is $0.5$ m/s. The momentum is the same as before. Half the kinetic energy has been converted to heat and half is left as kinetic energy. The final state is both balls swing back and forth together. For the $5$ steel balls that gradually lose kinetic energy, the final state will be something like this too. All $5$ balls swinging back and forth together. You could show this experimentally by sticking two balls in the middle together with a very small piece of gum. Normally the balls are like extremely stiff springs. They deform slightly and push on the next ball. It is such a small and quick deformation that you can't see it. But gum would deform and convert some of that energy to heat. The situation is different if you consider air friction. Now the forces are not all between balls. Air is outside the system. The balls push air around and slow down. Air speeds up and carry away energy and momentum. We don't count the momentum outside the system. We see the momentum and kinetic energy of the system decrease. It is not conserved in the system because the system is not isolated. Eventually all the balls would stop. Of course, you can always choose a bigger system that does count the air. You might have to work at it, but you put the whole thing in a rocket in space where there is no air outside. In that case, you would have an isolated system again. If you added up the momentum of the balls and air and other rocket parts, you would find momentum is conserved. The final state of this system is the balls are stopped, and the air stopped blowing around. All the kinetic energy is converted to heat. Momentum is conserved in this rocket. As the balls swing back and forth, the whole rocket would move a little bit in the opposite direction. The total momentum doesn't change.
602,200
Let's consider that we have a Newton's cradle in vacuum: [![enter image description here](https://i.stack.imgur.com/NPea6.jpg)](https://i.stack.imgur.com/NPea6.jpg) Considering that each ball has a mass of 100g or 0.1 kg we release the ball and at the time of contact, the ball has a final velocity of 1 m/s. So the momentum will be: $$p = mv = 1\*0.1 = 0.1 kg m/s$$ If the momentum is conserved, the ball at the other side should also come out with a speed of **1 m/s**. Then it will come back with an equal magnitude of momentum and the first ball should again move back at 1 m/s. Note that there is another effect at play here, which is the 'pendulum effect' which reverses the direction of the momentum but perfectly conserves its magnitude. And this process should keep going. But since the collision is inelastic, the kinetic energy will not be conserved and even in a vacuum some energy will be lost in the form of heat, but not as sound because it is in a vacuum. But according to the law of conservation of momentum, the momentum should still be conserved even if the kinetic energy is not. But the problem here is that since some kinetic energy is lost, the speed of the balls should gradually decrease. At one point the balls should stop moving, and so they will have 0 velocity. And if that happens, the momentum will become 0, even though we started out with 0.1 kg m/s. Doesn't this seem to violate the law of conservation of momentum? I can't seem to make sense of it
2020/12/22
[ "https://physics.stackexchange.com/questions/602200", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/281732/" ]
I don't think this is a bad question at all - I don't understand the down votes. Issues like this used to confuse me too, and I don't feel that any of the comments or answers so far have really got to the bottom of the issue. Let's think about your setup a bit. You have a Newton's cradle toy in a vacuum, so it's isolated from air resistance. But you still have gravity acting on it, which means it must be resting on a surface. You didn't specify whether that surface is frictionless or not, so I'll cover both cases. **Case 1: the cradle is resting on a frictionless surface** In this case, you have a ball of mass $0.1\,\mathrm{kg}$ moving at $1\,\mathrm{ms}^{-1}$, which hits an object of mass $0.4\,\mathrm{kg}$ moving at $0\,\mathrm{ms}^{-1}$, namely the remaining four balls. A small amount of energy is converted into heat during the collision, which means that the 5th ball comes out of the collision at a speed of $(1-\varepsilon)\,\mathrm{ms}^{-1}$, where $\varepsilon$ is some small number. In order for momentum to be conserved, that means the remaining four balls will not be completely stationary, but instead will be moving at a velocity of about $\varepsilon/4 \,\mathrm{ms}^{-1}$ in the same direction as the original ball. (Really we should worry about the mass of the frame and the dynamics of the strings and so on too, but I'll ignore all that.) This will happen repeatedly until the balls come to rest relative to each other, at which point the combined system of 5 balls will have the momentum of the original ball at the moment of the first collision, meaning that when it comes to rest the whole system will be sliding at a rate of $1/5 \,\mathrm{ms}^{-1}$ along the frictionless surface. **Case 2: the surface has friction.** Now let's assume the friction is high enough that the cradle doesn't move relative to the surface it's sitting on. In this case, the ball is colliding with an object that consists of the four balls, the frame, the surface it's attached to, and the planet that's attached to that. Once the balls have come to rest, the *entire Earth* will have an little bit of extra momentum, but since its mass is so high we don't usually bother to account for that. So generally speaking, when we have an inelastic collision with a stationary object, we just treat momentum as not being conserved by that collision. The actual dynamics are more complicated of course. Momentum first gets transferred from the moving to the other four balls in the same way as described above, then it gets transferred to the frame, then to the local area of the Earth's crust, where it will reverberate as seismic waves for a while before eventually becoming spread out evenly over the whole planet.
I think that to understand your misunderstanding we have to consider the conditions for conservation of momentum: momentum is conserved so long as there is no net external force acting on the system in question. Considering the simple case in a vacuum, even friction between balls or between the strings and the post is acting. There may even be other forces that aren't listed here that you could think of. But in essence, this is why momentum is not conserved in this case: because it is not ideal. Hence, energy is being dissipated away as heat or sound (if we insert a medium), causing the balls to lose energy and therefore velocity/linear momentum.
602,200
Let's consider that we have a Newton's cradle in vacuum: [![enter image description here](https://i.stack.imgur.com/NPea6.jpg)](https://i.stack.imgur.com/NPea6.jpg) Considering that each ball has a mass of 100g or 0.1 kg we release the ball and at the time of contact, the ball has a final velocity of 1 m/s. So the momentum will be: $$p = mv = 1\*0.1 = 0.1 kg m/s$$ If the momentum is conserved, the ball at the other side should also come out with a speed of **1 m/s**. Then it will come back with an equal magnitude of momentum and the first ball should again move back at 1 m/s. Note that there is another effect at play here, which is the 'pendulum effect' which reverses the direction of the momentum but perfectly conserves its magnitude. And this process should keep going. But since the collision is inelastic, the kinetic energy will not be conserved and even in a vacuum some energy will be lost in the form of heat, but not as sound because it is in a vacuum. But according to the law of conservation of momentum, the momentum should still be conserved even if the kinetic energy is not. But the problem here is that since some kinetic energy is lost, the speed of the balls should gradually decrease. At one point the balls should stop moving, and so they will have 0 velocity. And if that happens, the momentum will become 0, even though we started out with 0.1 kg m/s. Doesn't this seem to violate the law of conservation of momentum? I can't seem to make sense of it
2020/12/22
[ "https://physics.stackexchange.com/questions/602200", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/281732/" ]
Let's simplify a bit more. Suppose there are only two balls, and they are made of wet clay. One balls swings toward the other and sticks - totally inelastic. You have probably already done the math for collisions like this. Momentum is conserved, kinetic energy is not. Both balls have the same velocity afterward. The outcome is the velocity is $0.5$ m/s. The momentum is the same as before. Half the kinetic energy has been converted to heat and half is left as kinetic energy. The final state is both balls swing back and forth together. For the $5$ steel balls that gradually lose kinetic energy, the final state will be something like this too. All $5$ balls swinging back and forth together. You could show this experimentally by sticking two balls in the middle together with a very small piece of gum. Normally the balls are like extremely stiff springs. They deform slightly and push on the next ball. It is such a small and quick deformation that you can't see it. But gum would deform and convert some of that energy to heat. The situation is different if you consider air friction. Now the forces are not all between balls. Air is outside the system. The balls push air around and slow down. Air speeds up and carry away energy and momentum. We don't count the momentum outside the system. We see the momentum and kinetic energy of the system decrease. It is not conserved in the system because the system is not isolated. Eventually all the balls would stop. Of course, you can always choose a bigger system that does count the air. You might have to work at it, but you put the whole thing in a rocket in space where there is no air outside. In that case, you would have an isolated system again. If you added up the momentum of the balls and air and other rocket parts, you would find momentum is conserved. The final state of this system is the balls are stopped, and the air stopped blowing around. All the kinetic energy is converted to heat. Momentum is conserved in this rocket. As the balls swing back and forth, the whole rocket would move a little bit in the opposite direction. The total momentum doesn't change.
You seem to dismiss the fact that conservation of momentum means conservation of momentum **vector**. If you consider the initial state right before the first collision, on the left hand side, the initial momentum is 0.1 kg m/s in the direction horizonatl to the right. Once the last ball on the right is moving up the momentum is already changed. It will change both in magnitude, decreasing to zero and in direction, gaining a vertical component. Then there is a point where its momentum is zero and then the motion is reversed. So you have a continous change in momentum way before you see the effects of friction or other kind of dissipative effects. Why the momentum is not conserved? The condition for conservation is to have no external forces and this is not the case here. You can only expect conservation if you take the states just before collision and just after collision between two balls. Or even before the first collision and right before the last ball starts to rise. But after that the tension in the string and gravity act to change the momentum.
602,200
Let's consider that we have a Newton's cradle in vacuum: [![enter image description here](https://i.stack.imgur.com/NPea6.jpg)](https://i.stack.imgur.com/NPea6.jpg) Considering that each ball has a mass of 100g or 0.1 kg we release the ball and at the time of contact, the ball has a final velocity of 1 m/s. So the momentum will be: $$p = mv = 1\*0.1 = 0.1 kg m/s$$ If the momentum is conserved, the ball at the other side should also come out with a speed of **1 m/s**. Then it will come back with an equal magnitude of momentum and the first ball should again move back at 1 m/s. Note that there is another effect at play here, which is the 'pendulum effect' which reverses the direction of the momentum but perfectly conserves its magnitude. And this process should keep going. But since the collision is inelastic, the kinetic energy will not be conserved and even in a vacuum some energy will be lost in the form of heat, but not as sound because it is in a vacuum. But according to the law of conservation of momentum, the momentum should still be conserved even if the kinetic energy is not. But the problem here is that since some kinetic energy is lost, the speed of the balls should gradually decrease. At one point the balls should stop moving, and so they will have 0 velocity. And if that happens, the momentum will become 0, even though we started out with 0.1 kg m/s. Doesn't this seem to violate the law of conservation of momentum? I can't seem to make sense of it
2020/12/22
[ "https://physics.stackexchange.com/questions/602200", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/281732/" ]
I don't think this is a bad question at all - I don't understand the down votes. Issues like this used to confuse me too, and I don't feel that any of the comments or answers so far have really got to the bottom of the issue. Let's think about your setup a bit. You have a Newton's cradle toy in a vacuum, so it's isolated from air resistance. But you still have gravity acting on it, which means it must be resting on a surface. You didn't specify whether that surface is frictionless or not, so I'll cover both cases. **Case 1: the cradle is resting on a frictionless surface** In this case, you have a ball of mass $0.1\,\mathrm{kg}$ moving at $1\,\mathrm{ms}^{-1}$, which hits an object of mass $0.4\,\mathrm{kg}$ moving at $0\,\mathrm{ms}^{-1}$, namely the remaining four balls. A small amount of energy is converted into heat during the collision, which means that the 5th ball comes out of the collision at a speed of $(1-\varepsilon)\,\mathrm{ms}^{-1}$, where $\varepsilon$ is some small number. In order for momentum to be conserved, that means the remaining four balls will not be completely stationary, but instead will be moving at a velocity of about $\varepsilon/4 \,\mathrm{ms}^{-1}$ in the same direction as the original ball. (Really we should worry about the mass of the frame and the dynamics of the strings and so on too, but I'll ignore all that.) This will happen repeatedly until the balls come to rest relative to each other, at which point the combined system of 5 balls will have the momentum of the original ball at the moment of the first collision, meaning that when it comes to rest the whole system will be sliding at a rate of $1/5 \,\mathrm{ms}^{-1}$ along the frictionless surface. **Case 2: the surface has friction.** Now let's assume the friction is high enough that the cradle doesn't move relative to the surface it's sitting on. In this case, the ball is colliding with an object that consists of the four balls, the frame, the surface it's attached to, and the planet that's attached to that. Once the balls have come to rest, the *entire Earth* will have an little bit of extra momentum, but since its mass is so high we don't usually bother to account for that. So generally speaking, when we have an inelastic collision with a stationary object, we just treat momentum as not being conserved by that collision. The actual dynamics are more complicated of course. Momentum first gets transferred from the moving to the other four balls in the same way as described above, then it gets transferred to the frame, then to the local area of the Earth's crust, where it will reverberate as seismic waves for a while before eventually becoming spread out evenly over the whole planet.
You seem to dismiss the fact that conservation of momentum means conservation of momentum **vector**. If you consider the initial state right before the first collision, on the left hand side, the initial momentum is 0.1 kg m/s in the direction horizonatl to the right. Once the last ball on the right is moving up the momentum is already changed. It will change both in magnitude, decreasing to zero and in direction, gaining a vertical component. Then there is a point where its momentum is zero and then the motion is reversed. So you have a continous change in momentum way before you see the effects of friction or other kind of dissipative effects. Why the momentum is not conserved? The condition for conservation is to have no external forces and this is not the case here. You can only expect conservation if you take the states just before collision and just after collision between two balls. Or even before the first collision and right before the last ball starts to rise. But after that the tension in the string and gravity act to change the momentum.
602,200
Let's consider that we have a Newton's cradle in vacuum: [![enter image description here](https://i.stack.imgur.com/NPea6.jpg)](https://i.stack.imgur.com/NPea6.jpg) Considering that each ball has a mass of 100g or 0.1 kg we release the ball and at the time of contact, the ball has a final velocity of 1 m/s. So the momentum will be: $$p = mv = 1\*0.1 = 0.1 kg m/s$$ If the momentum is conserved, the ball at the other side should also come out with a speed of **1 m/s**. Then it will come back with an equal magnitude of momentum and the first ball should again move back at 1 m/s. Note that there is another effect at play here, which is the 'pendulum effect' which reverses the direction of the momentum but perfectly conserves its magnitude. And this process should keep going. But since the collision is inelastic, the kinetic energy will not be conserved and even in a vacuum some energy will be lost in the form of heat, but not as sound because it is in a vacuum. But according to the law of conservation of momentum, the momentum should still be conserved even if the kinetic energy is not. But the problem here is that since some kinetic energy is lost, the speed of the balls should gradually decrease. At one point the balls should stop moving, and so they will have 0 velocity. And if that happens, the momentum will become 0, even though we started out with 0.1 kg m/s. Doesn't this seem to violate the law of conservation of momentum? I can't seem to make sense of it
2020/12/22
[ "https://physics.stackexchange.com/questions/602200", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/281732/" ]
I don't think this is a bad question at all - I don't understand the down votes. Issues like this used to confuse me too, and I don't feel that any of the comments or answers so far have really got to the bottom of the issue. Let's think about your setup a bit. You have a Newton's cradle toy in a vacuum, so it's isolated from air resistance. But you still have gravity acting on it, which means it must be resting on a surface. You didn't specify whether that surface is frictionless or not, so I'll cover both cases. **Case 1: the cradle is resting on a frictionless surface** In this case, you have a ball of mass $0.1\,\mathrm{kg}$ moving at $1\,\mathrm{ms}^{-1}$, which hits an object of mass $0.4\,\mathrm{kg}$ moving at $0\,\mathrm{ms}^{-1}$, namely the remaining four balls. A small amount of energy is converted into heat during the collision, which means that the 5th ball comes out of the collision at a speed of $(1-\varepsilon)\,\mathrm{ms}^{-1}$, where $\varepsilon$ is some small number. In order for momentum to be conserved, that means the remaining four balls will not be completely stationary, but instead will be moving at a velocity of about $\varepsilon/4 \,\mathrm{ms}^{-1}$ in the same direction as the original ball. (Really we should worry about the mass of the frame and the dynamics of the strings and so on too, but I'll ignore all that.) This will happen repeatedly until the balls come to rest relative to each other, at which point the combined system of 5 balls will have the momentum of the original ball at the moment of the first collision, meaning that when it comes to rest the whole system will be sliding at a rate of $1/5 \,\mathrm{ms}^{-1}$ along the frictionless surface. **Case 2: the surface has friction.** Now let's assume the friction is high enough that the cradle doesn't move relative to the surface it's sitting on. In this case, the ball is colliding with an object that consists of the four balls, the frame, the surface it's attached to, and the planet that's attached to that. Once the balls have come to rest, the *entire Earth* will have an little bit of extra momentum, but since its mass is so high we don't usually bother to account for that. So generally speaking, when we have an inelastic collision with a stationary object, we just treat momentum as not being conserved by that collision. The actual dynamics are more complicated of course. Momentum first gets transferred from the moving to the other four balls in the same way as described above, then it gets transferred to the frame, then to the local area of the Earth's crust, where it will reverberate as seismic waves for a while before eventually becoming spread out evenly over the whole planet.
Let's simplify a bit more. Suppose there are only two balls, and they are made of wet clay. One balls swings toward the other and sticks - totally inelastic. You have probably already done the math for collisions like this. Momentum is conserved, kinetic energy is not. Both balls have the same velocity afterward. The outcome is the velocity is $0.5$ m/s. The momentum is the same as before. Half the kinetic energy has been converted to heat and half is left as kinetic energy. The final state is both balls swing back and forth together. For the $5$ steel balls that gradually lose kinetic energy, the final state will be something like this too. All $5$ balls swinging back and forth together. You could show this experimentally by sticking two balls in the middle together with a very small piece of gum. Normally the balls are like extremely stiff springs. They deform slightly and push on the next ball. It is such a small and quick deformation that you can't see it. But gum would deform and convert some of that energy to heat. The situation is different if you consider air friction. Now the forces are not all between balls. Air is outside the system. The balls push air around and slow down. Air speeds up and carry away energy and momentum. We don't count the momentum outside the system. We see the momentum and kinetic energy of the system decrease. It is not conserved in the system because the system is not isolated. Eventually all the balls would stop. Of course, you can always choose a bigger system that does count the air. You might have to work at it, but you put the whole thing in a rocket in space where there is no air outside. In that case, you would have an isolated system again. If you added up the momentum of the balls and air and other rocket parts, you would find momentum is conserved. The final state of this system is the balls are stopped, and the air stopped blowing around. All the kinetic energy is converted to heat. Momentum is conserved in this rocket. As the balls swing back and forth, the whole rocket would move a little bit in the opposite direction. The total momentum doesn't change.
6,961
I'm trying to accurately describe a person who acts in one way and does another but knowingly and openly accepts that his actions also include him in the same group he criticizes. This differs from a hypocrite who condemns those who perform an action but justifies his own actions by unrelated means and does not accept he is a part of that group. Does such a word exist or is there a better way of describing such a person? [Merriam-Webster](http://www.merriam-webster.com/dictionary/hypocrite?show=0&t=1292603911) defines a hypocrite as a person who acts in contradiction to his or her stated beliefs or feelings.
2010/12/17
[ "https://english.stackexchange.com/questions/6961", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2871/" ]
I have heard someone use > > I am a prophet, not a saint. > > > A *prophet* is one who comes to the world to give us a message. Here it refers to how he criticizes others for their wrongdoings. A *saint* is one who does good things. Here it refers to how he does the same bad thing that he criticizes others for.
If you don't mind using a Biblical allusion which may not be immediately obvious to your audience, you could go with *whitewashed tomb*.
6,961
I'm trying to accurately describe a person who acts in one way and does another but knowingly and openly accepts that his actions also include him in the same group he criticizes. This differs from a hypocrite who condemns those who perform an action but justifies his own actions by unrelated means and does not accept he is a part of that group. Does such a word exist or is there a better way of describing such a person? [Merriam-Webster](http://www.merriam-webster.com/dictionary/hypocrite?show=0&t=1292603911) defines a hypocrite as a person who acts in contradiction to his or her stated beliefs or feelings.
2010/12/17
[ "https://english.stackexchange.com/questions/6961", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2871/" ]
If you don't mind it as an adjective, this person is either: **insincere** or **disingenuous**
> > Nixonian? > > As in "Well, when the President does it that means that it is not illegal." [via Wikipedia](http://en.wikiquote.org/wiki/Richard_Nixon) > > >
6,961
I'm trying to accurately describe a person who acts in one way and does another but knowingly and openly accepts that his actions also include him in the same group he criticizes. This differs from a hypocrite who condemns those who perform an action but justifies his own actions by unrelated means and does not accept he is a part of that group. Does such a word exist or is there a better way of describing such a person? [Merriam-Webster](http://www.merriam-webster.com/dictionary/hypocrite?show=0&t=1292603911) defines a hypocrite as a person who acts in contradiction to his or her stated beliefs or feelings.
2010/12/17
[ "https://english.stackexchange.com/questions/6961", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2871/" ]
I have heard someone use > > I am a prophet, not a saint. > > > A *prophet* is one who comes to the world to give us a message. Here it refers to how he criticizes others for their wrongdoings. A *saint* is one who does good things. Here it refers to how he does the same bad thing that he criticizes others for.
> > Nixonian? > > As in "Well, when the President does it that means that it is not illegal." [via Wikipedia](http://en.wikiquote.org/wiki/Richard_Nixon) > > >
6,961
I'm trying to accurately describe a person who acts in one way and does another but knowingly and openly accepts that his actions also include him in the same group he criticizes. This differs from a hypocrite who condemns those who perform an action but justifies his own actions by unrelated means and does not accept he is a part of that group. Does such a word exist or is there a better way of describing such a person? [Merriam-Webster](http://www.merriam-webster.com/dictionary/hypocrite?show=0&t=1292603911) defines a hypocrite as a person who acts in contradiction to his or her stated beliefs or feelings.
2010/12/17
[ "https://english.stackexchange.com/questions/6961", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2871/" ]
I have heard someone use > > I am a prophet, not a saint. > > > A *prophet* is one who comes to the world to give us a message. Here it refers to how he criticizes others for their wrongdoings. A *saint* is one who does good things. Here it refers to how he does the same bad thing that he criticizes others for.
This sounds like a person who is making a *rationalization*. The noun form would be *rationalizer* (one who rationalizes), but I can't think of any times I've seen or heard that word used.
6,961
I'm trying to accurately describe a person who acts in one way and does another but knowingly and openly accepts that his actions also include him in the same group he criticizes. This differs from a hypocrite who condemns those who perform an action but justifies his own actions by unrelated means and does not accept he is a part of that group. Does such a word exist or is there a better way of describing such a person? [Merriam-Webster](http://www.merriam-webster.com/dictionary/hypocrite?show=0&t=1292603911) defines a hypocrite as a person who acts in contradiction to his or her stated beliefs or feelings.
2010/12/17
[ "https://english.stackexchange.com/questions/6961", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2871/" ]
The idiom that describes this behavior is: "Do as I say and not as I do." However, it's usually said by the person exhibiting the contradictory behavior and not those categorizing them.
I have heard someone use > > I am a prophet, not a saint. > > > A *prophet* is one who comes to the world to give us a message. Here it refers to how he criticizes others for their wrongdoings. A *saint* is one who does good things. Here it refers to how he does the same bad thing that he criticizes others for.
6,961
I'm trying to accurately describe a person who acts in one way and does another but knowingly and openly accepts that his actions also include him in the same group he criticizes. This differs from a hypocrite who condemns those who perform an action but justifies his own actions by unrelated means and does not accept he is a part of that group. Does such a word exist or is there a better way of describing such a person? [Merriam-Webster](http://www.merriam-webster.com/dictionary/hypocrite?show=0&t=1292603911) defines a hypocrite as a person who acts in contradiction to his or her stated beliefs or feelings.
2010/12/17
[ "https://english.stackexchange.com/questions/6961", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2871/" ]
If you don't mind it as an adjective, this person is either: **insincere** or **disingenuous**
Does it have to be one word? I suggest some sort of compound phrase: > > *open hypocrite* > > > The implication being that a normal hypocrite is closed because they hide their hypocrisy either intentionally or unintentionally. > > *apathetic hypocrite* > > > This person knows and communicates that they are among a group that acts in a way that is in conflict with the person's beliefs, but they are indifferent, unmotivated to change, or motivated to not change.
6,961
I'm trying to accurately describe a person who acts in one way and does another but knowingly and openly accepts that his actions also include him in the same group he criticizes. This differs from a hypocrite who condemns those who perform an action but justifies his own actions by unrelated means and does not accept he is a part of that group. Does such a word exist or is there a better way of describing such a person? [Merriam-Webster](http://www.merriam-webster.com/dictionary/hypocrite?show=0&t=1292603911) defines a hypocrite as a person who acts in contradiction to his or her stated beliefs or feelings.
2010/12/17
[ "https://english.stackexchange.com/questions/6961", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2871/" ]
If you don't mind using a Biblical allusion which may not be immediately obvious to your audience, you could go with *whitewashed tomb*.
> > Nixonian? > > As in "Well, when the President does it that means that it is not illegal." [via Wikipedia](http://en.wikiquote.org/wiki/Richard_Nixon) > > >
6,961
I'm trying to accurately describe a person who acts in one way and does another but knowingly and openly accepts that his actions also include him in the same group he criticizes. This differs from a hypocrite who condemns those who perform an action but justifies his own actions by unrelated means and does not accept he is a part of that group. Does such a word exist or is there a better way of describing such a person? [Merriam-Webster](http://www.merriam-webster.com/dictionary/hypocrite?show=0&t=1292603911) defines a hypocrite as a person who acts in contradiction to his or her stated beliefs or feelings.
2010/12/17
[ "https://english.stackexchange.com/questions/6961", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2871/" ]
If you don't mind using a Biblical allusion which may not be immediately obvious to your audience, you could go with *whitewashed tomb*.
Does it have to be one word? I suggest some sort of compound phrase: > > *open hypocrite* > > > The implication being that a normal hypocrite is closed because they hide their hypocrisy either intentionally or unintentionally. > > *apathetic hypocrite* > > > This person knows and communicates that they are among a group that acts in a way that is in conflict with the person's beliefs, but they are indifferent, unmotivated to change, or motivated to not change.
6,961
I'm trying to accurately describe a person who acts in one way and does another but knowingly and openly accepts that his actions also include him in the same group he criticizes. This differs from a hypocrite who condemns those who perform an action but justifies his own actions by unrelated means and does not accept he is a part of that group. Does such a word exist or is there a better way of describing such a person? [Merriam-Webster](http://www.merriam-webster.com/dictionary/hypocrite?show=0&t=1292603911) defines a hypocrite as a person who acts in contradiction to his or her stated beliefs or feelings.
2010/12/17
[ "https://english.stackexchange.com/questions/6961", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2871/" ]
The idiom that describes this behavior is: "Do as I say and not as I do." However, it's usually said by the person exhibiting the contradictory behavior and not those categorizing them.
This sounds like a person who is making a *rationalization*. The noun form would be *rationalizer* (one who rationalizes), but I can't think of any times I've seen or heard that word used.
6,961
I'm trying to accurately describe a person who acts in one way and does another but knowingly and openly accepts that his actions also include him in the same group he criticizes. This differs from a hypocrite who condemns those who perform an action but justifies his own actions by unrelated means and does not accept he is a part of that group. Does such a word exist or is there a better way of describing such a person? [Merriam-Webster](http://www.merriam-webster.com/dictionary/hypocrite?show=0&t=1292603911) defines a hypocrite as a person who acts in contradiction to his or her stated beliefs or feelings.
2010/12/17
[ "https://english.stackexchange.com/questions/6961", "https://english.stackexchange.com", "https://english.stackexchange.com/users/2871/" ]
I have heard someone use > > I am a prophet, not a saint. > > > A *prophet* is one who comes to the world to give us a message. Here it refers to how he criticizes others for their wrongdoings. A *saint* is one who does good things. Here it refers to how he does the same bad thing that he criticizes others for.
If you don't mind it as an adjective, this person is either: **insincere** or **disingenuous**
4,610,120
I have jquery function: ``` function handleSplittingPrices() { var customerId = $(this).val(); loadSplittingPrices(customerId); } ``` I want to execute it with elem as "this": ``` var elem=$('...'); handleSplittingPrices() <-- here elem will be this ``` How can I do it?
2011/01/05
[ "https://Stackoverflow.com/questions/4610120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289246/" ]
You're looking for the [`call` method](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call): ``` handleSplittingPrices.call(elem); ``` Note that `elem` is a jQuery object, not a DOM element, so you won't need to call `$` inside the function.
Use [`call`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call): ``` handleSplittingPrices.call(elem); ```
4,610,120
I have jquery function: ``` function handleSplittingPrices() { var customerId = $(this).val(); loadSplittingPrices(customerId); } ``` I want to execute it with elem as "this": ``` var elem=$('...'); handleSplittingPrices() <-- here elem will be this ``` How can I do it?
2011/01/05
[ "https://Stackoverflow.com/questions/4610120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289246/" ]
You're looking for the [`call` method](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call): ``` handleSplittingPrices.call(elem); ``` Note that `elem` is a jQuery object, not a DOM element, so you won't need to call `$` inside the function.
You can't. Obviously you don't know what "this" is for. function handleSplittingPrices(elem) { var customerId = $(elem).val(); loadSplittingPrices(customerId); } var elem=$('...'); handleSplittingPrices(elem); Wow. Now wasn't that simpler than trying to define the whole concept of Object Oriented programming?
4,610,120
I have jquery function: ``` function handleSplittingPrices() { var customerId = $(this).val(); loadSplittingPrices(customerId); } ``` I want to execute it with elem as "this": ``` var elem=$('...'); handleSplittingPrices() <-- here elem will be this ``` How can I do it?
2011/01/05
[ "https://Stackoverflow.com/questions/4610120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289246/" ]
Use [`call`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call): ``` handleSplittingPrices.call(elem); ```
You can't. Obviously you don't know what "this" is for. function handleSplittingPrices(elem) { var customerId = $(elem).val(); loadSplittingPrices(customerId); } var elem=$('...'); handleSplittingPrices(elem); Wow. Now wasn't that simpler than trying to define the whole concept of Object Oriented programming?
85,440
I've moved my blogs from SP2010 to SP2013, and the original **Posts** Web Part doesn't render correctly, it shows the error > > Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web server administrator. > > > I'm replacing this web part with the SP2013 version, but this is showing me my posts in a tabulated form, like this: ![How my blog looks](https://i.stack.imgur.com/rHP06.png) When I try the `Blog Tools` -> `Change post layout` nothing happens. I cannot get the layout to be `Inline`, as I'd like it. Any ideas what's going wrong?
2013/12/18
[ "https://sharepoint.stackexchange.com/questions/85440", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/3384/" ]
Make sure first that the selected view is "Summary View". The inline, Basic and Boxed styles work only with "Summary View"
The easiest solution is to reactivate `BlogHomePage` feature `{E4639BB7-6E95-4E2F-B562-03B832DD4793}`. It will re-populate the homepage with new `default.aspx` with all webparts.
85,440
I've moved my blogs from SP2010 to SP2013, and the original **Posts** Web Part doesn't render correctly, it shows the error > > Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web server administrator. > > > I'm replacing this web part with the SP2013 version, but this is showing me my posts in a tabulated form, like this: ![How my blog looks](https://i.stack.imgur.com/rHP06.png) When I try the `Blog Tools` -> `Change post layout` nothing happens. I cannot get the layout to be `Inline`, as I'd like it. Any ideas what's going wrong?
2013/12/18
[ "https://sharepoint.stackexchange.com/questions/85440", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/3384/" ]
If you want to see the blogs with date image and other summary details, You need to select the view as "**Summary View**" for the webpart by "**Edit Web Part**" option. It is working as expected for me.
The easiest solution is to reactivate `BlogHomePage` feature `{E4639BB7-6E95-4E2F-B562-03B832DD4793}`. It will re-populate the homepage with new `default.aspx` with all webparts.
78,745
I know the basic difference between Arminianism and Calvinism in the soteriology subject, but when Molinism comes I can't grasp the core doctrines that it teaches. I'm not asking for which is better, just a concise, easy, and helpful definition of each one without too much philosophical blather.
2020/08/06
[ "https://christianity.stackexchange.com/questions/78745", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/46961/" ]
***I found an article*** that explains Molinism in simple, easy to understand language. The second part of the article asks whether it is biblical, but I have left that part out since this is not what you ask. Here is a partial quote: > > Molinism is named for the 16th-century Jesuit, Luis de Molina. Molinism is a system of thought that seeks to reconcile the sovereignty of God and the free will of man. The heart of Molinism is the principle that God is completely sovereign and man is also free in a libertarian sense. Molinism partly seeks to avoid so-called “theological determinism”: the view that God decrees who will be saved or damned without any meaningful impact of their own free choice. Today’s highest-profile defenders of Molinism are William Lane Craig and Alvin Plantinga. > > > > > ***The primary distinctive of Molinism is the affirmation that God has middle knowledge*** (scientia media). Molinism holds that God’s knowledge consists of three logical moments. These “moments” of knowledge are not to be thought of as chronological; rather, they are to be understood as “logical.” In other words, one moment does not come before another moment in time; instead, one moment is logically prior to the other moments. The Molinist differentiates between three different moments of knowledge which are respectively called natural knowledge, middle knowledge and free knowledge. > > > > > **1. Natural Knowledge** – This is God’s knowledge of all necessary and all possible truths: all things which “can be.” In this “moment” God knows every possible combination of causes and effects. He also knows all the truths of logic and all moral truths. This knowledge is independent of God’s will, a point few if any theologians would dispute. > > > > > **2. Middle Knowledge** – This is God’s knowledge of what a free creature would do in any given circumstance. This knowledge consists of what philosophers call counterfactuals of creaturely freedom. These are facts about what any creature with a free will would freely do in any circumstance in which it could be placed. This knowledge, like natural knowledge, is independent of God’s will. > > > > > **3. Creative Command** – this is the “moment” where God actually acts. Between His knowledge of all that is or could be, and all that actually comes to be, is God’s purposeful intervention and creation. > > > > > **4. Free Knowledge** – This is God’s knowledge of what He decided to create: all things that “actually are.” God’s free knowledge is His knowledge of the actual world as it is. This knowledge is completely dependent on God’s will. > > > > > Using middle knowledge, Molinism attempts to show that all of God’s knowledge is self-contained, but it is ordered so as to allow for the possibility of man’s free will. In other words, man is completely free, but God is also completely sovereign—He is absolutely in control of all that happens, and yet humanity’s choices are not coerced. > > > > > According to Molinism, God omnisciently knows what you would have been like had you lived in Africa instead of Australia, or had a car accident that paralyzed you at age 9. He knows how the world would have been changed had John F. Kennedy not been assassinated. More importantly, He knows who would choose to be saved and who would not, in each of those varying circumstances. > > > > > Accordingly, it is out of this (middle) knowledge that God chooses to create. God has middle knowledge of all feasible worlds, and He chooses to create the world that corresponds to His ultimate desires. Therefore, while a person is truly free, God is truly in control of who is or is not saved. Molinists differ on how God defines His underlying desires. For example, some believe God is seeking the maximum number of people to be saved. Others believe God creates in order to maximize some other divine goal. Source: <https://www.gotquestions.org/molinism.html> > > > As to how it differs from Arminianism and Calvinism, I doubt I could do justice to that. Perhaps you could draw from these articles: <https://www.gotquestions.org/arminianism.html> <https://www.gotquestions.org/calvinism.html> <https://www.gotquestions.org/Calvinism-vs-Arminianism.html> Like Nigel J, I am simply presenting one particular point of view in the hope it will help to answer your question. I have permission to copy and paste the Got Questions article on Molinism.
Extract from [William Lane Craig](https://www.reasonablefaith.org/writings/question-answer/molinism-vs.-calvinism/) answering a question on the complexity of Molinism : > > Actually, I have no problem with certain classic statements of the Reformed view. For example, the Westminster Confession (Sect. III) declares that > > > > > *God from all eternity did by the most wise and holy counsel of his own will, freely and unchangeably ordain whatsoever comes to pass; yet so as thereby neither is God the author of sin; nor is violence offered to the will of creatures, nor is the liberty or contingency of second causes taken away, but rather established.* > > > > > **Now this is precisely what the Molinist believes!** The Confession affirms God’s preordination of everything that comes to pass as well as the liberty and contingency of the creaturely will, so that God is not the author of sin. It is a tragedy that in rejecting middle knowledge Reformed divines have cut themselves off from the most perspicuous explanation of the coherence of this wonderful confession. > > > William Lane Craig is Research Professor of Philosophy at Talbot School of Theology and Professor of Philosophy at Houston Baptist University. The whole article is on [Reasonable Faith .org](https://www.reasonablefaith.org/writings/question-answer/molinism-vs.-calvinism/) --- (I do not personally subscribe to these arguments and proposals. I simply report the existence of the references and statements.)
78,745
I know the basic difference between Arminianism and Calvinism in the soteriology subject, but when Molinism comes I can't grasp the core doctrines that it teaches. I'm not asking for which is better, just a concise, easy, and helpful definition of each one without too much philosophical blather.
2020/08/06
[ "https://christianity.stackexchange.com/questions/78745", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/46961/" ]
Extract from [William Lane Craig](https://www.reasonablefaith.org/writings/question-answer/molinism-vs.-calvinism/) answering a question on the complexity of Molinism : > > Actually, I have no problem with certain classic statements of the Reformed view. For example, the Westminster Confession (Sect. III) declares that > > > > > *God from all eternity did by the most wise and holy counsel of his own will, freely and unchangeably ordain whatsoever comes to pass; yet so as thereby neither is God the author of sin; nor is violence offered to the will of creatures, nor is the liberty or contingency of second causes taken away, but rather established.* > > > > > **Now this is precisely what the Molinist believes!** The Confession affirms God’s preordination of everything that comes to pass as well as the liberty and contingency of the creaturely will, so that God is not the author of sin. It is a tragedy that in rejecting middle knowledge Reformed divines have cut themselves off from the most perspicuous explanation of the coherence of this wonderful confession. > > > William Lane Craig is Research Professor of Philosophy at Talbot School of Theology and Professor of Philosophy at Houston Baptist University. The whole article is on [Reasonable Faith .org](https://www.reasonablefaith.org/writings/question-answer/molinism-vs.-calvinism/) --- (I do not personally subscribe to these arguments and proposals. I simply report the existence of the references and statements.)
TL;DR: Calvinists and Arminians disagree about whether man is able and/or free to choose God, Molinism is to do with God's knowledge and not salvation, so can fit with either. Molinist here - Molinism isn't technically a view of soteriology (meaning to do with man's salvation), but is a view of God's knowledge, summed up pretty well by the gotquestions article referenced by Lesley. Molinism's two main points (or core doctrines) are: 1: God has Middle knowledge 2: Man, at least some of the time, has libertarian free will (although the precise definition is disputed, a reasonable interpretation of the term is 'the ability to do otherwise') Arminianism and Calvinism, on the other hand, are directly opposing views that are to do with soteriology, not God's knowledge. Thus, you could be an Arminian Molinist or a Calvinist Molinist. The latter, however, is quite rare. Calvinism is a very difficult doctrine to clearly define, but a working minimum of the system is summed up by the acronym TULIP. I won't go into a lengthy description of each of the letters (it's well documented in many places) but in summary Calvinism teaches that man, in his natural state, is completely unable to come to God (T) . God then 'elects' certain individuals whom He decides to save (U) and draws them to himself via irresistible grace (I) (literally irresistible, the elect person is unable to reject or refuse the grace). Additionally, Christ's atonement only covers and was only intended for these elect (L), and finally, the elect will never fall away or apostasize (P). Arminianism is even harder to specifically define, but the gist is that although man would be unable to come to God alone, God's grace (prevenient grace) overcomes this state and enables all men to come to God and be saved, although it doesn't guarantee any will or force anyone. Christ's atonement covers any and all who come to Him, and is not limited. Beyond that, there are a lot of variations of Arminianism that I don't know as much as I should about. It is worth noting that some (Many? Most?) Molinists hold to a soteriology which is similar to Arminianism but goes further in regards to God's providence and the election of individuals while maintaining free will, but that is beyond the scope of the question as it technically isn't Molinism proper. Hope that helps
78,745
I know the basic difference between Arminianism and Calvinism in the soteriology subject, but when Molinism comes I can't grasp the core doctrines that it teaches. I'm not asking for which is better, just a concise, easy, and helpful definition of each one without too much philosophical blather.
2020/08/06
[ "https://christianity.stackexchange.com/questions/78745", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/46961/" ]
***I found an article*** that explains Molinism in simple, easy to understand language. The second part of the article asks whether it is biblical, but I have left that part out since this is not what you ask. Here is a partial quote: > > Molinism is named for the 16th-century Jesuit, Luis de Molina. Molinism is a system of thought that seeks to reconcile the sovereignty of God and the free will of man. The heart of Molinism is the principle that God is completely sovereign and man is also free in a libertarian sense. Molinism partly seeks to avoid so-called “theological determinism”: the view that God decrees who will be saved or damned without any meaningful impact of their own free choice. Today’s highest-profile defenders of Molinism are William Lane Craig and Alvin Plantinga. > > > > > ***The primary distinctive of Molinism is the affirmation that God has middle knowledge*** (scientia media). Molinism holds that God’s knowledge consists of three logical moments. These “moments” of knowledge are not to be thought of as chronological; rather, they are to be understood as “logical.” In other words, one moment does not come before another moment in time; instead, one moment is logically prior to the other moments. The Molinist differentiates between three different moments of knowledge which are respectively called natural knowledge, middle knowledge and free knowledge. > > > > > **1. Natural Knowledge** – This is God’s knowledge of all necessary and all possible truths: all things which “can be.” In this “moment” God knows every possible combination of causes and effects. He also knows all the truths of logic and all moral truths. This knowledge is independent of God’s will, a point few if any theologians would dispute. > > > > > **2. Middle Knowledge** – This is God’s knowledge of what a free creature would do in any given circumstance. This knowledge consists of what philosophers call counterfactuals of creaturely freedom. These are facts about what any creature with a free will would freely do in any circumstance in which it could be placed. This knowledge, like natural knowledge, is independent of God’s will. > > > > > **3. Creative Command** – this is the “moment” where God actually acts. Between His knowledge of all that is or could be, and all that actually comes to be, is God’s purposeful intervention and creation. > > > > > **4. Free Knowledge** – This is God’s knowledge of what He decided to create: all things that “actually are.” God’s free knowledge is His knowledge of the actual world as it is. This knowledge is completely dependent on God’s will. > > > > > Using middle knowledge, Molinism attempts to show that all of God’s knowledge is self-contained, but it is ordered so as to allow for the possibility of man’s free will. In other words, man is completely free, but God is also completely sovereign—He is absolutely in control of all that happens, and yet humanity’s choices are not coerced. > > > > > According to Molinism, God omnisciently knows what you would have been like had you lived in Africa instead of Australia, or had a car accident that paralyzed you at age 9. He knows how the world would have been changed had John F. Kennedy not been assassinated. More importantly, He knows who would choose to be saved and who would not, in each of those varying circumstances. > > > > > Accordingly, it is out of this (middle) knowledge that God chooses to create. God has middle knowledge of all feasible worlds, and He chooses to create the world that corresponds to His ultimate desires. Therefore, while a person is truly free, God is truly in control of who is or is not saved. Molinists differ on how God defines His underlying desires. For example, some believe God is seeking the maximum number of people to be saved. Others believe God creates in order to maximize some other divine goal. Source: <https://www.gotquestions.org/molinism.html> > > > As to how it differs from Arminianism and Calvinism, I doubt I could do justice to that. Perhaps you could draw from these articles: <https://www.gotquestions.org/arminianism.html> <https://www.gotquestions.org/calvinism.html> <https://www.gotquestions.org/Calvinism-vs-Arminianism.html> Like Nigel J, I am simply presenting one particular point of view in the hope it will help to answer your question. I have permission to copy and paste the Got Questions article on Molinism.
TL;DR: Calvinists and Arminians disagree about whether man is able and/or free to choose God, Molinism is to do with God's knowledge and not salvation, so can fit with either. Molinist here - Molinism isn't technically a view of soteriology (meaning to do with man's salvation), but is a view of God's knowledge, summed up pretty well by the gotquestions article referenced by Lesley. Molinism's two main points (or core doctrines) are: 1: God has Middle knowledge 2: Man, at least some of the time, has libertarian free will (although the precise definition is disputed, a reasonable interpretation of the term is 'the ability to do otherwise') Arminianism and Calvinism, on the other hand, are directly opposing views that are to do with soteriology, not God's knowledge. Thus, you could be an Arminian Molinist or a Calvinist Molinist. The latter, however, is quite rare. Calvinism is a very difficult doctrine to clearly define, but a working minimum of the system is summed up by the acronym TULIP. I won't go into a lengthy description of each of the letters (it's well documented in many places) but in summary Calvinism teaches that man, in his natural state, is completely unable to come to God (T) . God then 'elects' certain individuals whom He decides to save (U) and draws them to himself via irresistible grace (I) (literally irresistible, the elect person is unable to reject or refuse the grace). Additionally, Christ's atonement only covers and was only intended for these elect (L), and finally, the elect will never fall away or apostasize (P). Arminianism is even harder to specifically define, but the gist is that although man would be unable to come to God alone, God's grace (prevenient grace) overcomes this state and enables all men to come to God and be saved, although it doesn't guarantee any will or force anyone. Christ's atonement covers any and all who come to Him, and is not limited. Beyond that, there are a lot of variations of Arminianism that I don't know as much as I should about. It is worth noting that some (Many? Most?) Molinists hold to a soteriology which is similar to Arminianism but goes further in regards to God's providence and the election of individuals while maintaining free will, but that is beyond the scope of the question as it technically isn't Molinism proper. Hope that helps
30,561,195
I have an app in which the main view is a `PopupWindow` with a couple of `ImageViews` and an `EditText` on top of them. My problem is when I enter a very long text and the text box expands down and pushing the image views out of the view and I can't see them, and in order to see them back I need to delete some text. What is the proper way of overcoming this? thanks.
2015/05/31
[ "https://Stackoverflow.com/questions/30561195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2162550/" ]
There is a difference, and it has to do with whether that list is referenced from multiple places/names. ``` >>> a = [1, 2, 3] >>> b = a >>> del a[:] >>> print(b) [] >>> a = [1, 2, 3] >>> b = a >>> a = [] >>> print(b) [1, 2, 3] ``` Using `del a[:]` clears the *existing* list, which means anywhere it's referenced will become an empty list. Using `a = []` sets `a` to point to a *new* empty list, which means that other places the original list is referenced will remain non-empty. The key to understanding here is to realize that when you assign something to a variable, it just makes that name point to a thing. Things can have multiple names, and changing what a name points to doesn't change the thing itself.
This can probably best be shown: ``` >>> a = [1, 2, 3] >>> id(a) 45556280 >>> del a[:] >>> id(a) 45556280 >>> b = [4, 5, 6] >>> id(b) 45556680 >>> b = [] >>> id(b) 45556320 ``` When you do `a[:]` you are referring to all elements within the list "assigned" to `a`. The `del` statement removes references to objects. So, doing `del a[:]` is saying "remove all references to objects from within the list assigned to `a`". The list itself has not changed. We can see this with the id function, which gives us a number representing an object in memory. The id of the list before using `del` and after remains the same, indicating the same list object is assigned to `a`. On the other hand, when we assign a non-empty list to `b` and then assign a new *empty* list to `b`, the id changes. This is because we have actually moved the `b` reference from the existing `[4, 5, 6]` list to the new `[]` list. Beyond just the identity of the objects you are dealing with, there are other things to be aware of: ``` >>> a = [1, 2, 3] >>> b = a >>> del a[:] >>> print a [] >>> print b [] ``` Both `b` and `a` refer to the same list. Removing the elements from the `a` list without changing the list itself mutates the list in place. As `b` references the same object, we see the same result there. If you did `a = []` instead, then `a` will refer to a new empty list while `b` continues to reference the `[1, 2, 3]` list.
30,561,195
I have an app in which the main view is a `PopupWindow` with a couple of `ImageViews` and an `EditText` on top of them. My problem is when I enter a very long text and the text box expands down and pushing the image views out of the view and I can't see them, and in order to see them back I need to delete some text. What is the proper way of overcoming this? thanks.
2015/05/31
[ "https://Stackoverflow.com/questions/30561195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2162550/" ]
There is a difference, and it has to do with whether that list is referenced from multiple places/names. ``` >>> a = [1, 2, 3] >>> b = a >>> del a[:] >>> print(b) [] >>> a = [1, 2, 3] >>> b = a >>> a = [] >>> print(b) [1, 2, 3] ``` Using `del a[:]` clears the *existing* list, which means anywhere it's referenced will become an empty list. Using `a = []` sets `a` to point to a *new* empty list, which means that other places the original list is referenced will remain non-empty. The key to understanding here is to realize that when you assign something to a variable, it just makes that name point to a thing. Things can have multiple names, and changing what a name points to doesn't change the thing itself.
``` >>> list1 = [1,2,3,4,5] >>> list2 = list1 ``` **To get a better understanding, let us see with the help of pictures what happens internally.** ``` >>> list1 = [1,2,3,4,5] ``` This creates a list object and assigns it to `list1`. ![Initialization of list1 in memory](https://i.stack.imgur.com/zkQ8F.png) ``` >>> list2 = list1 ``` The list object which `list1` was referring to is also assigned to `list2`. ![](https://i.stack.imgur.com/IM5Ra.png) Now, lets look at the methods to empty an list and what actually happens internally. **METHOD-1: Set to empty list [] :** ``` >>> list1 = [] >>> list2 [1,2,3,4,5] ``` ![Set list1 to empty list](https://i.stack.imgur.com/FQWAL.png) This does not delete the elements of the list but deletes the reference to the list. So, `list1` now points to an empty list but all other references will have access to that old `list1`. This method just creates a new list object and assigns it to `list1`. Any other references will remain. **METHOD-2: Delete using slice operator[:] :** ``` >>> del list1[:] >>> list2 [] ``` ![Delete all elements of list1 using slice operator](https://i.stack.imgur.com/qSgVB.png) When we use the slice operator to delete all the elements of the list, then all the places where it is referenced, it becomes an empty list. So `list2` also becomes an empty list.
30,561,195
I have an app in which the main view is a `PopupWindow` with a couple of `ImageViews` and an `EditText` on top of them. My problem is when I enter a very long text and the text box expands down and pushing the image views out of the view and I can't see them, and in order to see them back I need to delete some text. What is the proper way of overcoming this? thanks.
2015/05/31
[ "https://Stackoverflow.com/questions/30561195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2162550/" ]
There is a difference, and it has to do with whether that list is referenced from multiple places/names. ``` >>> a = [1, 2, 3] >>> b = a >>> del a[:] >>> print(b) [] >>> a = [1, 2, 3] >>> b = a >>> a = [] >>> print(b) [1, 2, 3] ``` Using `del a[:]` clears the *existing* list, which means anywhere it's referenced will become an empty list. Using `a = []` sets `a` to point to a *new* empty list, which means that other places the original list is referenced will remain non-empty. The key to understanding here is to realize that when you assign something to a variable, it just makes that name point to a thing. Things can have multiple names, and changing what a name points to doesn't change the thing itself.
Well, del uses just a little less space in the computer as the person above me implied. The computer still accepts the variable as the same code, except with a different value. However, when you variable is assigned something else, the computer assigns a completely different code ID to it in order to account for the change in memory required.
30,561,195
I have an app in which the main view is a `PopupWindow` with a couple of `ImageViews` and an `EditText` on top of them. My problem is when I enter a very long text and the text box expands down and pushing the image views out of the view and I can't see them, and in order to see them back I need to delete some text. What is the proper way of overcoming this? thanks.
2015/05/31
[ "https://Stackoverflow.com/questions/30561195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2162550/" ]
This can probably best be shown: ``` >>> a = [1, 2, 3] >>> id(a) 45556280 >>> del a[:] >>> id(a) 45556280 >>> b = [4, 5, 6] >>> id(b) 45556680 >>> b = [] >>> id(b) 45556320 ``` When you do `a[:]` you are referring to all elements within the list "assigned" to `a`. The `del` statement removes references to objects. So, doing `del a[:]` is saying "remove all references to objects from within the list assigned to `a`". The list itself has not changed. We can see this with the id function, which gives us a number representing an object in memory. The id of the list before using `del` and after remains the same, indicating the same list object is assigned to `a`. On the other hand, when we assign a non-empty list to `b` and then assign a new *empty* list to `b`, the id changes. This is because we have actually moved the `b` reference from the existing `[4, 5, 6]` list to the new `[]` list. Beyond just the identity of the objects you are dealing with, there are other things to be aware of: ``` >>> a = [1, 2, 3] >>> b = a >>> del a[:] >>> print a [] >>> print b [] ``` Both `b` and `a` refer to the same list. Removing the elements from the `a` list without changing the list itself mutates the list in place. As `b` references the same object, we see the same result there. If you did `a = []` instead, then `a` will refer to a new empty list while `b` continues to reference the `[1, 2, 3]` list.
``` >>> list1 = [1,2,3,4,5] >>> list2 = list1 ``` **To get a better understanding, let us see with the help of pictures what happens internally.** ``` >>> list1 = [1,2,3,4,5] ``` This creates a list object and assigns it to `list1`. ![Initialization of list1 in memory](https://i.stack.imgur.com/zkQ8F.png) ``` >>> list2 = list1 ``` The list object which `list1` was referring to is also assigned to `list2`. ![](https://i.stack.imgur.com/IM5Ra.png) Now, lets look at the methods to empty an list and what actually happens internally. **METHOD-1: Set to empty list [] :** ``` >>> list1 = [] >>> list2 [1,2,3,4,5] ``` ![Set list1 to empty list](https://i.stack.imgur.com/FQWAL.png) This does not delete the elements of the list but deletes the reference to the list. So, `list1` now points to an empty list but all other references will have access to that old `list1`. This method just creates a new list object and assigns it to `list1`. Any other references will remain. **METHOD-2: Delete using slice operator[:] :** ``` >>> del list1[:] >>> list2 [] ``` ![Delete all elements of list1 using slice operator](https://i.stack.imgur.com/qSgVB.png) When we use the slice operator to delete all the elements of the list, then all the places where it is referenced, it becomes an empty list. So `list2` also becomes an empty list.
30,561,195
I have an app in which the main view is a `PopupWindow` with a couple of `ImageViews` and an `EditText` on top of them. My problem is when I enter a very long text and the text box expands down and pushing the image views out of the view and I can't see them, and in order to see them back I need to delete some text. What is the proper way of overcoming this? thanks.
2015/05/31
[ "https://Stackoverflow.com/questions/30561195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2162550/" ]
This can probably best be shown: ``` >>> a = [1, 2, 3] >>> id(a) 45556280 >>> del a[:] >>> id(a) 45556280 >>> b = [4, 5, 6] >>> id(b) 45556680 >>> b = [] >>> id(b) 45556320 ``` When you do `a[:]` you are referring to all elements within the list "assigned" to `a`. The `del` statement removes references to objects. So, doing `del a[:]` is saying "remove all references to objects from within the list assigned to `a`". The list itself has not changed. We can see this with the id function, which gives us a number representing an object in memory. The id of the list before using `del` and after remains the same, indicating the same list object is assigned to `a`. On the other hand, when we assign a non-empty list to `b` and then assign a new *empty* list to `b`, the id changes. This is because we have actually moved the `b` reference from the existing `[4, 5, 6]` list to the new `[]` list. Beyond just the identity of the objects you are dealing with, there are other things to be aware of: ``` >>> a = [1, 2, 3] >>> b = a >>> del a[:] >>> print a [] >>> print b [] ``` Both `b` and `a` refer to the same list. Removing the elements from the `a` list without changing the list itself mutates the list in place. As `b` references the same object, we see the same result there. If you did `a = []` instead, then `a` will refer to a new empty list while `b` continues to reference the `[1, 2, 3]` list.
Well, del uses just a little less space in the computer as the person above me implied. The computer still accepts the variable as the same code, except with a different value. However, when you variable is assigned something else, the computer assigns a completely different code ID to it in order to account for the change in memory required.
30,561,195
I have an app in which the main view is a `PopupWindow` with a couple of `ImageViews` and an `EditText` on top of them. My problem is when I enter a very long text and the text box expands down and pushing the image views out of the view and I can't see them, and in order to see them back I need to delete some text. What is the proper way of overcoming this? thanks.
2015/05/31
[ "https://Stackoverflow.com/questions/30561195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2162550/" ]
``` >>> list1 = [1,2,3,4,5] >>> list2 = list1 ``` **To get a better understanding, let us see with the help of pictures what happens internally.** ``` >>> list1 = [1,2,3,4,5] ``` This creates a list object and assigns it to `list1`. ![Initialization of list1 in memory](https://i.stack.imgur.com/zkQ8F.png) ``` >>> list2 = list1 ``` The list object which `list1` was referring to is also assigned to `list2`. ![](https://i.stack.imgur.com/IM5Ra.png) Now, lets look at the methods to empty an list and what actually happens internally. **METHOD-1: Set to empty list [] :** ``` >>> list1 = [] >>> list2 [1,2,3,4,5] ``` ![Set list1 to empty list](https://i.stack.imgur.com/FQWAL.png) This does not delete the elements of the list but deletes the reference to the list. So, `list1` now points to an empty list but all other references will have access to that old `list1`. This method just creates a new list object and assigns it to `list1`. Any other references will remain. **METHOD-2: Delete using slice operator[:] :** ``` >>> del list1[:] >>> list2 [] ``` ![Delete all elements of list1 using slice operator](https://i.stack.imgur.com/qSgVB.png) When we use the slice operator to delete all the elements of the list, then all the places where it is referenced, it becomes an empty list. So `list2` also becomes an empty list.
Well, del uses just a little less space in the computer as the person above me implied. The computer still accepts the variable as the same code, except with a different value. However, when you variable is assigned something else, the computer assigns a completely different code ID to it in order to account for the change in memory required.
55,559,336
I've got a stored procedure that i'm having some issues with. I'm trying to lookup against my table `GOTWVotes` and if `VotedBy` hasn't voted before write the vote to the table(this is working) however if `VotedBy` has voted before not to write to the table and return `VoteCount` as 1. Although it doesn't write to the table when `VotedBy` exists the value of `VoteCount`always appears to be 0 Any help would be appreciated ``` CREATE PROCEDURE [dbo].[Votes] @VotedMember BIGINT, @VotedBy BIGINT AS DECLARE @votecount INT BEGIN TRY BEGIN TRANSACTION t_Transaction SELECT TOP 1 * FROM [GOTWVotes] WITH (TABLOCKX) SELECT @votecount = COUNT(*) FROM [dbo].[GOTWVotes] WHERE [VotedBy] = @VotedBy IF @votecount = 0 INSERT INTO [dbo].[GOTWVotes] ([VotedMember],[VotedBy]) VALUES (@VotedMember, @VotedBy) COMMIT TRANSACTION t_Transaction END TRY BEGIN CATCH SET @votecount = -1 ROLLBACK TRANSACTION t_Transaction END CATCH RETURN @votecount ```
2019/04/07
[ "https://Stackoverflow.com/questions/55559336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11041621/" ]
Spring uses `jakarta.annotation.PostConstruct`. As a contributor in `spring-cloud-kubernetes`, I have used it and included it in that project numerous times. As a matter of fact we favor *dropping* `InitializingBean`.
Ref <https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-postconstruct-and-predestroy-annotations> > > Like @Resource, the @PostConstruct and @PreDestroy annotation types were a part of the standard Java libraries from JDK 6 to 8. However, the entire javax.annotation package got separated from the core Java modules in JDK 9 and eventually removed in JDK 11. If needed, the javax.annotation-api artifact needs to be obtained via Maven Central now, **simply to be added to the application’s classpath like any other library.** > > >
27,913,144
Is there a way to specify which bold or italic variations to use in a font like Avenir Next? Here's an example. By default a Avenir Next will choose Avenir Next Bold for bold but I would like it to use Avenir Next Demi Bold instead. [Here is fiddle.](http://jsfiddle.net/pdtk1rjt/) ``` <span style="font-family:'Avenir Next'"> Normal <!-- I want this to be AvenirNext-DemiBold. --> <span style="font-weight:bold">Bold</span> </span> <br> <span style="font-family:'Avenir Next'">Normal</span> <span style="font-family:'AvenirNext-DemiBold'">Bold</span> ```
2015/01/13
[ "https://Stackoverflow.com/questions/27913144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/284714/" ]
CSS dosen't let you change font-family for different weights of the same font, unless you start providing your own font files, which is a lot of work for a better looking bold... However, if you can avoid using inline styles, and instead use the `<strong>` tag to mark bold text, you'll be able to get the exact result you want, and have cleaner HTML: ```css span { font-family:'Avenir Next'; } strong { font-weight: bold; font-family: 'AvenirNext-DemiBold'; } ``` ```html <span>Normal</span> <span><strong>Bold</strong></span> <br> <span style="font-family:'Avenir Next'">Normal</span> <span style="font-family:'AvenirNext-DemiBold'">Bold</span> ```
The solution is to use the @font-face rule. ***Update: This seems broken now on OS X 10.10.2.*** ```css @font-face { font-family: 'Avenir Next'; src: local('AvenirNext-DemiBold'); font-weight: bold; font-style: normal; } ``` ```html <span style="font-family:'Avenir Next'"> Normal <span style="font-weight:bold">Bold</span> </span> ```
13,411,779
I have a table of representative in some schema in "mysql" and the table has a column named "userName". now for log in to program, i need to get data from text field in frame and check it with all usernames in in that column (username column has more than one row!) and if text of in username jtextfield equals with one of those rows, then the log in will be permitted ! i need a method to do that. i have write something but it does not work! Here : ``` `public static boolean checkRep(String user, String pass) { String sql = "SELECT * FROM representative"; Connection con = DBManager.getConnection(); PreparedStatement st = null; try { st = con.prepareStatement(sql); ResultSet rs = st.executeQuery(sql); while (rs.next()){ if(user == rs.getString("passWord")){ System.out.println("Right"); } } } catch (SQLException e) { e.printStackTrace(); } return true; }` ```
2012/11/16
[ "https://Stackoverflow.com/questions/13411779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1828782/" ]
I think you should try this ``` .... if (user.equals(rs.getString("passWord")) .... ```
The problem is with the string equality check in your if.Always check string equality using `equals` method. `==` operator checks if two reference variables point the same object. it checksif both the reference variables are identical. equals method checksif both objects are considered meaningfully equal. ``` if(user == rs.getString("passWord")){ should be if(user.equals(rs.getString("passWord"))){ ```
13,411,779
I have a table of representative in some schema in "mysql" and the table has a column named "userName". now for log in to program, i need to get data from text field in frame and check it with all usernames in in that column (username column has more than one row!) and if text of in username jtextfield equals with one of those rows, then the log in will be permitted ! i need a method to do that. i have write something but it does not work! Here : ``` `public static boolean checkRep(String user, String pass) { String sql = "SELECT * FROM representative"; Connection con = DBManager.getConnection(); PreparedStatement st = null; try { st = con.prepareStatement(sql); ResultSet rs = st.executeQuery(sql); while (rs.next()){ if(user == rs.getString("passWord")){ System.out.println("Right"); } } } catch (SQLException e) { e.printStackTrace(); } return true; }` ```
2012/11/16
[ "https://Stackoverflow.com/questions/13411779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1828782/" ]
Your query should be more specific like `"SELECT * FROM representative where user=? and passWord =?";` And in `prepareStatement` should set those dynamic values ``` st = con.prepareStatement(sql); st.setString(1,user); st.setString(2,pass); ``` And you need to check result like - ``` //no while if(rs.next()){ System.out.println("user found in db"); return true; } ```
The problem is with the string equality check in your if.Always check string equality using `equals` method. `==` operator checks if two reference variables point the same object. it checksif both the reference variables are identical. equals method checksif both objects are considered meaningfully equal. ``` if(user == rs.getString("passWord")){ should be if(user.equals(rs.getString("passWord"))){ ```
13,411,779
I have a table of representative in some schema in "mysql" and the table has a column named "userName". now for log in to program, i need to get data from text field in frame and check it with all usernames in in that column (username column has more than one row!) and if text of in username jtextfield equals with one of those rows, then the log in will be permitted ! i need a method to do that. i have write something but it does not work! Here : ``` `public static boolean checkRep(String user, String pass) { String sql = "SELECT * FROM representative"; Connection con = DBManager.getConnection(); PreparedStatement st = null; try { st = con.prepareStatement(sql); ResultSet rs = st.executeQuery(sql); while (rs.next()){ if(user == rs.getString("passWord")){ System.out.println("Right"); } } } catch (SQLException e) { e.printStackTrace(); } return true; }` ```
2012/11/16
[ "https://Stackoverflow.com/questions/13411779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1828782/" ]
Your query should be more specific like `"SELECT * FROM representative where user=? and passWord =?";` And in `prepareStatement` should set those dynamic values ``` st = con.prepareStatement(sql); st.setString(1,user); st.setString(2,pass); ``` And you need to check result like - ``` //no while if(rs.next()){ System.out.println("user found in db"); return true; } ```
I think you should try this ``` .... if (user.equals(rs.getString("passWord")) .... ```
1,674,980
I really can't believe I couldn't find a clear answer to this... How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the `new` operator. E.g.: ``` class Blah { public: Blah() { throw "oops"; } }; void main() { Blah* b = NULL; try { b = new Blah(); } catch (...) { // What now? } } ``` When I tried this out, `b` is NULL in the catch block (which makes sense). When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor. This on the MSDN website [seems to confirm this](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx): > > When new is used to allocate memory > for a C++ class object, the object's > constructor is called after the memory > is allocated. > > > So, bearing in mind that the local variable `b` is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory? It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say? CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate *THE* object (`Blah` in my case).
2009/11/04
[ "https://Stackoverflow.com/questions/1674980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31760/" ]
If the Constructor throws the memory allocated for the object is auto-magically returned to the system. Note the destructor of the class that threw will not be called. But the destructor of any base class (where the base constructor has completed) will also be called. Note: As most other people have noted members may need some clean up. Members that have been fully initialized will have their destructors called, but if you have any RAW pointer members that you own (ie delete in the destructor) you will have to do some clean up before you do the throw (another reason not to use owned RAW pointers in your class). ``` #include <iostream> class Base { public: Base() {std::cout << "Create Base\n";} ~Base() {std::cout << "Destroy Base\n";} }; class Deriv: public Base { public: Deriv(int x) {std::cout << "Create Deriv\n";if (x > 0) throw int(x);} ~Deriv() {std::cout << "Destroy Deriv\n";} }; int main() { try { { Deriv d0(0); // All constructors/Destructors called. } { Deriv d1(1); // Base constructor and destructor called. // Derived constructor called (not destructor) } } catch(...) { throw; // Also note here. // If an exception escapes main it is implementation defined // whether the stack is unwound. By catching in main() you force // the stack to unwind to this point. If you can't handle re-throw // so the system exception handling can provide the appropriate // error handling (such as user messages). } } ```
The problem described is as old as the road to Rome, to use a Dutch saying. I have worked out the problem and a memory allocation for an object that might throw an exception looks as follows: ``` try { std::string *l_string = (_heap_cleanup_tpl<std::string>(&l_string), new std::string(0xf0000000, ' ')); delete l_string; } catch(std::exception &) { } ``` Before the actual call to the `new`-operator, a nameless (temporary) object is created, which receives the address of the allocated memory through a user-defined new-operator (see the rest of this answer). In case of normal programme execution, the temporary object passes the result of the new-operator (the newly created and fully constructed object, in our case a very very very long string) to the variable `l_string`. In case of an exception, the value is not passed on, but the destructor of the temporary object deletes the memory (without ofcourse calling the destructor of the main object). It is a bit fuzzy way of dealing with the issue, but it works. Problems may arise because this solution requires a user-defined new-operator and a user-defined delete-operator to go allong with it. The user-defined new/delete-operators would have to call the C++-standard library's implementation of new/delete-operators, but I have left that out for briefity and relied on `malloc()` and `free()` instead. It is not the final answer, but I think it is worth working this one out. PS: There was an 'undocumented' feature in the code below, so I have made an improvement. The code for the temporary object is as follows: ``` class _heap_cleanup_helper { public: _heap_cleanup_helper(void **p_heap_block) : m_heap_block(p_heap_block), m_previous(m_last), m_guard_block(NULL) { *m_heap_block = NULL; m_last = this; } ~_heap_cleanup_helper() { if (*m_heap_block == NULL) operator delete(m_guard_block); m_last = m_previous; } void **m_heap_block, *m_guard_block; _heap_cleanup_helper *m_previous; static _heap_cleanup_helper *m_last; }; _heap_cleanup_helper *_heap_cleanup_helper::m_last; template <typename p_alloc_type> class _heap_cleanup_tpl : public _heap_cleanup_helper { public: _heap_cleanup_tpl(p_alloc_type **p_heap_block) : _heap_cleanup_helper((void **)p_heap_block) { } }; ``` The user-defined new-operator is as follows: ``` void *operator new (size_t p_cbytes) { void *l_retval = malloc(p_cbytes); if ( l_retval != NULL && *_heap_cleanup_helper::m_last->m_heap_block == NULL && _heap_cleanup_helper::m_last->m_guard_block == NULL ) { _heap_cleanup_helper::m_last->m_guard_block = l_retval; } if (p_cbytes != 0 && l_retval == NULL) throw std::bad_alloc(); return l_retval; } void operator delete(void *p_buffer) { if (p_buffer != NULL) free(p_buffer); } ```
1,674,980
I really can't believe I couldn't find a clear answer to this... How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the `new` operator. E.g.: ``` class Blah { public: Blah() { throw "oops"; } }; void main() { Blah* b = NULL; try { b = new Blah(); } catch (...) { // What now? } } ``` When I tried this out, `b` is NULL in the catch block (which makes sense). When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor. This on the MSDN website [seems to confirm this](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx): > > When new is used to allocate memory > for a C++ class object, the object's > constructor is called after the memory > is allocated. > > > So, bearing in mind that the local variable `b` is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory? It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say? CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate *THE* object (`Blah` in my case).
2009/11/04
[ "https://Stackoverflow.com/questions/1674980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31760/" ]
If an object cannot complete destruction because the constructor throws an exception, the first thing to happen (this happens as part of the constructor's special handling) is that all member variables to have been constructed are destroyed - if an exception is thrown in the initializer list, this means that only elements for which the initializer has completed are destroyed. Then, if the object was being allocated with `new`, the appropriate deallocation function (`operator delete`) is called with the same additional arguments that were passed to `operator new`. For instance, `new (std::nothrow) SomethingThatThrows()` will allocate memory with `operator new (size_of_ob, nothrow)`, attempt to construct `SomethingThatThrows`, destroy any members that were successfully constructed, then call `operator delete (ptr_to_obj, nothrow)` when an exception is propagated - it won't leak memory. What you have to be careful is allocating several objects in succession - if one of the later ones throws, the previous ones will not be automatically be deallocated. The best way around this is with smart pointers, because as local objects their destructors will be called during stack unwinding, and their destructors will properly deallocate memory.
The long and short of it is that if you haven't made any allocations of other entities in you object(as in your example) then the memory that was allocated will be deleted automatically. However, any new statements(or anything else that directly manages memory) needs to be handled in a catch statement in the constructor, Otherwise the object is deleted without deleting it's subsequent allocations and you, my friend, have a leak.
1,674,980
I really can't believe I couldn't find a clear answer to this... How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the `new` operator. E.g.: ``` class Blah { public: Blah() { throw "oops"; } }; void main() { Blah* b = NULL; try { b = new Blah(); } catch (...) { // What now? } } ``` When I tried this out, `b` is NULL in the catch block (which makes sense). When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor. This on the MSDN website [seems to confirm this](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx): > > When new is used to allocate memory > for a C++ class object, the object's > constructor is called after the memory > is allocated. > > > So, bearing in mind that the local variable `b` is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory? It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say? CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate *THE* object (`Blah` in my case).
2009/11/04
[ "https://Stackoverflow.com/questions/1674980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31760/" ]
From the C++ 2003 Standard 5.3.4/17 - New: > > If any part of the object initialization described above terminates by throwing an exception and a suitable deallocation function can be found, the deallocation function is called to free the memory in which the object was being constructed, after which the exception continues to propagate in the context of the new-expression. If no unambiguous matching deallocation function can be found, propagating the exception does not cause the object’s memory to be freed. [Note: This is appropriate when the called allocation function does not allocate memory; otherwise, it is likely to result in a memory leak. ] > > > So there may or may not be a leak - it depends on whether an appropriate deallocator can be found (which is normally the case, unless operator new/delete have been overridden).In the case where there's a suitable deallocator, the compiler is responsible for wiring in a call to it if the constructor throws. Note that this is more or less unrelated to what happens to resources acquired in the constructor, which is what my first attempt at an answer discussed - and is a question that is discussed in many FAQs, articles, and postings.
Quoted from C++ FAQ ([parashift.com](http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.10)): > > [17.4] How should I handle resources if my constructors may throw > exceptions? > ------------------------------------------------------------------------------ > > > Every data member inside your object should clean up its own mess. > > > If a constructor throws an exception, the object's destructor is not > run. If your object has already done something that needs to be undone > (such as allocating some memory, opening a file, or locking a > semaphore), this "stuff that needs to be undone" *must* be remembered > by a data member inside the object. > > > For example, rather than allocating memory into a raw `Fred*` data > member, put the allocated memory into a "smart pointer" member object, > and the destructor of this smart pointer will `delete` the `Fred` > object when the smart pointer dies. The template `std::auto_ptr` is an > example of such as "smart pointer." You can also [write your own > reference counting smart pointer](http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.22). You can also [use smart pointers > to "point" to disk records or objects on other machines](http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.3). > > > By the way, if you think your `Fred` class is going to be allocated > into a smart pointer, be nice to your users and create a `typedef` > within your `Fred` class: > > > > ``` > #include <memory> > > class Fred { > public: > typedef std::auto_ptr<Fred> Ptr; > ... > }; > > ``` > > That typedef simplifies the syntax of all the code that uses your > objects: your users can say `Fred::Ptr` instead of > `std::auto_ptr<Fred>`: > > > > ``` > #include "Fred.h" > > void f(std::auto_ptr<Fred> p); // explicit but verbose > void f(Fred::Ptr p); // simpler > > void g() > { > std::auto_ptr<Fred> p1( new Fred() ); // explicit but verbose > Fred::Ptr p2( new Fred() ); // simpler > ... > } > > ``` > >
1,674,980
I really can't believe I couldn't find a clear answer to this... How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the `new` operator. E.g.: ``` class Blah { public: Blah() { throw "oops"; } }; void main() { Blah* b = NULL; try { b = new Blah(); } catch (...) { // What now? } } ``` When I tried this out, `b` is NULL in the catch block (which makes sense). When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor. This on the MSDN website [seems to confirm this](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx): > > When new is used to allocate memory > for a C++ class object, the object's > constructor is called after the memory > is allocated. > > > So, bearing in mind that the local variable `b` is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory? It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say? CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate *THE* object (`Blah` in my case).
2009/11/04
[ "https://Stackoverflow.com/questions/1674980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31760/" ]
If the Constructor throws the memory allocated for the object is auto-magically returned to the system. Note the destructor of the class that threw will not be called. But the destructor of any base class (where the base constructor has completed) will also be called. Note: As most other people have noted members may need some clean up. Members that have been fully initialized will have their destructors called, but if you have any RAW pointer members that you own (ie delete in the destructor) you will have to do some clean up before you do the throw (another reason not to use owned RAW pointers in your class). ``` #include <iostream> class Base { public: Base() {std::cout << "Create Base\n";} ~Base() {std::cout << "Destroy Base\n";} }; class Deriv: public Base { public: Deriv(int x) {std::cout << "Create Deriv\n";if (x > 0) throw int(x);} ~Deriv() {std::cout << "Destroy Deriv\n";} }; int main() { try { { Deriv d0(0); // All constructors/Destructors called. } { Deriv d1(1); // Base constructor and destructor called. // Derived constructor called (not destructor) } } catch(...) { throw; // Also note here. // If an exception escapes main it is implementation defined // whether the stack is unwound. By catching in main() you force // the stack to unwind to this point. If you can't handle re-throw // so the system exception handling can provide the appropriate // error handling (such as user messages). } } ```
I think it's kind of wierd for a constructor to raise an exception. Could you have a return value and test it in your main? ``` class Blah { public: Blah() { if Error { this.Error = "oops"; } } }; void main() { Blah* b = NULL; b = new Blah(); if (b.Error == "oops") { delete (b); b = NULL; } ```
1,674,980
I really can't believe I couldn't find a clear answer to this... How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the `new` operator. E.g.: ``` class Blah { public: Blah() { throw "oops"; } }; void main() { Blah* b = NULL; try { b = new Blah(); } catch (...) { // What now? } } ``` When I tried this out, `b` is NULL in the catch block (which makes sense). When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor. This on the MSDN website [seems to confirm this](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx): > > When new is used to allocate memory > for a C++ class object, the object's > constructor is called after the memory > is allocated. > > > So, bearing in mind that the local variable `b` is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory? It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say? CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate *THE* object (`Blah` in my case).
2009/11/04
[ "https://Stackoverflow.com/questions/1674980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31760/" ]
From the C++ 2003 Standard 5.3.4/17 - New: > > If any part of the object initialization described above terminates by throwing an exception and a suitable deallocation function can be found, the deallocation function is called to free the memory in which the object was being constructed, after which the exception continues to propagate in the context of the new-expression. If no unambiguous matching deallocation function can be found, propagating the exception does not cause the object’s memory to be freed. [Note: This is appropriate when the called allocation function does not allocate memory; otherwise, it is likely to result in a memory leak. ] > > > So there may or may not be a leak - it depends on whether an appropriate deallocator can be found (which is normally the case, unless operator new/delete have been overridden).In the case where there's a suitable deallocator, the compiler is responsible for wiring in a call to it if the constructor throws. Note that this is more or less unrelated to what happens to resources acquired in the constructor, which is what my first attempt at an answer discussed - and is a question that is discussed in many FAQs, articles, and postings.
The problem described is as old as the road to Rome, to use a Dutch saying. I have worked out the problem and a memory allocation for an object that might throw an exception looks as follows: ``` try { std::string *l_string = (_heap_cleanup_tpl<std::string>(&l_string), new std::string(0xf0000000, ' ')); delete l_string; } catch(std::exception &) { } ``` Before the actual call to the `new`-operator, a nameless (temporary) object is created, which receives the address of the allocated memory through a user-defined new-operator (see the rest of this answer). In case of normal programme execution, the temporary object passes the result of the new-operator (the newly created and fully constructed object, in our case a very very very long string) to the variable `l_string`. In case of an exception, the value is not passed on, but the destructor of the temporary object deletes the memory (without ofcourse calling the destructor of the main object). It is a bit fuzzy way of dealing with the issue, but it works. Problems may arise because this solution requires a user-defined new-operator and a user-defined delete-operator to go allong with it. The user-defined new/delete-operators would have to call the C++-standard library's implementation of new/delete-operators, but I have left that out for briefity and relied on `malloc()` and `free()` instead. It is not the final answer, but I think it is worth working this one out. PS: There was an 'undocumented' feature in the code below, so I have made an improvement. The code for the temporary object is as follows: ``` class _heap_cleanup_helper { public: _heap_cleanup_helper(void **p_heap_block) : m_heap_block(p_heap_block), m_previous(m_last), m_guard_block(NULL) { *m_heap_block = NULL; m_last = this; } ~_heap_cleanup_helper() { if (*m_heap_block == NULL) operator delete(m_guard_block); m_last = m_previous; } void **m_heap_block, *m_guard_block; _heap_cleanup_helper *m_previous; static _heap_cleanup_helper *m_last; }; _heap_cleanup_helper *_heap_cleanup_helper::m_last; template <typename p_alloc_type> class _heap_cleanup_tpl : public _heap_cleanup_helper { public: _heap_cleanup_tpl(p_alloc_type **p_heap_block) : _heap_cleanup_helper((void **)p_heap_block) { } }; ``` The user-defined new-operator is as follows: ``` void *operator new (size_t p_cbytes) { void *l_retval = malloc(p_cbytes); if ( l_retval != NULL && *_heap_cleanup_helper::m_last->m_heap_block == NULL && _heap_cleanup_helper::m_last->m_guard_block == NULL ) { _heap_cleanup_helper::m_last->m_guard_block = l_retval; } if (p_cbytes != 0 && l_retval == NULL) throw std::bad_alloc(); return l_retval; } void operator delete(void *p_buffer) { if (p_buffer != NULL) free(p_buffer); } ```
1,674,980
I really can't believe I couldn't find a clear answer to this... How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the `new` operator. E.g.: ``` class Blah { public: Blah() { throw "oops"; } }; void main() { Blah* b = NULL; try { b = new Blah(); } catch (...) { // What now? } } ``` When I tried this out, `b` is NULL in the catch block (which makes sense). When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor. This on the MSDN website [seems to confirm this](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx): > > When new is used to allocate memory > for a C++ class object, the object's > constructor is called after the memory > is allocated. > > > So, bearing in mind that the local variable `b` is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory? It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say? CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate *THE* object (`Blah` in my case).
2009/11/04
[ "https://Stackoverflow.com/questions/1674980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31760/" ]
If an object cannot complete destruction because the constructor throws an exception, the first thing to happen (this happens as part of the constructor's special handling) is that all member variables to have been constructed are destroyed - if an exception is thrown in the initializer list, this means that only elements for which the initializer has completed are destroyed. Then, if the object was being allocated with `new`, the appropriate deallocation function (`operator delete`) is called with the same additional arguments that were passed to `operator new`. For instance, `new (std::nothrow) SomethingThatThrows()` will allocate memory with `operator new (size_of_ob, nothrow)`, attempt to construct `SomethingThatThrows`, destroy any members that were successfully constructed, then call `operator delete (ptr_to_obj, nothrow)` when an exception is propagated - it won't leak memory. What you have to be careful is allocating several objects in succession - if one of the later ones throws, the previous ones will not be automatically be deallocated. The best way around this is with smart pointers, because as local objects their destructors will be called during stack unwinding, and their destructors will properly deallocate memory.
I think it's kind of wierd for a constructor to raise an exception. Could you have a return value and test it in your main? ``` class Blah { public: Blah() { if Error { this.Error = "oops"; } } }; void main() { Blah* b = NULL; b = new Blah(); if (b.Error == "oops") { delete (b); b = NULL; } ```
1,674,980
I really can't believe I couldn't find a clear answer to this... How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the `new` operator. E.g.: ``` class Blah { public: Blah() { throw "oops"; } }; void main() { Blah* b = NULL; try { b = new Blah(); } catch (...) { // What now? } } ``` When I tried this out, `b` is NULL in the catch block (which makes sense). When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor. This on the MSDN website [seems to confirm this](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx): > > When new is used to allocate memory > for a C++ class object, the object's > constructor is called after the memory > is allocated. > > > So, bearing in mind that the local variable `b` is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory? It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say? CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate *THE* object (`Blah` in my case).
2009/11/04
[ "https://Stackoverflow.com/questions/1674980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31760/" ]
If the Constructor throws the memory allocated for the object is auto-magically returned to the system. Note the destructor of the class that threw will not be called. But the destructor of any base class (where the base constructor has completed) will also be called. Note: As most other people have noted members may need some clean up. Members that have been fully initialized will have their destructors called, but if you have any RAW pointer members that you own (ie delete in the destructor) you will have to do some clean up before you do the throw (another reason not to use owned RAW pointers in your class). ``` #include <iostream> class Base { public: Base() {std::cout << "Create Base\n";} ~Base() {std::cout << "Destroy Base\n";} }; class Deriv: public Base { public: Deriv(int x) {std::cout << "Create Deriv\n";if (x > 0) throw int(x);} ~Deriv() {std::cout << "Destroy Deriv\n";} }; int main() { try { { Deriv d0(0); // All constructors/Destructors called. } { Deriv d1(1); // Base constructor and destructor called. // Derived constructor called (not destructor) } } catch(...) { throw; // Also note here. // If an exception escapes main it is implementation defined // whether the stack is unwound. By catching in main() you force // the stack to unwind to this point. If you can't handle re-throw // so the system exception handling can provide the appropriate // error handling (such as user messages). } } ```
Quoted from C++ FAQ ([parashift.com](http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.10)): > > [17.4] How should I handle resources if my constructors may throw > exceptions? > ------------------------------------------------------------------------------ > > > Every data member inside your object should clean up its own mess. > > > If a constructor throws an exception, the object's destructor is not > run. If your object has already done something that needs to be undone > (such as allocating some memory, opening a file, or locking a > semaphore), this "stuff that needs to be undone" *must* be remembered > by a data member inside the object. > > > For example, rather than allocating memory into a raw `Fred*` data > member, put the allocated memory into a "smart pointer" member object, > and the destructor of this smart pointer will `delete` the `Fred` > object when the smart pointer dies. The template `std::auto_ptr` is an > example of such as "smart pointer." You can also [write your own > reference counting smart pointer](http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.22). You can also [use smart pointers > to "point" to disk records or objects on other machines](http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.3). > > > By the way, if you think your `Fred` class is going to be allocated > into a smart pointer, be nice to your users and create a `typedef` > within your `Fred` class: > > > > ``` > #include <memory> > > class Fred { > public: > typedef std::auto_ptr<Fred> Ptr; > ... > }; > > ``` > > That typedef simplifies the syntax of all the code that uses your > objects: your users can say `Fred::Ptr` instead of > `std::auto_ptr<Fred>`: > > > > ``` > #include "Fred.h" > > void f(std::auto_ptr<Fred> p); // explicit but verbose > void f(Fred::Ptr p); // simpler > > void g() > { > std::auto_ptr<Fred> p1( new Fred() ); // explicit but verbose > Fred::Ptr p2( new Fred() ); // simpler > ... > } > > ``` > >
1,674,980
I really can't believe I couldn't find a clear answer to this... How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the `new` operator. E.g.: ``` class Blah { public: Blah() { throw "oops"; } }; void main() { Blah* b = NULL; try { b = new Blah(); } catch (...) { // What now? } } ``` When I tried this out, `b` is NULL in the catch block (which makes sense). When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor. This on the MSDN website [seems to confirm this](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx): > > When new is used to allocate memory > for a C++ class object, the object's > constructor is called after the memory > is allocated. > > > So, bearing in mind that the local variable `b` is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory? It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say? CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate *THE* object (`Blah` in my case).
2009/11/04
[ "https://Stackoverflow.com/questions/1674980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31760/" ]
You should refer to the similar questions [here](https://stackoverflow.com/questions/1230423/c-handle-resources-if-constructors-may-throw-exceptions-reference-to-faq-17) and [here](https://stackoverflow.com/questions/1197566/is-it-ever-not-safe-to-throw-an-exception-in-a-constructor). Basically if the constructor throws an exception you're safe that the memory of the object itself is freed again. Although, if other memory has been claimed during the constructor, you're on your own to have it freed before leaving the constructor with the exception. For your question WHO deletes the memory the answer is the code behind the new-operator (which is generated by the compiler). If it recognizes an exception leaving the constructor it has to call all the destructors of the classes members (as those have already been constructed successfully prior calling the constructor code) and free their memory (could be done recursively together with destructor-calling, most probably by calling a proper *delete* on them) as well as free the memory allocated for this class itself. Then it has to rethrow the catched exception from the constructor to the caller of *new*. Of course there may be more work which has to be done but I cannot pull out all the details from my head because they are up to each compiler's implementation.
From the C++ 2003 Standard 5.3.4/17 - New: > > If any part of the object initialization described above terminates by throwing an exception and a suitable deallocation function can be found, the deallocation function is called to free the memory in which the object was being constructed, after which the exception continues to propagate in the context of the new-expression. If no unambiguous matching deallocation function can be found, propagating the exception does not cause the object’s memory to be freed. [Note: This is appropriate when the called allocation function does not allocate memory; otherwise, it is likely to result in a memory leak. ] > > > So there may or may not be a leak - it depends on whether an appropriate deallocator can be found (which is normally the case, unless operator new/delete have been overridden).In the case where there's a suitable deallocator, the compiler is responsible for wiring in a call to it if the constructor throws. Note that this is more or less unrelated to what happens to resources acquired in the constructor, which is what my first attempt at an answer discussed - and is a question that is discussed in many FAQs, articles, and postings.