qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
25,403,082
Got a table in SQL Server which contains a `varchar` column with date data. Unfortunately the dates are in a whole slew of different formats. ``` 2012-05-01 27/05/2012 07MAY2014 19/07/13 ``` There may be others, but that's all I've encountered so far. I need to squeeze these into a `datetime` column into another table, so I've been trying to select them as standard date-time values. At first, I thought that'd be easy: ``` UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103) WHERE ISDATE(myDateColumn) = 0 ``` But the trouble is that SQL Server treats `dd/mm/yy` and `dd/mm/yyyy` as separate formats. The former is code 3, and the latter is code 103. So whichever way I run that update, it chokes on the opposite format. Is there any way I can select/update based on the date format, and get all these dates converted to a single valid `DateTime` format?
2014/08/20
[ "https://Stackoverflow.com/questions/25403082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271907/" ]
In SQL Server 2012, you could use `try_convert()`. Otherwise, you could multiple updates: ``` UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103) WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]'; UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 3) WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9]'; ``` Note: the `where` clause will probably work here for the `update`. It does not work for a `select`. You may need to use a `case` as well: ``` UPDATE myTable SET myDateColumn = (CASE WHEN ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]' THEN CONVERT(DATETIME, myDateColumn, 103) ELSE myDateColumn END) WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-0]' ``` Also, you are putting the values back in the same column so you are overwriting the original data -- and you have another implicit conversion back to a string I would strongly recommend that you add another column to the table with a `datetime` data type and put the correctly-typed value there.
For this first you can convert all the data into another format such as `110` the `USA date fromat`, and then further again update the whole table with the desired format.
25,403,082
Got a table in SQL Server which contains a `varchar` column with date data. Unfortunately the dates are in a whole slew of different formats. ``` 2012-05-01 27/05/2012 07MAY2014 19/07/13 ``` There may be others, but that's all I've encountered so far. I need to squeeze these into a `datetime` column into another table, so I've been trying to select them as standard date-time values. At first, I thought that'd be easy: ``` UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103) WHERE ISDATE(myDateColumn) = 0 ``` But the trouble is that SQL Server treats `dd/mm/yy` and `dd/mm/yyyy` as separate formats. The former is code 3, and the latter is code 103. So whichever way I run that update, it chokes on the opposite format. Is there any way I can select/update based on the date format, and get all these dates converted to a single valid `DateTime` format?
2014/08/20
[ "https://Stackoverflow.com/questions/25403082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271907/" ]
This is totally horrid, but it works with your example: ``` DECLARE @DodgyDates TABLE ( DateString VARCHAR(50)); INSERT INTO @DodgyDates VALUES ('2012-05-01'); INSERT INTO @DodgyDates VALUES ('27/05/2012'); INSERT INTO @DodgyDates VALUES ('07MAY2014'); INSERT INTO @DodgyDates VALUES ('19/07/13'); SELECT * FROM @DodgyDates; --SELECT CONVERT(DATE, DateString) FROM @DodgyDates;--Fails WITH DateDeconstruct AS ( SELECT *, CASE WHEN DateString LIKE '____-__-__' THEN DateString WHEN DateString LIKE '__/__/____' THEN RIGHT(DateString, 4) + '-' + SUBSTRING(DateString, 4, 2) + '-' + LEFT(DateString, 2) WHEN DateString LIKE '__/__/__' THEN '20' + RIGHT(DateString, 2) + '-' + SUBSTRING(DateString, 4, 2) + '-' + LEFT(DateString, 2) WHEN DateString LIKE '_________' THEN RIGHT(DateString, 4) + '-' + CONVERT(VARCHAR(2), DATEPART(MM, DateString)) + '-' + LEFT(DateString, 2) END AS FixedString FROM @DodgyDates) SELECT DateString AS OriginalDate, FixedString AS FixedDate, CONVERT(DATE, FixedString) AS ConvertedDate FROM DateDeconstruct; ``` Results are: ``` OriginalDate FixedDate ConvertedDate 2012-05-01 2012-05-01 2012-05-01 27/05/2012 2012-05-27 2012-05-27 07MAY2014 2014-5-07 2014-05-07 19/07/13 2013-07-19 2013-07-19 ```
For this first you can convert all the data into another format such as `110` the `USA date fromat`, and then further again update the whole table with the desired format.
25,403,082
Got a table in SQL Server which contains a `varchar` column with date data. Unfortunately the dates are in a whole slew of different formats. ``` 2012-05-01 27/05/2012 07MAY2014 19/07/13 ``` There may be others, but that's all I've encountered so far. I need to squeeze these into a `datetime` column into another table, so I've been trying to select them as standard date-time values. At first, I thought that'd be easy: ``` UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103) WHERE ISDATE(myDateColumn) = 0 ``` But the trouble is that SQL Server treats `dd/mm/yy` and `dd/mm/yyyy` as separate formats. The former is code 3, and the latter is code 103. So whichever way I run that update, it chokes on the opposite format. Is there any way I can select/update based on the date format, and get all these dates converted to a single valid `DateTime` format?
2014/08/20
[ "https://Stackoverflow.com/questions/25403082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271907/" ]
My guess is that you just have to try to differentiate between the different classes and handle each case in the appropriate way. Something like this: ``` declare @tab table (d varchar(20)) insert @tab values ('2012-05-01'),('27/05/2012'),('07MAY2014'),('19/07/13') select case when isnumeric(left(d,4)) = 1 then cast(d as date) when len(d) = 10 then convert(date, d, 103) when len(d) = 8 then convert(date, d, 3) when charindex('/',d) = 0 and isnumeric(d) = 0 then convert(date, d, 106) end as [date] from @tab ``` Output: ``` date ---------- 2012-05-01 2012-05-27 2014-05-07 2013-07-19 ``` It might not be that efficient, but I presume this is a one-off operation. I didn't write it as an update statement, but the query should be easy to adapt, and you should consider adding the converted date as a new proper datetime column if possible in my opinion. Edit: here's the corresponding update statement: ``` update @tab set d = case when isnumeric(left(d,4)) = 1 then cast(d as date) when len(d) = 10 then convert(date, d, 103) when len(d) = 8 then convert(date, d, 3) when charindex('/',d) = 0 and isnumeric(d) = 0 then convert(date, d, 106) end from @tab ```
In SQL Server 2012, you could use `try_convert()`. Otherwise, you could multiple updates: ``` UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103) WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]'; UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 3) WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9]'; ``` Note: the `where` clause will probably work here for the `update`. It does not work for a `select`. You may need to use a `case` as well: ``` UPDATE myTable SET myDateColumn = (CASE WHEN ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]' THEN CONVERT(DATETIME, myDateColumn, 103) ELSE myDateColumn END) WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-0]' ``` Also, you are putting the values back in the same column so you are overwriting the original data -- and you have another implicit conversion back to a string I would strongly recommend that you add another column to the table with a `datetime` data type and put the correctly-typed value there.
25,403,082
Got a table in SQL Server which contains a `varchar` column with date data. Unfortunately the dates are in a whole slew of different formats. ``` 2012-05-01 27/05/2012 07MAY2014 19/07/13 ``` There may be others, but that's all I've encountered so far. I need to squeeze these into a `datetime` column into another table, so I've been trying to select them as standard date-time values. At first, I thought that'd be easy: ``` UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103) WHERE ISDATE(myDateColumn) = 0 ``` But the trouble is that SQL Server treats `dd/mm/yy` and `dd/mm/yyyy` as separate formats. The former is code 3, and the latter is code 103. So whichever way I run that update, it chokes on the opposite format. Is there any way I can select/update based on the date format, and get all these dates converted to a single valid `DateTime` format?
2014/08/20
[ "https://Stackoverflow.com/questions/25403082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271907/" ]
My guess is that you just have to try to differentiate between the different classes and handle each case in the appropriate way. Something like this: ``` declare @tab table (d varchar(20)) insert @tab values ('2012-05-01'),('27/05/2012'),('07MAY2014'),('19/07/13') select case when isnumeric(left(d,4)) = 1 then cast(d as date) when len(d) = 10 then convert(date, d, 103) when len(d) = 8 then convert(date, d, 3) when charindex('/',d) = 0 and isnumeric(d) = 0 then convert(date, d, 106) end as [date] from @tab ``` Output: ``` date ---------- 2012-05-01 2012-05-27 2014-05-07 2013-07-19 ``` It might not be that efficient, but I presume this is a one-off operation. I didn't write it as an update statement, but the query should be easy to adapt, and you should consider adding the converted date as a new proper datetime column if possible in my opinion. Edit: here's the corresponding update statement: ``` update @tab set d = case when isnumeric(left(d,4)) = 1 then cast(d as date) when len(d) = 10 then convert(date, d, 103) when len(d) = 8 then convert(date, d, 3) when charindex('/',d) = 0 and isnumeric(d) = 0 then convert(date, d, 106) end from @tab ```
This is totally horrid, but it works with your example: ``` DECLARE @DodgyDates TABLE ( DateString VARCHAR(50)); INSERT INTO @DodgyDates VALUES ('2012-05-01'); INSERT INTO @DodgyDates VALUES ('27/05/2012'); INSERT INTO @DodgyDates VALUES ('07MAY2014'); INSERT INTO @DodgyDates VALUES ('19/07/13'); SELECT * FROM @DodgyDates; --SELECT CONVERT(DATE, DateString) FROM @DodgyDates;--Fails WITH DateDeconstruct AS ( SELECT *, CASE WHEN DateString LIKE '____-__-__' THEN DateString WHEN DateString LIKE '__/__/____' THEN RIGHT(DateString, 4) + '-' + SUBSTRING(DateString, 4, 2) + '-' + LEFT(DateString, 2) WHEN DateString LIKE '__/__/__' THEN '20' + RIGHT(DateString, 2) + '-' + SUBSTRING(DateString, 4, 2) + '-' + LEFT(DateString, 2) WHEN DateString LIKE '_________' THEN RIGHT(DateString, 4) + '-' + CONVERT(VARCHAR(2), DATEPART(MM, DateString)) + '-' + LEFT(DateString, 2) END AS FixedString FROM @DodgyDates) SELECT DateString AS OriginalDate, FixedString AS FixedDate, CONVERT(DATE, FixedString) AS ConvertedDate FROM DateDeconstruct; ``` Results are: ``` OriginalDate FixedDate ConvertedDate 2012-05-01 2012-05-01 2012-05-01 27/05/2012 2012-05-27 2012-05-27 07MAY2014 2014-5-07 2014-05-07 19/07/13 2013-07-19 2013-07-19 ```
25,403,082
Got a table in SQL Server which contains a `varchar` column with date data. Unfortunately the dates are in a whole slew of different formats. ``` 2012-05-01 27/05/2012 07MAY2014 19/07/13 ``` There may be others, but that's all I've encountered so far. I need to squeeze these into a `datetime` column into another table, so I've been trying to select them as standard date-time values. At first, I thought that'd be easy: ``` UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103) WHERE ISDATE(myDateColumn) = 0 ``` But the trouble is that SQL Server treats `dd/mm/yy` and `dd/mm/yyyy` as separate formats. The former is code 3, and the latter is code 103. So whichever way I run that update, it chokes on the opposite format. Is there any way I can select/update based on the date format, and get all these dates converted to a single valid `DateTime` format?
2014/08/20
[ "https://Stackoverflow.com/questions/25403082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271907/" ]
This is totally horrid, but it works with your example: ``` DECLARE @DodgyDates TABLE ( DateString VARCHAR(50)); INSERT INTO @DodgyDates VALUES ('2012-05-01'); INSERT INTO @DodgyDates VALUES ('27/05/2012'); INSERT INTO @DodgyDates VALUES ('07MAY2014'); INSERT INTO @DodgyDates VALUES ('19/07/13'); SELECT * FROM @DodgyDates; --SELECT CONVERT(DATE, DateString) FROM @DodgyDates;--Fails WITH DateDeconstruct AS ( SELECT *, CASE WHEN DateString LIKE '____-__-__' THEN DateString WHEN DateString LIKE '__/__/____' THEN RIGHT(DateString, 4) + '-' + SUBSTRING(DateString, 4, 2) + '-' + LEFT(DateString, 2) WHEN DateString LIKE '__/__/__' THEN '20' + RIGHT(DateString, 2) + '-' + SUBSTRING(DateString, 4, 2) + '-' + LEFT(DateString, 2) WHEN DateString LIKE '_________' THEN RIGHT(DateString, 4) + '-' + CONVERT(VARCHAR(2), DATEPART(MM, DateString)) + '-' + LEFT(DateString, 2) END AS FixedString FROM @DodgyDates) SELECT DateString AS OriginalDate, FixedString AS FixedDate, CONVERT(DATE, FixedString) AS ConvertedDate FROM DateDeconstruct; ``` Results are: ``` OriginalDate FixedDate ConvertedDate 2012-05-01 2012-05-01 2012-05-01 27/05/2012 2012-05-27 2012-05-27 07MAY2014 2014-5-07 2014-05-07 19/07/13 2013-07-19 2013-07-19 ```
In SQL Server 2012, you could use `try_convert()`. Otherwise, you could multiple updates: ``` UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103) WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]'; UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 3) WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9]'; ``` Note: the `where` clause will probably work here for the `update`. It does not work for a `select`. You may need to use a `case` as well: ``` UPDATE myTable SET myDateColumn = (CASE WHEN ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]' THEN CONVERT(DATETIME, myDateColumn, 103) ELSE myDateColumn END) WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-0]' ``` Also, you are putting the values back in the same column so you are overwriting the original data -- and you have another implicit conversion back to a string I would strongly recommend that you add another column to the table with a `datetime` data type and put the correctly-typed value there.
381,823
I designed a device on which there is a HUB, FT232 , two external USB port and some periphery. I wanted to check the noise on the power bus. And I saw only white noise. [![enter image description here](https://i.stack.imgur.com/tFYGt.png)](https://i.stack.imgur.com/tFYGt.png) But after I connect the USB cable, I see on ALL circuit this is an noise. [![enter image description here](https://i.stack.imgur.com/jovKX.png)](https://i.stack.imgur.com/jovKX.png) [![enter image description here](https://i.stack.imgur.com/ACYt7.png)](https://i.stack.imgur.com/ACYt7.png) Most likely it is common mode noise from fronts D+/D-, because if I connect only the VBUS and the GND noise disappears. How terrible is this noise? How can i get rid of this noise?
2018/06/26
[ "https://electronics.stackexchange.com/questions/381823", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/113405/" ]
This doesn't work because the current thru the touch sensor is small and the gain of the transistor isn't large enough to amplify it to what the relay needs. You haven't provided any specs on the relay, so I'll just make up numbers for sake of example. Let's say the relay needs 30 mA at 9 V to operate. You haven't provided a link to the datasheet of the transistor, so let's say it's guaranteed minimum gain is 50. That means the minimum base current to operate the relay would be (30 mA)/50 = 600 µA. It is quite unlikely that this touch sensor will let 600 µA pass. Let's work backwards to see what the resistance between the touch sensor terminals would need to be. Figure 700 mV for the B-E drop of the transistor. That leaves 8.3 V across the touch sensor. By Ohm's law, (8.3 V)/(600 µA) = 13.8 kΩ. That's low for ordinary skin, but could probably be achieved by wetting the skin with salt water first. However, beware of the current thru the body. If this touch sensor is passing current between different parts of the same finger, then you might only feel a tingle. If this touch sensor connects two fingers on opposite hands, then this would actually be quite dangerous. Nearly a milliamp flowing near the heart is a bad idea. In any case, the solution is more gain. A second transistor could be used. That would also allow a resistor in series with the touch sensor to guarantee the current thru the body would be limited. This is something your circuit is NOT doing now.
Another way to build this circuit is with a MOSFET. It can be used in these applications because it requires almost no current to switch on and off. The gate of a MOSFET is like a capacitor; when it charges it allows current to flow. When you place your finger across the contacts, the gate charges and allows current to flow. Select the MOSFET for the current you need. The downside of this circuit is humans have the ability to collect static charge and this is bad for the MOSFET's gate as they are susceptible to ESD. It's a fun circuit to build however. You can change this by adding [ESD diodes](https://electronics.stackexchange.com/questions/233566/why-not-put-a-resistor-on-fet-gate). Some MOSFETs are so sensitive, you only need to wave your hand next to them; you don't even need to touch the contact. ![schematic](https://i.stack.imgur.com/JY9zZ.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fJY9zZ.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
381,823
I designed a device on which there is a HUB, FT232 , two external USB port and some periphery. I wanted to check the noise on the power bus. And I saw only white noise. [![enter image description here](https://i.stack.imgur.com/tFYGt.png)](https://i.stack.imgur.com/tFYGt.png) But after I connect the USB cable, I see on ALL circuit this is an noise. [![enter image description here](https://i.stack.imgur.com/jovKX.png)](https://i.stack.imgur.com/jovKX.png) [![enter image description here](https://i.stack.imgur.com/ACYt7.png)](https://i.stack.imgur.com/ACYt7.png) Most likely it is common mode noise from fronts D+/D-, because if I connect only the VBUS and the GND noise disappears. How terrible is this noise? How can i get rid of this noise?
2018/06/26
[ "https://electronics.stackexchange.com/questions/381823", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/113405/" ]
This doesn't work because the current thru the touch sensor is small and the gain of the transistor isn't large enough to amplify it to what the relay needs. You haven't provided any specs on the relay, so I'll just make up numbers for sake of example. Let's say the relay needs 30 mA at 9 V to operate. You haven't provided a link to the datasheet of the transistor, so let's say it's guaranteed minimum gain is 50. That means the minimum base current to operate the relay would be (30 mA)/50 = 600 µA. It is quite unlikely that this touch sensor will let 600 µA pass. Let's work backwards to see what the resistance between the touch sensor terminals would need to be. Figure 700 mV for the B-E drop of the transistor. That leaves 8.3 V across the touch sensor. By Ohm's law, (8.3 V)/(600 µA) = 13.8 kΩ. That's low for ordinary skin, but could probably be achieved by wetting the skin with salt water first. However, beware of the current thru the body. If this touch sensor is passing current between different parts of the same finger, then you might only feel a tingle. If this touch sensor connects two fingers on opposite hands, then this would actually be quite dangerous. Nearly a milliamp flowing near the heart is a bad idea. In any case, the solution is more gain. A second transistor could be used. That would also allow a resistor in series with the touch sensor to guarantee the current thru the body would be limited. This is something your circuit is NOT doing now.
Tray to use a darlington transistor and you got a good result [![enter image description here](https://i.stack.imgur.com/XWfnG.png)](https://i.stack.imgur.com/XWfnG.png) Because the B (amplification) is the product of the two transistor: B1 X B2 =B if B1=b2=100 you got B=10000 and tray to use a small relay of 6v (low current consumption)
381,823
I designed a device on which there is a HUB, FT232 , two external USB port and some periphery. I wanted to check the noise on the power bus. And I saw only white noise. [![enter image description here](https://i.stack.imgur.com/tFYGt.png)](https://i.stack.imgur.com/tFYGt.png) But after I connect the USB cable, I see on ALL circuit this is an noise. [![enter image description here](https://i.stack.imgur.com/jovKX.png)](https://i.stack.imgur.com/jovKX.png) [![enter image description here](https://i.stack.imgur.com/ACYt7.png)](https://i.stack.imgur.com/ACYt7.png) Most likely it is common mode noise from fronts D+/D-, because if I connect only the VBUS and the GND noise disappears. How terrible is this noise? How can i get rid of this noise?
2018/06/26
[ "https://electronics.stackexchange.com/questions/381823", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/113405/" ]
Another way to build this circuit is with a MOSFET. It can be used in these applications because it requires almost no current to switch on and off. The gate of a MOSFET is like a capacitor; when it charges it allows current to flow. When you place your finger across the contacts, the gate charges and allows current to flow. Select the MOSFET for the current you need. The downside of this circuit is humans have the ability to collect static charge and this is bad for the MOSFET's gate as they are susceptible to ESD. It's a fun circuit to build however. You can change this by adding [ESD diodes](https://electronics.stackexchange.com/questions/233566/why-not-put-a-resistor-on-fet-gate). Some MOSFETs are so sensitive, you only need to wave your hand next to them; you don't even need to touch the contact. ![schematic](https://i.stack.imgur.com/JY9zZ.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fJY9zZ.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Tray to use a darlington transistor and you got a good result [![enter image description here](https://i.stack.imgur.com/XWfnG.png)](https://i.stack.imgur.com/XWfnG.png) Because the B (amplification) is the product of the two transistor: B1 X B2 =B if B1=b2=100 you got B=10000 and tray to use a small relay of 6v (low current consumption)
57,277,248
I have a function: ``` public static async Task DoSomthing(string str1, int num1, bool bool1) { //Do something.... (This function will not return any value) } ``` I want to overload this function so it can be called with other arguments, but this function will basically call the function above. Now I have 2 choices and I don't know what is the better one (in every aspect from performance to good coding)? Option 1: ``` public static Task DoSomething(CustomObject obj) { return DoSomthing(obj.str, obj.num1, obj.bool1); } ``` Option 2: ``` public static async Task DoSomething(CustomObject obj) { await DoSomthing(obj.str, obj.num1, obj.bool1); } ```
2019/07/30
[ "https://Stackoverflow.com/questions/57277248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2760983/" ]
It will be executed almost in the same way but for the one with await it will add some overhead because the compiler will create a state machine. Compiler creates state machine for methods with async-await keywords so when the control flow reaches `await` it is returned to the calling method. The execution of async method continues when the awaited `Task` (or method that returns `Task`) has finished execution. As there is no code after `await` it is somewhat inadvisable to use `await` in this scenario. You could simply return a `Task`.
You can do option 1 because you only want to return the task witch it's passing. Personally I prefer to read in the Taskname Async like DoSomthingAsync you you always know what's async and what's sync ``` public static Task DoSomethingAsync(CustomObject obj) // or set the ConfigureAwait to true when you need stuff done on the same thread. => DoSomthingAsync(obj.str, obj.num1, obj.bool1).ConfigureAwait(false); ```
13,599,638
Probably a silly question, but in python is there a simple way to automatically pad a number with zeros to a fixed length? I wasn't able to find this in the python docs, but I may not have been looking hard enough? e.i. I want bin(4) to return 00100, rather than just 100. Is there a simple way to ensure the output will be six bits instead of three?
2012/11/28
[ "https://Stackoverflow.com/questions/13599638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1287834/" ]
Strings have a `.zfill()` method to pad it with zeros: ``` >>> '100'.zfill(5) '00100' ``` For binary numbers however, I'd use string formatting: ``` >>> '{0:05b}'.format(4) '00100' ``` The `:05b` formatting specification formats the number passed in as binary, with 5 digits, zero padded. See the [Python format string syntax](http://docs.python.org/2/library/string.html#format-string-syntax). I've used [`str.format()`](http://docs.python.org/2/library/stdtypes.html#str.format) here, but the [built-in `format()` function](http://docs.python.org/2/library/functions.html#format) can take the same formatting instruction, minus the `{0:..}` placeholder syntax: ``` >>> format(4, '05b') '00100' ``` if you find that easier.
try this... ``` In [11]: x = 1 In [12]: print str(x).zfill(5) 00001 In [13]: bin(4) Out[13]: '0b100' In [14]: str(bin(4)[2:]).zfill(5) Out[14]: '00100' ```
13,599,638
Probably a silly question, but in python is there a simple way to automatically pad a number with zeros to a fixed length? I wasn't able to find this in the python docs, but I may not have been looking hard enough? e.i. I want bin(4) to return 00100, rather than just 100. Is there a simple way to ensure the output will be six bits instead of three?
2012/11/28
[ "https://Stackoverflow.com/questions/13599638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1287834/" ]
Strings have a `.zfill()` method to pad it with zeros: ``` >>> '100'.zfill(5) '00100' ``` For binary numbers however, I'd use string formatting: ``` >>> '{0:05b}'.format(4) '00100' ``` The `:05b` formatting specification formats the number passed in as binary, with 5 digits, zero padded. See the [Python format string syntax](http://docs.python.org/2/library/string.html#format-string-syntax). I've used [`str.format()`](http://docs.python.org/2/library/stdtypes.html#str.format) here, but the [built-in `format()` function](http://docs.python.org/2/library/functions.html#format) can take the same formatting instruction, minus the `{0:..}` placeholder syntax: ``` >>> format(4, '05b') '00100' ``` if you find that easier.
This is a job for the [*format*](http://docs.python.org/2.7/library/functions.html#format) built-in function: ``` >>> format(4, '05b') '00100' ```
8,292,313
I'm trying to convert this C code to C#, is there a C# equivalent to the C union typedef? ``` struct sockaddr_in { short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; typedef struct in_addr { union { struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b; struct { u_short s_w1,s_w2; } S_un_w; u_long S_addr; } S_un; } IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR; ``` Thanks.
2011/11/28
[ "https://Stackoverflow.com/questions/8292313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1068804/" ]
You may check out the [following page](http://pinvoke.net/default.aspx/Structures/SOCKADDR.html). This being said, in .NET you have classes that allows you to work directly with sockets and TCP/IP such as Socket, TcpListener, TcpClient and you don't need to translate C code blindly.
Whilst the others definitely have a point - this is likely something you *really* don't need to do - there **is** a way to simulate unions in C# using [StructLayoutAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx) (example of simulating a union [here](http://msdn.microsoft.com/en-us/library/aa288471%28v=vs.71%29.aspx)). But don't do it. The purpose of this C union seems to be to permit bit twiddling parts of a 4 byte long. Using a union in this way depends on byte order knowledge of the target architecture, something that C# cannot guarantee. In C# - or any other language where portability is a concern - if you want to get or set the high byte/low byte/etc you need to use explicit bit shifting as explained [here](https://stackoverflow.com/questions/1436190/c-sharp-get-and-set-the-high-order-word-of-an-integer). But then don't do that either. Do like others have said and don't port this code. Someone's already done it for you, most likely Microsoft in the built in libraries ;).
56,662
I purchased my house (3 bedrooms, 2 full baths) in 1997 for $84,500. I have already made $166,500 of mortgage payments on a 9% interest rate loan. I have $53,000 left in payments. It recently appraised for approx. $71,000. I have made two unsuccessful attempts to refinance (but that’s a different story). I am looking at purchasing about 3 acres of property on which there is a similar house in well-developed area. I have about $100,000 cash in personal savings and $10,000 in my daughter’s account (she is 6 years old). Besides the mortgage, my biggest debt is a $31,200 car loan (2014 Infinity Q50) on which there is zero interest (actually, there was interest but, it has been paid in full in the amount of $600. My credit rating is “Excellent”). Should I pay off my house?
2015/12/04
[ "https://money.stackexchange.com/questions/56662", "https://money.stackexchange.com", "https://money.stackexchange.com/users/35490/" ]
If it were me, I'd be debt free today, Monday, at latest. 100K-(53K+31.2K) = 15.8K would be my bank balance by this afternoon. I am not sure why you would count 6K of your daughter's money as yours to use. Either it is her money, or yours, not both. If you still want debt, which I think is silly, you might try to refi your home with a home equity loan. That loan would be in first position, at a fixed rate, and for a fixed term. Regions bank did some thing like this for a person with excellent credit and plenty of equity. They got a 7 year loan at 2.6% when the prevailing interest rate on a 15 year was about a point higher.
9% would be an absurdly high rate in the US by today's standards, so you should at the very least consider refinancing to fix that. Paying off completely is of course another way to fix that. Which approach makes more sense depends on what you plan to do with the money instead if you do refinance -- if you can put it in an investment which yieds a higher percentage than the loan costs you, than refinancing the mortgage could actually be a profitable decision. You also need to consider what the bank will want to see in order to give you a mortgage on the new property. I have no idea whether they'd be happier that you had no prior mortgage, that you had the mortgage but also had the cash to pay it off, or if they wouldn't care. Remember that you want to be able to make at least a 20% down payment on the new property to avoid the insurance fees. That requires that you have a reasonable amount of cash-equivalent on hand. And generally, "house rich but cash poor" is an awkward state to be in.
56,662
I purchased my house (3 bedrooms, 2 full baths) in 1997 for $84,500. I have already made $166,500 of mortgage payments on a 9% interest rate loan. I have $53,000 left in payments. It recently appraised for approx. $71,000. I have made two unsuccessful attempts to refinance (but that’s a different story). I am looking at purchasing about 3 acres of property on which there is a similar house in well-developed area. I have about $100,000 cash in personal savings and $10,000 in my daughter’s account (she is 6 years old). Besides the mortgage, my biggest debt is a $31,200 car loan (2014 Infinity Q50) on which there is zero interest (actually, there was interest but, it has been paid in full in the amount of $600. My credit rating is “Excellent”). Should I pay off my house?
2015/12/04
[ "https://money.stackexchange.com/questions/56662", "https://money.stackexchange.com", "https://money.stackexchange.com/users/35490/" ]
If it were me, I'd be debt free today, Monday, at latest. 100K-(53K+31.2K) = 15.8K would be my bank balance by this afternoon. I am not sure why you would count 6K of your daughter's money as yours to use. Either it is her money, or yours, not both. If you still want debt, which I think is silly, you might try to refi your home with a home equity loan. That loan would be in first position, at a fixed rate, and for a fixed term. Regions bank did some thing like this for a person with excellent credit and plenty of equity. They got a 7 year loan at 2.6% when the prevailing interest rate on a 15 year was about a point higher.
If you get a mortgage on the new property, you can almost surely get better than 9% today. I refinanced my house a year or so ago at 4%. You didn't say how much the new house will cost or how much of your cash you're willing to put to it, but just to make up a number say the house costs $200,000 and you'll pay $100,000 with cash. So you could keep the $50,000 at 9% and get a new $100,000 at 4%, or you could pay off the old loan so you have $0 at 9% and $150,000 at 4%. Clearly plan B is significantly less interest -- 5% x $50,000 = $2,500 per year. If you can afford to buy the new house without getting a loan at all, it gets more complicated. By not getting a loan, you avoid closing costs, typically several thousand dollars. Would the amount you save on closing costs be more than the difference in interest? I think probably not, but I'd check into it. If paying off the old loan means that your down payment on the new place is now low enough that you have to pay mortgage insurance, you'd have to factor that in. I can't say without knowing the numbers, but I'd guess PMI would be less than the interest savings, but maybe not. Oh, I assume that you're planning to keep the old house. If you sell it, this whole question becomes a moot point, as most mortgages have a due-on-sale clause.
56,662
I purchased my house (3 bedrooms, 2 full baths) in 1997 for $84,500. I have already made $166,500 of mortgage payments on a 9% interest rate loan. I have $53,000 left in payments. It recently appraised for approx. $71,000. I have made two unsuccessful attempts to refinance (but that’s a different story). I am looking at purchasing about 3 acres of property on which there is a similar house in well-developed area. I have about $100,000 cash in personal savings and $10,000 in my daughter’s account (she is 6 years old). Besides the mortgage, my biggest debt is a $31,200 car loan (2014 Infinity Q50) on which there is zero interest (actually, there was interest but, it has been paid in full in the amount of $600. My credit rating is “Excellent”). Should I pay off my house?
2015/12/04
[ "https://money.stackexchange.com/questions/56662", "https://money.stackexchange.com", "https://money.stackexchange.com/users/35490/" ]
If it were me, I'd be debt free today, Monday, at latest. 100K-(53K+31.2K) = 15.8K would be my bank balance by this afternoon. I am not sure why you would count 6K of your daughter's money as yours to use. Either it is her money, or yours, not both. If you still want debt, which I think is silly, you might try to refi your home with a home equity loan. That loan would be in first position, at a fixed rate, and for a fixed term. Regions bank did some thing like this for a person with excellent credit and plenty of equity. They got a 7 year loan at 2.6% when the prevailing interest rate on a 15 year was about a point higher.
You owe only $38,860 to pay off your loan now, possibly less. From what you say about your loan, tell me if I got this right: `30 year loan $75,780 original loan amount 9% annual interest rate $609.74 monthly payment You have made 272 payments Payment number 273 is not due until late 2019, possibly early 2020` If I have correctly figured out what you have done, you have been making monthly payments early by pulling out payment coupons before they are due and sending them in with payment. You are about 4 years ahead on your payments. If I have this correct, if you called the bank and asked "what is my payoff amount if I want to pay this loan off tomorrow" they would answer something like $38,860. When you pay a loan off early, you don't just owe the sum of the coupons still remaining. In your case, you owe at least $16,000 less! Indeed, if there is some way to convert your 4 years of pre-payments into an early payment, you would owe even less than $38,860. I don't know banking law well enough to know if that is possible. You should stop pulling coupons out of your book and paying them early. Any payments you make between now and when your next payment is actually due (late 2019 sometime?) you should tell the bank you want applied as an early payment. This will bring your total owed amount down much faster than pulling coupons out of your book and making payments years early. If there is someone in your family who understands banking pretty well, maybe they can help you sort this out. I don't know who to refer you to for more personal help, but I really do think you have more than $16,000 to gain by changing how you are paying your mortgage. Good luck!
56,662
I purchased my house (3 bedrooms, 2 full baths) in 1997 for $84,500. I have already made $166,500 of mortgage payments on a 9% interest rate loan. I have $53,000 left in payments. It recently appraised for approx. $71,000. I have made two unsuccessful attempts to refinance (but that’s a different story). I am looking at purchasing about 3 acres of property on which there is a similar house in well-developed area. I have about $100,000 cash in personal savings and $10,000 in my daughter’s account (she is 6 years old). Besides the mortgage, my biggest debt is a $31,200 car loan (2014 Infinity Q50) on which there is zero interest (actually, there was interest but, it has been paid in full in the amount of $600. My credit rating is “Excellent”). Should I pay off my house?
2015/12/04
[ "https://money.stackexchange.com/questions/56662", "https://money.stackexchange.com", "https://money.stackexchange.com/users/35490/" ]
9% would be an absurdly high rate in the US by today's standards, so you should at the very least consider refinancing to fix that. Paying off completely is of course another way to fix that. Which approach makes more sense depends on what you plan to do with the money instead if you do refinance -- if you can put it in an investment which yieds a higher percentage than the loan costs you, than refinancing the mortgage could actually be a profitable decision. You also need to consider what the bank will want to see in order to give you a mortgage on the new property. I have no idea whether they'd be happier that you had no prior mortgage, that you had the mortgage but also had the cash to pay it off, or if they wouldn't care. Remember that you want to be able to make at least a 20% down payment on the new property to avoid the insurance fees. That requires that you have a reasonable amount of cash-equivalent on hand. And generally, "house rich but cash poor" is an awkward state to be in.
You owe only $38,860 to pay off your loan now, possibly less. From what you say about your loan, tell me if I got this right: `30 year loan $75,780 original loan amount 9% annual interest rate $609.74 monthly payment You have made 272 payments Payment number 273 is not due until late 2019, possibly early 2020` If I have correctly figured out what you have done, you have been making monthly payments early by pulling out payment coupons before they are due and sending them in with payment. You are about 4 years ahead on your payments. If I have this correct, if you called the bank and asked "what is my payoff amount if I want to pay this loan off tomorrow" they would answer something like $38,860. When you pay a loan off early, you don't just owe the sum of the coupons still remaining. In your case, you owe at least $16,000 less! Indeed, if there is some way to convert your 4 years of pre-payments into an early payment, you would owe even less than $38,860. I don't know banking law well enough to know if that is possible. You should stop pulling coupons out of your book and paying them early. Any payments you make between now and when your next payment is actually due (late 2019 sometime?) you should tell the bank you want applied as an early payment. This will bring your total owed amount down much faster than pulling coupons out of your book and making payments years early. If there is someone in your family who understands banking pretty well, maybe they can help you sort this out. I don't know who to refer you to for more personal help, but I really do think you have more than $16,000 to gain by changing how you are paying your mortgage. Good luck!
56,662
I purchased my house (3 bedrooms, 2 full baths) in 1997 for $84,500. I have already made $166,500 of mortgage payments on a 9% interest rate loan. I have $53,000 left in payments. It recently appraised for approx. $71,000. I have made two unsuccessful attempts to refinance (but that’s a different story). I am looking at purchasing about 3 acres of property on which there is a similar house in well-developed area. I have about $100,000 cash in personal savings and $10,000 in my daughter’s account (she is 6 years old). Besides the mortgage, my biggest debt is a $31,200 car loan (2014 Infinity Q50) on which there is zero interest (actually, there was interest but, it has been paid in full in the amount of $600. My credit rating is “Excellent”). Should I pay off my house?
2015/12/04
[ "https://money.stackexchange.com/questions/56662", "https://money.stackexchange.com", "https://money.stackexchange.com/users/35490/" ]
If you get a mortgage on the new property, you can almost surely get better than 9% today. I refinanced my house a year or so ago at 4%. You didn't say how much the new house will cost or how much of your cash you're willing to put to it, but just to make up a number say the house costs $200,000 and you'll pay $100,000 with cash. So you could keep the $50,000 at 9% and get a new $100,000 at 4%, or you could pay off the old loan so you have $0 at 9% and $150,000 at 4%. Clearly plan B is significantly less interest -- 5% x $50,000 = $2,500 per year. If you can afford to buy the new house without getting a loan at all, it gets more complicated. By not getting a loan, you avoid closing costs, typically several thousand dollars. Would the amount you save on closing costs be more than the difference in interest? I think probably not, but I'd check into it. If paying off the old loan means that your down payment on the new place is now low enough that you have to pay mortgage insurance, you'd have to factor that in. I can't say without knowing the numbers, but I'd guess PMI would be less than the interest savings, but maybe not. Oh, I assume that you're planning to keep the old house. If you sell it, this whole question becomes a moot point, as most mortgages have a due-on-sale clause.
You owe only $38,860 to pay off your loan now, possibly less. From what you say about your loan, tell me if I got this right: `30 year loan $75,780 original loan amount 9% annual interest rate $609.74 monthly payment You have made 272 payments Payment number 273 is not due until late 2019, possibly early 2020` If I have correctly figured out what you have done, you have been making monthly payments early by pulling out payment coupons before they are due and sending them in with payment. You are about 4 years ahead on your payments. If I have this correct, if you called the bank and asked "what is my payoff amount if I want to pay this loan off tomorrow" they would answer something like $38,860. When you pay a loan off early, you don't just owe the sum of the coupons still remaining. In your case, you owe at least $16,000 less! Indeed, if there is some way to convert your 4 years of pre-payments into an early payment, you would owe even less than $38,860. I don't know banking law well enough to know if that is possible. You should stop pulling coupons out of your book and paying them early. Any payments you make between now and when your next payment is actually due (late 2019 sometime?) you should tell the bank you want applied as an early payment. This will bring your total owed amount down much faster than pulling coupons out of your book and making payments years early. If there is someone in your family who understands banking pretty well, maybe they can help you sort this out. I don't know who to refer you to for more personal help, but I really do think you have more than $16,000 to gain by changing how you are paying your mortgage. Good luck!
64,880,156
I have a situation where I have a paragraph, which needs to have a select box right in the middle of it. However, `v-select` is a bit too big and doesn't seem to allow you to control its width. This is currently what it looks like: ```js new Vue({ el: '#root', vuetify: new Vuetify(), template: ` <div style="{ margin: '20px' }"> <v-row> <v-col col="12"> <p>I would like to have the following select: <v-select placeholder="0"/> shrunk and displayed with this text all in line. How can I do that?</p> </v-col> </v-row> </div> ` }) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"> <div id="root"></div> ``` Based on the [API docs](https://vuetifyjs.com/en/api/v-select/#props), there doesn't seem to be an easy way to control for its size. What is the proper way of getting this done?
2020/11/17
[ "https://Stackoverflow.com/questions/64880156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1676032/" ]
You will have to override the Vuetify css with your own styles. A good way to do this is to create some kind of override class for your UI or for specific things you need to have higher in the cascade. Then you can call the Vuetify classes inside that class and most of the time it will make your styles fire last. If that still fails, you can resort to adding `!important` after the style that isn't picking up. ```js new Vue({ el: '#root', vuetify: new Vuetify(), template: ` <div class="override-class" style="{ margin: '20px' }"> <v-row> <v-col col="12"> <p>I would like to have the following select: <v-select placeholder="0"/> shrunk and displayed with this text all in line. How can I do that?</p> </v-col> </v-row> </div> ` }) ``` ```css .override-class .v-input { display: inline-block; width: 100px; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"> <div id="root"></div> ```
You could apply an inline CSS style `style="width:64px;display:inline-flex"` ```js new Vue({ el: '#root', vuetify: new Vuetify(), template: ` <div style="{ margin: '20px' }"> <v-row> <v-col col="12"> <p>I would like to have the following select: <v-select style="width:64px" placeholder="0"/> shrunk and displayed with this text all in line. How can I do that?</p> </v-col> </v-row> </div> ` }) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"> <div id="root"></div> ```
37,784,030
I want to get month value using week no. I have week numbers stored in a table with year value. [![enter image description here](https://i.stack.imgur.com/eMh1L.png)](https://i.stack.imgur.com/eMh1L.png) How to query database to get month value using that week value. I am using SQL
2016/06/13
[ "https://Stackoverflow.com/questions/37784030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681855/" ]
You can try this: ``` SELECT DATEPART(m,DATEADD(wk, DATEDIFF(wk, 6, '1/1/' + CAST(t.year as VARCHAR(4))) + (t.week-1), 6)) ```
It depends on how you're classing your week numbers, For example, if we assume that week numbers start on a Monday then we'd have to say that week 1 in 2016 actually started on Monday 28th of December 2015 and finished on Sunday 3rd January 2016. If this is how your week numbers are set up then you can use the method below Sample Data; ``` CREATE TABLE #DateTable (WeekNum int, YearNum int) INSERT INTO #DateTable (WeekNum, YearNum) VALUES (1,2016) ,(2,2016) ,(3,2016) ,(4,2016) ,(5,2016) ,(6,2016) ,(7,2016) ``` We will then cast the week and year into a date, then convert this to a month; ``` SELECT WeekNum ,YearNum ,DATEADD(wk, DATEDIFF(wk, 7, '1/1/' + CONVERT(varchar(4),YearNum)) + (WeekNum-1), 7) AS WeekStart ,DATEPART(mm,DATEADD(wk, DATEDIFF(wk, 7, '1/1/' + CONVERT(varchar(4),YearNum)) + (WeekNum-1), 7)) MonthNum ``` (Edit: updated as source is int) Gives these results; ``` WeekNum YearNum WeekStart MonthNum 1 2016 2015-12-28 00:00:00.000 12 2 2016 2016-01-04 00:00:00.000 1 3 2016 2016-01-11 00:00:00.000 1 4 2016 2016-01-18 00:00:00.000 1 5 2016 2016-01-25 00:00:00.000 1 6 2016 2016-02-01 00:00:00.000 2 7 2016 2016-02-08 00:00:00.000 2 ```
37,784,030
I want to get month value using week no. I have week numbers stored in a table with year value. [![enter image description here](https://i.stack.imgur.com/eMh1L.png)](https://i.stack.imgur.com/eMh1L.png) How to query database to get month value using that week value. I am using SQL
2016/06/13
[ "https://Stackoverflow.com/questions/37784030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681855/" ]
You can try this: ``` SELECT DATEPART(m,DATEADD(wk, DATEDIFF(wk, 6, '1/1/' + CAST(t.year as VARCHAR(4))) + (t.week-1), 6)) ```
You can try the query below: ``` SELECT [Week], [Year], 'Output-Month' = MONTH(DATEADD(WEEK, [Week], DATEADD(WEEK, DATEDIFF(WEEK, '19050101', '01/01/' + CAST([Year] AS VARCHAR(4))), '19050101'))) FROM YourTable ``` 1st is to get the 1st day of the year using this: ``` DATEADD(WEEK, DATEDIFF(WEEK, '19050101', '01/01/' + CAST([Year] AS VARCHAR(4))), '19050101') ``` 2nd is to add your number of week using this: ``` DATEADD(WEEK, [Week], 'From 1st result') ``` Last is getting the number of Month using the MONTH function.
37,784,030
I want to get month value using week no. I have week numbers stored in a table with year value. [![enter image description here](https://i.stack.imgur.com/eMh1L.png)](https://i.stack.imgur.com/eMh1L.png) How to query database to get month value using that week value. I am using SQL
2016/06/13
[ "https://Stackoverflow.com/questions/37784030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681855/" ]
You can try this: ``` SELECT DATEPART(m,DATEADD(wk, DATEDIFF(wk, 6, '1/1/' + CAST(t.year as VARCHAR(4))) + (t.week-1), 6)) ```
You can't go from week number to month because weeks can occur in two different months. For example the 31st Jan 2016 and 1st Feb 2016 are both in week 6. ``` SELECT DATEPART(WEEK, '2016-01-31') SELECT DATEPART(WEEK, '2016-02-01') ```
37,784,030
I want to get month value using week no. I have week numbers stored in a table with year value. [![enter image description here](https://i.stack.imgur.com/eMh1L.png)](https://i.stack.imgur.com/eMh1L.png) How to query database to get month value using that week value. I am using SQL
2016/06/13
[ "https://Stackoverflow.com/questions/37784030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681855/" ]
It depends on how you're classing your week numbers, For example, if we assume that week numbers start on a Monday then we'd have to say that week 1 in 2016 actually started on Monday 28th of December 2015 and finished on Sunday 3rd January 2016. If this is how your week numbers are set up then you can use the method below Sample Data; ``` CREATE TABLE #DateTable (WeekNum int, YearNum int) INSERT INTO #DateTable (WeekNum, YearNum) VALUES (1,2016) ,(2,2016) ,(3,2016) ,(4,2016) ,(5,2016) ,(6,2016) ,(7,2016) ``` We will then cast the week and year into a date, then convert this to a month; ``` SELECT WeekNum ,YearNum ,DATEADD(wk, DATEDIFF(wk, 7, '1/1/' + CONVERT(varchar(4),YearNum)) + (WeekNum-1), 7) AS WeekStart ,DATEPART(mm,DATEADD(wk, DATEDIFF(wk, 7, '1/1/' + CONVERT(varchar(4),YearNum)) + (WeekNum-1), 7)) MonthNum ``` (Edit: updated as source is int) Gives these results; ``` WeekNum YearNum WeekStart MonthNum 1 2016 2015-12-28 00:00:00.000 12 2 2016 2016-01-04 00:00:00.000 1 3 2016 2016-01-11 00:00:00.000 1 4 2016 2016-01-18 00:00:00.000 1 5 2016 2016-01-25 00:00:00.000 1 6 2016 2016-02-01 00:00:00.000 2 7 2016 2016-02-08 00:00:00.000 2 ```
You can try the query below: ``` SELECT [Week], [Year], 'Output-Month' = MONTH(DATEADD(WEEK, [Week], DATEADD(WEEK, DATEDIFF(WEEK, '19050101', '01/01/' + CAST([Year] AS VARCHAR(4))), '19050101'))) FROM YourTable ``` 1st is to get the 1st day of the year using this: ``` DATEADD(WEEK, DATEDIFF(WEEK, '19050101', '01/01/' + CAST([Year] AS VARCHAR(4))), '19050101') ``` 2nd is to add your number of week using this: ``` DATEADD(WEEK, [Week], 'From 1st result') ``` Last is getting the number of Month using the MONTH function.
37,784,030
I want to get month value using week no. I have week numbers stored in a table with year value. [![enter image description here](https://i.stack.imgur.com/eMh1L.png)](https://i.stack.imgur.com/eMh1L.png) How to query database to get month value using that week value. I am using SQL
2016/06/13
[ "https://Stackoverflow.com/questions/37784030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681855/" ]
It depends on how you're classing your week numbers, For example, if we assume that week numbers start on a Monday then we'd have to say that week 1 in 2016 actually started on Monday 28th of December 2015 and finished on Sunday 3rd January 2016. If this is how your week numbers are set up then you can use the method below Sample Data; ``` CREATE TABLE #DateTable (WeekNum int, YearNum int) INSERT INTO #DateTable (WeekNum, YearNum) VALUES (1,2016) ,(2,2016) ,(3,2016) ,(4,2016) ,(5,2016) ,(6,2016) ,(7,2016) ``` We will then cast the week and year into a date, then convert this to a month; ``` SELECT WeekNum ,YearNum ,DATEADD(wk, DATEDIFF(wk, 7, '1/1/' + CONVERT(varchar(4),YearNum)) + (WeekNum-1), 7) AS WeekStart ,DATEPART(mm,DATEADD(wk, DATEDIFF(wk, 7, '1/1/' + CONVERT(varchar(4),YearNum)) + (WeekNum-1), 7)) MonthNum ``` (Edit: updated as source is int) Gives these results; ``` WeekNum YearNum WeekStart MonthNum 1 2016 2015-12-28 00:00:00.000 12 2 2016 2016-01-04 00:00:00.000 1 3 2016 2016-01-11 00:00:00.000 1 4 2016 2016-01-18 00:00:00.000 1 5 2016 2016-01-25 00:00:00.000 1 6 2016 2016-02-01 00:00:00.000 2 7 2016 2016-02-08 00:00:00.000 2 ```
You can't go from week number to month because weeks can occur in two different months. For example the 31st Jan 2016 and 1st Feb 2016 are both in week 6. ``` SELECT DATEPART(WEEK, '2016-01-31') SELECT DATEPART(WEEK, '2016-02-01') ```
12,621,431
I wrote a small test page to grab `document.referrer` of users with javascript and send it to a simple log server (like `sendReferrer(document.referrer)`). The referrer Firefox sends is always url-encoded, (eg. 'http://www.google.com/search?q=%C3%9C' when referrer url is www.google.com/search?q=Ü) But some clients (like IE9 on Win7) sends urls without url-encoding (www.google.com/search?q=Ü) Is `document.referrer` is url-encoded in all browsers? Is this reliable (part of any standard) or not? **UPDATE:** In Firefox15/Chrome21 (on ubuntu) document.referrer is url-encoded
2012/09/27
[ "https://Stackoverflow.com/questions/12621431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326792/" ]
document.referrer isn't URL encoded I have recently tested it in all major browsers and it showed to be non encoded in every one of them.
My final answer for this question: `Referer` may/may not be encoded! With my tests some (only some!) IEs send unencoded referrers (I guess it depends on the locale of client system)
35,593,994
I have an array : ``` e = np.array([[ 0, 1, 2, 3, 5, 6, 7, 8], [ 4, 5, 6, 7, 5, 3, 2, 5], [ 8, 9, 10, 11, 4, 5, 3, 5]]) ``` I want to extract array by its columns in RANGE, if I want to take column in range 1 until 5, It will return ``` e = np.array([[ 1, 2, 3, 5, ], [ 5, 6, 7, 5, ], [ 9, 10, 11, 4, ]]) ``` How to solve it? Thanks
2016/02/24
[ "https://Stackoverflow.com/questions/35593994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4374970/" ]
You can just use e[:, 1:5] to retrive what you want. ``` In [1]: import numpy as np In [2]: e = np.array([[ 0, 1, 2, 3, 5, 6, 7, 8], ...: [ 4, 5, 6, 7, 5, 3, 2, 5], ...: [ 8, 9, 10, 11, 4, 5, 3, 5]]) In [3]: e[:, 1:5] Out[3]: array([[ 1, 2, 3, 5], [ 5, 6, 7, 5], [ 9, 10, 11, 4]]) ``` > > <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html> > > >
Numpy row and column indices start counting at 0. The rows are specified first and then the column with a comma to separate the row from column. The ":" (colon) is used to shortcut all rows or all columns when it is used alone. When the row or column specifier has a range, then the ":" is paired with numbers that specify the inclusive start range and the exclusive end range. For example ``` import numpy as np np_array = np.array( [ [ 1, 2, 3, ], [ 4, 5, 6, ], [ 7, 8, 9 ] ] ) first_row = np_array[0,:] first_row output: array([1, 2, 3]) last_column = np_array[:,2] last_column output: array([3, 6, 9]) first_two_vals = np_array[0,0:2] first_two_vals output: array([1, 2]) ```
35,593,994
I have an array : ``` e = np.array([[ 0, 1, 2, 3, 5, 6, 7, 8], [ 4, 5, 6, 7, 5, 3, 2, 5], [ 8, 9, 10, 11, 4, 5, 3, 5]]) ``` I want to extract array by its columns in RANGE, if I want to take column in range 1 until 5, It will return ``` e = np.array([[ 1, 2, 3, 5, ], [ 5, 6, 7, 5, ], [ 9, 10, 11, 4, ]]) ``` How to solve it? Thanks
2016/02/24
[ "https://Stackoverflow.com/questions/35593994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4374970/" ]
You can just use e[:, 1:5] to retrive what you want. ``` In [1]: import numpy as np In [2]: e = np.array([[ 0, 1, 2, 3, 5, 6, 7, 8], ...: [ 4, 5, 6, 7, 5, 3, 2, 5], ...: [ 8, 9, 10, 11, 4, 5, 3, 5]]) In [3]: e[:, 1:5] Out[3]: array([[ 1, 2, 3, 5], [ 5, 6, 7, 5], [ 9, 10, 11, 4]]) ``` > > <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html> > > >
You can use np.take with specifying axis=1 ``` import numpy as np e = np.array([[ 0, 1, 2, 3, 5, 6, 7, 8], [ 4, 5, 6, 7, 5, 3, 2, 5], [ 8, 9, 10, 11, 4, 5, 3, 5]]) e = np.take(e, [1,2,3,4], axis=1) output: array([[ 1, 2, 3, 5], [ 5, 6, 7, 5], [ 9, 10, 11, 4]]) ``` <https://numpy.org/doc/stable/reference/generated/numpy.take.html>
35,593,994
I have an array : ``` e = np.array([[ 0, 1, 2, 3, 5, 6, 7, 8], [ 4, 5, 6, 7, 5, 3, 2, 5], [ 8, 9, 10, 11, 4, 5, 3, 5]]) ``` I want to extract array by its columns in RANGE, if I want to take column in range 1 until 5, It will return ``` e = np.array([[ 1, 2, 3, 5, ], [ 5, 6, 7, 5, ], [ 9, 10, 11, 4, ]]) ``` How to solve it? Thanks
2016/02/24
[ "https://Stackoverflow.com/questions/35593994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4374970/" ]
Numpy row and column indices start counting at 0. The rows are specified first and then the column with a comma to separate the row from column. The ":" (colon) is used to shortcut all rows or all columns when it is used alone. When the row or column specifier has a range, then the ":" is paired with numbers that specify the inclusive start range and the exclusive end range. For example ``` import numpy as np np_array = np.array( [ [ 1, 2, 3, ], [ 4, 5, 6, ], [ 7, 8, 9 ] ] ) first_row = np_array[0,:] first_row output: array([1, 2, 3]) last_column = np_array[:,2] last_column output: array([3, 6, 9]) first_two_vals = np_array[0,0:2] first_two_vals output: array([1, 2]) ```
You can use np.take with specifying axis=1 ``` import numpy as np e = np.array([[ 0, 1, 2, 3, 5, 6, 7, 8], [ 4, 5, 6, 7, 5, 3, 2, 5], [ 8, 9, 10, 11, 4, 5, 3, 5]]) e = np.take(e, [1,2,3,4], axis=1) output: array([[ 1, 2, 3, 5], [ 5, 6, 7, 5], [ 9, 10, 11, 4]]) ``` <https://numpy.org/doc/stable/reference/generated/numpy.take.html>
1,414,325
I didn't see any difference with or without this head information yet.
2009/09/12
[ "https://Stackoverflow.com/questions/1414325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
PHP uses Content-Type `text/html` as default, which is pretty similar to `text/plain` and this explains why you don't see any differences. `text/plain` content-type is necessary if you want to output text as is (including `<` and `>` symbols). Examples: ``` header("Content-Type: text/plain"); echo "<b>hello world</b>"; // Displays in the browser: <b>hello world</b> header("Content-Type: text/html"); echo "<b>hello world</b>"; // Displays in the browser with bold font: hello world ```
Say you want to answer a request with a 204: No Content HTTP status. Firefox will complain with "no element found" in the console of the browser. This is a bug in Firefox that has been reported, but never fixed, for several years. By sending a "Content-type: text/plain" header, you can prevent this error in Firefox.
1,414,325
I didn't see any difference with or without this head information yet.
2009/09/12
[ "https://Stackoverflow.com/questions/1414325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
Define "necessary". It is necessary if you want the browser to ***know*** what the type of the file is. PHP automatically sets the `Content-Type` header to `text/html` if you don't override it so your browser is treating it as an HTML file that doesn't contain any HTML. If your output contained any HTML you'd see very different outcomes. If you were to send: ``` <b><i>test</i></b> ``` `Content-Type: text/html; charset=UTF-8` would display in the browser text in bold and italics: ***✅ OK*** whereas `Content-Type: text/plain; charset=UTF-8` would display in the browser like this: ``` <b><i>✅ OK</i></b> ``` **TLDR Version:** If you really are only outputing plain text with no special characters like `<` or `>` then it doesn't really matter, but it *IS* wrong.
Setting the Content-Type header will affect how a web browser treats your content. When most mainstream web browsers encounter a Content-Type of text/plain, they'll render the raw text source in the browser window (as opposed to the source rendered at HTML). It's the difference between seeing ``` <b>foo</b> ``` or > > **foo** > > > Additionally, when using the `XMLHttpRequest` object, your Content-Type header will affect how the browser serializes the returned results. Prior to the takeover of AJAX frameworks like jQuery and Prototype, a common problem with AJAX responses was a Content-Type set to text/html instead of text/xml. Similar problems would likely occur if the Content-Type was text/plain.
1,414,325
I didn't see any difference with or without this head information yet.
2009/09/12
[ "https://Stackoverflow.com/questions/1414325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
It is very important that you tell the browser what type of data you are sending it. The difference should be obvious. Try viewing the output of the following PHP file in your browser; ``` <?php header('Content-Type:text/html; charset=UTF-8'); ?> <p>Hello</p> ``` You will see: > > hello > > > (note that you will get the same results if you miss off the header line in this case - text/html is php's default) Change it to text/plain ``` <?php header('Content-Type:text/plain; charset=UTF-8'); ?> <p>Hello</p> ``` You will see: > > <p>Hello</p> > > > Why does this matter? If you have something like the following in a php script that, for example, is used by an ajax request: ``` <?php header('Content-Type:text/html; charset=UTF-8'); print "Your name is " . $_GET['name'] ``` Someone can put a link to a URL like <http://example.com/test.php?name=%3Cscript%20src=%22http://example.com/eviljs%22%3E%3C/script%3E> on their site, and if a user clicks it, they have exposed all their information on your site to whoever put up the link. If you serve the file as text/plain, you are safe. Note that this is a silly example, it's more likely that the bad script tag would be added by the attacker to a field in the database or by using a form submission.
no its not like that,here is Example for the support of my answer ---->the clear difference is visible ,when you go for HTTP Compression,which allows you to compress the data while travelling from Server to Client and the Type of this data automatically becomes as "gzip" which Tells browser that bowser got a **zipped data** and it has to **upzip** it,this is a example where Type really matters at Bowser.
1,414,325
I didn't see any difference with or without this head information yet.
2009/09/12
[ "https://Stackoverflow.com/questions/1414325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
Say you want to answer a request with a 204: No Content HTTP status. Firefox will complain with "no element found" in the console of the browser. This is a bug in Firefox that has been reported, but never fixed, for several years. By sending a "Content-type: text/plain" header, you can prevent this error in Firefox.
no its not like that,here is Example for the support of my answer ---->the clear difference is visible ,when you go for HTTP Compression,which allows you to compress the data while travelling from Server to Client and the Type of this data automatically becomes as "gzip" which Tells browser that bowser got a **zipped data** and it has to **upzip** it,this is a example where Type really matters at Bowser.
1,414,325
I didn't see any difference with or without this head information yet.
2009/09/12
[ "https://Stackoverflow.com/questions/1414325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
PHP uses Content-Type `text/html` as default, which is pretty similar to `text/plain` and this explains why you don't see any differences. `text/plain` content-type is necessary if you want to output text as is (including `<` and `>` symbols). Examples: ``` header("Content-Type: text/plain"); echo "<b>hello world</b>"; // Displays in the browser: <b>hello world</b> header("Content-Type: text/html"); echo "<b>hello world</b>"; // Displays in the browser with bold font: hello world ```
It is very important that you tell the browser what type of data you are sending it. The difference should be obvious. Try viewing the output of the following PHP file in your browser; ``` <?php header('Content-Type:text/html; charset=UTF-8'); ?> <p>Hello</p> ``` You will see: > > hello > > > (note that you will get the same results if you miss off the header line in this case - text/html is php's default) Change it to text/plain ``` <?php header('Content-Type:text/plain; charset=UTF-8'); ?> <p>Hello</p> ``` You will see: > > <p>Hello</p> > > > Why does this matter? If you have something like the following in a php script that, for example, is used by an ajax request: ``` <?php header('Content-Type:text/html; charset=UTF-8'); print "Your name is " . $_GET['name'] ``` Someone can put a link to a URL like <http://example.com/test.php?name=%3Cscript%20src=%22http://example.com/eviljs%22%3E%3C/script%3E> on their site, and if a user clicks it, they have exposed all their information on your site to whoever put up the link. If you serve the file as text/plain, you are safe. Note that this is a silly example, it's more likely that the bad script tag would be added by the attacker to a field in the database or by using a form submission.
1,414,325
I didn't see any difference with or without this head information yet.
2009/09/12
[ "https://Stackoverflow.com/questions/1414325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
Define "necessary". It is necessary if you want the browser to ***know*** what the type of the file is. PHP automatically sets the `Content-Type` header to `text/html` if you don't override it so your browser is treating it as an HTML file that doesn't contain any HTML. If your output contained any HTML you'd see very different outcomes. If you were to send: ``` <b><i>test</i></b> ``` `Content-Type: text/html; charset=UTF-8` would display in the browser text in bold and italics: ***✅ OK*** whereas `Content-Type: text/plain; charset=UTF-8` would display in the browser like this: ``` <b><i>✅ OK</i></b> ``` **TLDR Version:** If you really are only outputing plain text with no special characters like `<` or `>` then it doesn't really matter, but it *IS* wrong.
It is very important that you tell the browser what type of data you are sending it. The difference should be obvious. Try viewing the output of the following PHP file in your browser; ``` <?php header('Content-Type:text/html; charset=UTF-8'); ?> <p>Hello</p> ``` You will see: > > hello > > > (note that you will get the same results if you miss off the header line in this case - text/html is php's default) Change it to text/plain ``` <?php header('Content-Type:text/plain; charset=UTF-8'); ?> <p>Hello</p> ``` You will see: > > <p>Hello</p> > > > Why does this matter? If you have something like the following in a php script that, for example, is used by an ajax request: ``` <?php header('Content-Type:text/html; charset=UTF-8'); print "Your name is " . $_GET['name'] ``` Someone can put a link to a URL like <http://example.com/test.php?name=%3Cscript%20src=%22http://example.com/eviljs%22%3E%3C/script%3E> on their site, and if a user clicks it, they have exposed all their information on your site to whoever put up the link. If you serve the file as text/plain, you are safe. Note that this is a silly example, it's more likely that the bad script tag would be added by the attacker to a field in the database or by using a form submission.
1,414,325
I didn't see any difference with or without this head information yet.
2009/09/12
[ "https://Stackoverflow.com/questions/1414325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
Setting the Content-Type header will affect how a web browser treats your content. When most mainstream web browsers encounter a Content-Type of text/plain, they'll render the raw text source in the browser window (as opposed to the source rendered at HTML). It's the difference between seeing ``` <b>foo</b> ``` or > > **foo** > > > Additionally, when using the `XMLHttpRequest` object, your Content-Type header will affect how the browser serializes the returned results. Prior to the takeover of AJAX frameworks like jQuery and Prototype, a common problem with AJAX responses was a Content-Type set to text/html instead of text/xml. Similar problems would likely occur if the Content-Type was text/plain.
no its not like that,here is Example for the support of my answer ---->the clear difference is visible ,when you go for HTTP Compression,which allows you to compress the data while travelling from Server to Client and the Type of this data automatically becomes as "gzip" which Tells browser that bowser got a **zipped data** and it has to **upzip** it,this is a example where Type really matters at Bowser.
1,414,325
I didn't see any difference with or without this head information yet.
2009/09/12
[ "https://Stackoverflow.com/questions/1414325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
PHP uses Content-Type `text/html` as default, which is pretty similar to `text/plain` and this explains why you don't see any differences. `text/plain` content-type is necessary if you want to output text as is (including `<` and `>` symbols). Examples: ``` header("Content-Type: text/plain"); echo "<b>hello world</b>"; // Displays in the browser: <b>hello world</b> header("Content-Type: text/html"); echo "<b>hello world</b>"; // Displays in the browser with bold font: hello world ```
no its not like that,here is Example for the support of my answer ---->the clear difference is visible ,when you go for HTTP Compression,which allows you to compress the data while travelling from Server to Client and the Type of this data automatically becomes as "gzip" which Tells browser that bowser got a **zipped data** and it has to **upzip** it,this is a example where Type really matters at Bowser.
1,414,325
I didn't see any difference with or without this head information yet.
2009/09/12
[ "https://Stackoverflow.com/questions/1414325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
PHP uses Content-Type `text/html` as default, which is pretty similar to `text/plain` and this explains why you don't see any differences. `text/plain` content-type is necessary if you want to output text as is (including `<` and `>` symbols). Examples: ``` header("Content-Type: text/plain"); echo "<b>hello world</b>"; // Displays in the browser: <b>hello world</b> header("Content-Type: text/html"); echo "<b>hello world</b>"; // Displays in the browser with bold font: hello world ```
Setting the Content-Type header will affect how a web browser treats your content. When most mainstream web browsers encounter a Content-Type of text/plain, they'll render the raw text source in the browser window (as opposed to the source rendered at HTML). It's the difference between seeing ``` <b>foo</b> ``` or > > **foo** > > > Additionally, when using the `XMLHttpRequest` object, your Content-Type header will affect how the browser serializes the returned results. Prior to the takeover of AJAX frameworks like jQuery and Prototype, a common problem with AJAX responses was a Content-Type set to text/html instead of text/xml. Similar problems would likely occur if the Content-Type was text/plain.
1,414,325
I didn't see any difference with or without this head information yet.
2009/09/12
[ "https://Stackoverflow.com/questions/1414325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104015/" ]
Setting the Content-Type header will affect how a web browser treats your content. When most mainstream web browsers encounter a Content-Type of text/plain, they'll render the raw text source in the browser window (as opposed to the source rendered at HTML). It's the difference between seeing ``` <b>foo</b> ``` or > > **foo** > > > Additionally, when using the `XMLHttpRequest` object, your Content-Type header will affect how the browser serializes the returned results. Prior to the takeover of AJAX frameworks like jQuery and Prototype, a common problem with AJAX responses was a Content-Type set to text/html instead of text/xml. Similar problems would likely occur if the Content-Type was text/plain.
Say you want to answer a request with a 204: No Content HTTP status. Firefox will complain with "no element found" in the console of the browser. This is a bug in Firefox that has been reported, but never fixed, for several years. By sending a "Content-type: text/plain" header, you can prevent this error in Firefox.
71,047,996
So I recently wrote an algorithm which I posted on stack exchange/code review and it was very well received and I got loads of improvements suggested. I'm new to C# and I don't really understand the IEnumerable interface. How do I print to the console my entire deck? The code below is a method, if I call the method there is nothing else I can do... Or can I? One of the Methods I was suggested to use is: ``` public IEnumerable<Card> CreateDeck() { var deck = new List<Card>(); foreach(var value in Enum.GetValues<CardValue>()) foreach (var suit in Enum.GetValues<CardSuit>()) deck.Add(new Card(value, suit)); return deck; } ``` **My Enums for Cards** ``` public enum CardValue {Ace, King, Queen, Jack, Ten, Nine, Eight, Seven, Six, Five, Four, Three, Two}; public enum CardSuit {Spades, Clubs, Hearts, Diamonds}; ``` **Creating a Card** ``` public struct Card { public CardValue Value { get; } public CardSuit Suit { get; } public Card(CardValue value, CardSuit suit) { Value = value; Suit = suit; } public override string ToString() { return $"{Value} of {Suit}"; } } ```
2022/02/09
[ "https://Stackoverflow.com/questions/71047996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12394124/" ]
Just use a simple `foreach` loop: ``` foreach (var card in CreateDeck()) Console.WriteLine(card); ``` This uses the `Console.WriteLine(object)` overload, that will internally call the `ToString()` method defined on `Card`. --- As an aside, you could reduce memory usage in your `CreateDeck` method by using `yield return` instead of allocating a list: ``` public IEnumerable<Card> CreateDeck() { foreach (var value in Enum.GetValues<CardValue>()) { foreach (var suit in Enum.GetValues<CardSuit>()) { yield return new Card(value, suit); } } } ``` This way, `Card`s are created on-demand as you iterate, and immediately become eligible for garbage collection after they leave scope. If you find that you need a list, you can always do this: ``` var cards = CreateDeck().ToList(); ```
Implement GetEnumerator method in CardDeck class or any class as ```cs class Program { static void Main(string[] args) { var cd = new CardDeck(); cd.cards = new List<Card>() { new Card(CardValue.Ace, CardSuit.Spades), new Card(CardValue.Five, CardSuit.Clubs) }; foreach (var c in cd) { Console.WriteLine(c); } } } ``` Above is example how to use in look OP Code ```cs public enum CardValue { Ace, King, Queen, Jack, Ten, Nine, Eight, Seven, Six, Five, Four, Three, Two }; public enum CardSuit { Spades, Clubs, Hearts, Diamonds }; public struct Card { public CardValue Value { get; } public CardSuit Suit { get; } public Card(CardValue value, CardSuit suit) { Value = value; Suit = suit; } public override string ToString() { return $"{Value} of {Suit}"; } } ``` IEnumerable implementation ```cs class CardDeck { public List<Card> cards; public IEnumerator<Card> GetEnumerator() { foreach (var contact in cards) yield return contact; } } ```
36,272,712
So I've been stuck for hours trying to figure out this problem. Given a randomly generated BST and using the method header: `public E higher(E elt)` Where `elt` is a randomly generated value within the tree's range, I need to find the least element in the set greater than `elt`. Nodes contain left links and right links, but no parent link. The tree in the linked image reads with the root being the leftmost node [BST](http://i.stack.imgur.com/sEZPn.png). So if `elt` is 27, then I want to return the node containing 28. I need to run this in O(logn) time, and everything I've tried has not worked. I'm not looking for someone to do my homework for me, but I have no clue what to do at this point. I can provide more detail and source code if it's needed. Edit: I'll put this here, though it's woefully inadequate. I feel as though this would be easier if I could do this recursively but I can't think of a way to do that. ``` Node n = root; //need to get this into a loop somehow and break out when I've found //the right value int c = myCompare(elt, ((E) n.data)); if (c < 0) { n = n.left; //now I need to compare this against any children } else if (c > 0) { n = n.right; //now I need to compare this against any children } return ((E)n.data); ```
2016/03/28
[ "https://Stackoverflow.com/questions/36272712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4938662/" ]
It's ``` UnityEngine.SceneManagement.SceneManager.LoadScene("Gameplay"); ``` and yes it does it "instantly" -- that is to say **s**ynchronously. In other words, it "stops" at that line of code, waits until it loads the whole scene (even if that takes some seconds) and then the new scene begins. Do not use the old command you mention in the question. Note that Unity also has the ability to do **a**sync loading .. it "slowly loads the new scene in the background". **However:** I encourage you to only use ordinary "LoadScene". All that matters is reliability and simplicity. **Users simply *don't mind* if the machine just "stops" for a few seconds while a level loads.** (Every time I click "Netflix" on my TV, it takes some time for the TV to do that. Nobody cares - it is normal.) But if you do want to load in the background, here's how... ``` public void LaunchGameRunWith(string levelCode, int stars, int diamonds) { .. analytics StartCoroutine(_game( levelCode, superBombs, hearts)); } private IEnumerator _game(string levelFileName, int stars, int diamonds) { // first, add some fake delay so it looks impressive on // ordinary modern machines made after 1960 yield return new WaitForSeconds(1.5f); AsyncOperation ao; ao = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync("Gameplay"); // here's exactly how you wait for it to load: while (!ao.isDone) { Debug.Log("loading " +ao.progress.ToString("n2")); yield return null; } // here's a confusing issue. in the new scene you have to have // some sort of script that controls things, perhaps "NewLap" NewLap newLap = Object.FindObjectOfType< NewLap >(); Gameplay gameplay = Object.FindObjectOfType<Gameplay>(); // this is precisely how you conceptually pass info from // say your "main menu scene" to "actual gameplay"... newLap.StarLevel = stars; newLap.DiamondTime = diamonds; newLap.ActuallyBeginRunWithLevel(levelFileName); } ``` Note: that script answers the question of how you pass information "from your main menu" when the player hits play "on to the actual game play scene".
Maybe it's changed. From the docs: > > When using SceneManager.LoadScene, the loading does not happen immediately, it completes in the next frame. > > > I had been doing the exact same thing as the poster and it was instantiating in the old scene. <https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html>
21,776,458
i am using a Apache directory studio for as my database. how i can create there my own field. because there are object class and based upon object class we can add the filed. how can we manually add any filed.. Following is my LDIF file. ``` dn: cn = username ,ou=users,o=Agile-Infotech,ou=system objectClass: organizationalPerson objectClass: person objectClass: inetOrgPerson objectClass: top cn: ***** sn: Doshi description: Manager uid: ****** userPassword:: e1NTSEF9TThWUnR3QjZrQm1jUTFjcWhUMmgwcmJqQUZCbGVnbkVHdDkzamc9P **homeFolder : anything** // i want to add this filed also in the user. ``` when i am adding in apache Ds it gives me **NO SUCH ATTRIBUTE FOUND**
2014/02/14
[ "https://Stackoverflow.com/questions/21776458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3184740/" ]
The LDAP object classes and their attributes are described in `schema` definition files. The classes and attributes can be inherited from and extended. If you want to add a new attribute to the class `organizationalPerson`, then you need to extend it. The schema files OpenLDAP ships with reside in a sub-directory `schema` under your OpenLDAP installation directory. Although not all files in that directory are being loaded into OpenLDAP by default. You can add your own definition files to that directory or any other directory the OpenLDAP run-user can read from. Have a look at the OpenLDAP [schema reference](http://www.openldap.org/doc/admin24/schema.html) and this [article](http://www.yolinux.com/TUTORIALS/LinuxTutorialLDAP-DefineObjectsAndAttributes.html) for a quick rundown on how to extend object classes and attributes. If you are using ApacheDS you can use the Apache Directory Studio to extend the schema via the studio or you can import OpenLDAP schema files. See the [online documentation](https://directory.apache.org/studio/users-guide/schema_editor/tasks.html).
You need to create a schema project, add schema and then add attributetype. Refer to similar attribute type in the existing schema if you have or read the OpenLDAP documentation. Basically, your definition of custom attribute type have to mention mandatory fields like the OID, NAME, SYNTAX etc.
11,627,441
I know I can get the time since the last boot using `Environment.TickCount` But is it possible to get the last time a compute woke up from hibernation or sleep? (Without using WMI please)
2012/07/24
[ "https://Stackoverflow.com/questions/11627441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/766006/" ]
Try this command - use [Process](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx) to fire it off - you'll need to parse the result > > cmd /k wevtutil qe System > /q:"\*[System[Provider[@Name='Microsoft-Windows-Power-Troubleshooter']]]" > /rd:true /c:1 /f:text > > > Lifted from [here](http://www.xhroot.com/blog/2012/04/14/get-time-of-last-wake-from-sleep-in-windows7/) if you want more info...
According to [this page](http://msdn.microsoft.com/en-us/library/windows/desktop/aa373235%28v=vs.85%29.aspx) you'll have to listen for [PBT\_APMRESUMEAUTOMATIC](http://msdn.microsoft.com/en-us/library/windows/desktop/aa372718%28v=vs.85%29.aspx) (and [PBT\_APMRESUMESUSPEND](http://msdn.microsoft.com/en-us/library/windows/desktop/aa372720%28v=vs.85%29.aspx) if you want to know if a user was the 'cause' for the wakeup). I think [Microsoft.Win32.SystemEvents](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.aspx) ([PowerModeChanged event](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.powermodechanged%28v=vs.85%29.aspx)) is the place to look but, without investigating any further, there might be [some issues](http://connect.microsoft.com/VisualStudio/feedback/details/736387/systemevents-powermodechanged-appears-to-ignore-pbt-apmresumeautomatic#details). [This page](http://www.pinvoke.net/default.aspx/user32/registerpowersettingnotification.html) might be interesting to get you started.
11,627,441
I know I can get the time since the last boot using `Environment.TickCount` But is it possible to get the last time a compute woke up from hibernation or sleep? (Without using WMI please)
2012/07/24
[ "https://Stackoverflow.com/questions/11627441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/766006/" ]
Try this command - use [Process](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx) to fire it off - you'll need to parse the result > > cmd /k wevtutil qe System > /q:"\*[System[Provider[@Name='Microsoft-Windows-Power-Troubleshooter']]]" > /rd:true /c:1 /f:text > > > Lifted from [here](http://www.xhroot.com/blog/2012/04/14/get-time-of-last-wake-from-sleep-in-windows7/) if you want more info...
Although there's an answer above that provides the core query, here's a more fleshed out solution for anyone who decides they want something more complete. ``` private string getLastWakeInfo() { String args = @"qe System /q:"" *[System[Provider[@Name = 'Microsoft-Windows-Power-Troubleshooter']]]"" /rd:true /c:1 /f:xml"; ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = "wevtutil.exe"; psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.RedirectStandardInput = true; psi.Arguments = args; Process proc = Process.Start(psi); proc.WaitForExit(2000); String strOutput = proc.StandardOutput.ReadToEnd(); return strOutput; } ``` Usage: ``` private void button1_Click_2(object sender, EventArgs e) { String xml = getLastWakeInfo(); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); String path = "//*[local-name()='Event']/*[local-name()='EventData']/*[local-name()='Data'][@Name='WakeTime']"; XmlNode root = doc.DocumentElement; XmlNode node = root.SelectSingleNode(path); MessageBox.Show(node.InnerText); } ``` The following will be needed; ``` using System.Diagnostics; using System.Runtime.InteropServices; using System.Xml; using System.Windows.Forms; // Needed only if you want to show the messagebox ``` In this example, I'm trying to find the PC wake time (as listed in `@Name='WakeTime'` - Change that to get the wake time or another individual value that's returned from the query). For example, if you want to know what woke up the PC, use `WakeSourceText` instead. You'll definitely want to add some error checking, but this should achieve what you're looking for.
49,638,082
I am using Observables in Angular 5, I am getting the data back from the API. Here's my code: ``` student: Student = null; // this is at a class level ngOnInit() { const id: number = Number(this.activatedRoute.snapshot.params['id']); if (id) { this.studentEditSubscription = this.studentService.getStudentById(id).subscribe( data => { this.student = data as Student; console.log(this.student); // {id: 14, firstName: "A6", middleName: "C6", lastName: "B6", program: "CS"} }, error => alert('The student you are tyring to update does not exist')); } console.log(this.student); // null } // student.service.ts getStudentById(id: number): Observable<Object> { return this._httpClient.get(`${this.url}/${id}`); } ``` The first `console.log(this.student)` is displaying proper student object whereas the second one seems to be printing `null`. I am using `ES6's arrow function` notation, so `this` must be pointing to the class. What am I missing here? Thank You.
2018/04/03
[ "https://Stackoverflow.com/questions/49638082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5924007/" ]
You're missing here that observable code runs asynchronously. So second `console.log(...)` fires before the first one. That's why you get `null` output from it. You can confirm this by changing `student` initial value to something else. You will get this value.
I believe your issue here is that the callback of the subscription on the `studentService#getStudentById` event is asynchronous so the first `null` console.log runs in the first tick of the event loop in this scope then once the observable is resolved then the `.student` is set. A basic example of this is: ``` setTimeout(_ => console.log('This runs after')); console.log('This runs before'); ``` The callback of the setTimeout is equivalent to your subscription to the observable.
19,043
Context ------- In this [Thread](http://www.mmo-champion.com/threads/2221878-Michael-Flynn-committed-Treason) the user titles it '*Michael Flynn committed Treason*'. He believes that Michael Flynn committed treason, Treason is defined in the [Article III Section 3](https://www.law.cornell.edu/constitution/articleiii) of the U.S. Constitution as: > > Treason against the United States, shall consist only in levying war > against them, or in adhering to their enemies, giving them aid and > comfort. No person shall be convicted of treason unless on the > testimony of two witnesses to the same overt act, or on confession in > open court. > > > The Congress shall have power to declare the punishment of treason, > but no attainder of treason shall work corruption of blood, or > forfeiture except during the life of the person attainted. > > > So, I'm not sure how much this would be defined as Treason. From my understanding Treason is defined as someone who the U.S. has declared war on, and they officially haven't done that according to [this article](http://edition.cnn.com/2016/07/18/politics/isis-declaration-of-war/). > > But the U.S. hasn't formally declared war on ISIS -- or on anyone else > since 1942, when Congress voted to do so against Nazi Germany allies > Bulgaria, Hungary and Romania. > > > Am I right in this assertion? Question -------- Did Michael Flynn commit treason?
2017/05/18
[ "https://law.stackexchange.com/questions/19043", "https://law.stackexchange.com", "https://law.stackexchange.com/users/18615/" ]
Since the treason statute is quite vague, you have to discover what the details of the law is by looking at precedent. Almost all federal treason convictions in the US have involved declared wars. There is the case of [John Fries](https://en.wikipedia.org/wiki/Fries%27s_Rebellion#Trials), an early tax rebellion case in 1800, who was pardoned by the president thus rendering the need for legal appeal moot, but this involved armed insurrection and is thus not analogous. All other federal cases have involved people supporting the enemy in case of a declared war. In this specific case, the allegation is that by advocating not working with Syrian Kurds in an assault on Raqqa (because it was thought to be in the best interests of the US in terms of our relationship with Turkey, given the position of the Turkish state w.r.t. Kurds), Flynn benefited ISIS. Compared to various wartime treason convictions, such as [Tokyo Rose and Axis Sally](https://en.wikipedia.org/wiki/List_of_people_convicted_of_treason), the difference between imaginary "aid" in the case of Flynn vs. actual aid in the other cases is so stark that there is no case to be made for a treason charge.
It says in times of war, or in adhering to their enemies, giving comfort or aid. You do not need to be at war to commit treason. Selling top secret information to others is treason. Lying to our top governing body- sounds like treason to me. There is a line of guys waiting to be tried. coercion with a foreign government that has known to be involved in comptomising or electoral process. Flynn should do some jail time.
19,043
Context ------- In this [Thread](http://www.mmo-champion.com/threads/2221878-Michael-Flynn-committed-Treason) the user titles it '*Michael Flynn committed Treason*'. He believes that Michael Flynn committed treason, Treason is defined in the [Article III Section 3](https://www.law.cornell.edu/constitution/articleiii) of the U.S. Constitution as: > > Treason against the United States, shall consist only in levying war > against them, or in adhering to their enemies, giving them aid and > comfort. No person shall be convicted of treason unless on the > testimony of two witnesses to the same overt act, or on confession in > open court. > > > The Congress shall have power to declare the punishment of treason, > but no attainder of treason shall work corruption of blood, or > forfeiture except during the life of the person attainted. > > > So, I'm not sure how much this would be defined as Treason. From my understanding Treason is defined as someone who the U.S. has declared war on, and they officially haven't done that according to [this article](http://edition.cnn.com/2016/07/18/politics/isis-declaration-of-war/). > > But the U.S. hasn't formally declared war on ISIS -- or on anyone else > since 1942, when Congress voted to do so against Nazi Germany allies > Bulgaria, Hungary and Romania. > > > Am I right in this assertion? Question -------- Did Michael Flynn commit treason?
2017/05/18
[ "https://law.stackexchange.com/questions/19043", "https://law.stackexchange.com", "https://law.stackexchange.com/users/18615/" ]
Since the treason statute is quite vague, you have to discover what the details of the law is by looking at precedent. Almost all federal treason convictions in the US have involved declared wars. There is the case of [John Fries](https://en.wikipedia.org/wiki/Fries%27s_Rebellion#Trials), an early tax rebellion case in 1800, who was pardoned by the president thus rendering the need for legal appeal moot, but this involved armed insurrection and is thus not analogous. All other federal cases have involved people supporting the enemy in case of a declared war. In this specific case, the allegation is that by advocating not working with Syrian Kurds in an assault on Raqqa (because it was thought to be in the best interests of the US in terms of our relationship with Turkey, given the position of the Turkish state w.r.t. Kurds), Flynn benefited ISIS. Compared to various wartime treason convictions, such as [Tokyo Rose and Axis Sally](https://en.wikipedia.org/wiki/List_of_people_convicted_of_treason), the difference between imaginary "aid" in the case of Flynn vs. actual aid in the other cases is so stark that there is no case to be made for a treason charge.
Treason is defined in Article III, Section 3, Clause 1 of the United States Constitution (it is the only constitutionally defined crime): > > Treason against the United States, shall consist only in levying war > against them, or in adhering to their enemies, giving them aid and > comfort. > > > The legal meaning of the word "enemy" in the context of treason law, is a country or group upon whom a war has been declared. Michael Flynn did not levy a war against the United States. Michael Flynn did not give aid and comfort or adhere to a country with whom the United States was currently in a declared war. Therefore, Michael Flynn did not commit treason.
19,043
Context ------- In this [Thread](http://www.mmo-champion.com/threads/2221878-Michael-Flynn-committed-Treason) the user titles it '*Michael Flynn committed Treason*'. He believes that Michael Flynn committed treason, Treason is defined in the [Article III Section 3](https://www.law.cornell.edu/constitution/articleiii) of the U.S. Constitution as: > > Treason against the United States, shall consist only in levying war > against them, or in adhering to their enemies, giving them aid and > comfort. No person shall be convicted of treason unless on the > testimony of two witnesses to the same overt act, or on confession in > open court. > > > The Congress shall have power to declare the punishment of treason, > but no attainder of treason shall work corruption of blood, or > forfeiture except during the life of the person attainted. > > > So, I'm not sure how much this would be defined as Treason. From my understanding Treason is defined as someone who the U.S. has declared war on, and they officially haven't done that according to [this article](http://edition.cnn.com/2016/07/18/politics/isis-declaration-of-war/). > > But the U.S. hasn't formally declared war on ISIS -- or on anyone else > since 1942, when Congress voted to do so against Nazi Germany allies > Bulgaria, Hungary and Romania. > > > Am I right in this assertion? Question -------- Did Michael Flynn commit treason?
2017/05/18
[ "https://law.stackexchange.com/questions/19043", "https://law.stackexchange.com", "https://law.stackexchange.com/users/18615/" ]
Treason is defined in Article III, Section 3, Clause 1 of the United States Constitution (it is the only constitutionally defined crime): > > Treason against the United States, shall consist only in levying war > against them, or in adhering to their enemies, giving them aid and > comfort. > > > The legal meaning of the word "enemy" in the context of treason law, is a country or group upon whom a war has been declared. Michael Flynn did not levy a war against the United States. Michael Flynn did not give aid and comfort or adhere to a country with whom the United States was currently in a declared war. Therefore, Michael Flynn did not commit treason.
It says in times of war, or in adhering to their enemies, giving comfort or aid. You do not need to be at war to commit treason. Selling top secret information to others is treason. Lying to our top governing body- sounds like treason to me. There is a line of guys waiting to be tried. coercion with a foreign government that has known to be involved in comptomising or electoral process. Flynn should do some jail time.
57,373,808
I am getting this error message when i wanna add a new line in my table: ``` ERROR TypeError: Cannot read property 'Nom' of undefined at Object.eval [as updateDirectives] (MedecinsComponent.html:43) at Object.debugUpdateDirectives [as updateDirectives] (core.js:36043) at checkAndUpdateView (core.js:35055) at callViewAction (core.js:35421) at execEmbeddedViewsAction (core.js:35378) at checkAndUpdateView (core.js:35056) at callViewAction (core.js:35421) at execComponentViewsAction (core.js:35349) at checkAndUpdateView (core.js:35062) at callViewAction (core.js:35421) ``` Here's my code: **component.ts** ```js this.cols = [ { field: 'User.Nom', header: 'Nom' }, { field: 'User.Prénom', header: 'Prénom' }, { field: 'User.Tel', header: 'Téléphone' }, { field: 'User.Email', header: 'Email' }, { field: 'User.Pays', header: 'Pays' }, { field: 'User.Login', header: 'Login' }, { field: 'User.Password', header: 'Password' }, { field: 'User.Active', header: 'Active' }, { field: 'Details', header: 'Détails'} ]; ``` **component.html** ```html <p-dialog header="Détails de l'utilisateur" [(visible)]="displayDialog" [responsive]="true" showEffect="fade" [modal]="true" [closable]="true" [width]="600"> <div class="ui-g ui-fluid" *ngIf="medecin"> <div class="ui-g-4"><label for="Nom">Nom</label></div> <div class="ui-g-8"><input pInputText id="Nom" [(ngModel)]="medecin.Users.Nom"/></div> </div> </p-dialog> ``` **model.ts** ```js import { User } from './user'; export class Medecin { Id: number; Users_Id: number; Image: ByteLengthChunk; Details: string; Updated: Date; Created: Date; Deleted: Date; Users: User; } ``` So, is there an implementation issue? Am I doing it wrong?
2019/08/06
[ "https://Stackoverflow.com/questions/57373808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11869110/" ]
You must initialize and get the value of "User" instance first. so before writing "this.col = ..." try getting the user instance & then pass-on the user properties to "col" array of objects.
Since it says "can't find property Nom in undefined", it looks like you have no object `User` to start with.
2,683,577
I have a bash script that runs on our shared web host. It does a dump of our mysql database and zips up the output file. Sometimes the mysqldump process gets killed, which leaves an incomplete sql file that still gets zipped. How do I get my script to 'notice' the killing and then delete the output file if the killing occurred? --- Edit: here's the line from my script ``` nice -19 mysqldump -uuser -ppassword -h database.hostname.com --skip-opt --all --complete-insert --add-drop-table database_name > ~/file/system/path/filename.sql ``` And here's what I get *on occasion* from my buddy Cron: ``` /home/user/backup_script.bash: line 17: 12611 Killed nice -19 mysqldump -uuser -ppassword -h database.hostname.com --skip-opt --all --complete-insert --add-drop-table database_name > ~/file/system/path/filename.sql ``` So when this happens, I want to just delete the filename.sql, becuase it will have some number of inserts, but not all. I know in bash there is someway to capture the output state of a command, true or false, and then if it's false, do something.
2010/04/21
[ "https://Stackoverflow.com/questions/2683577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151841/" ]
If mysqldump gets killed it will have an exit code != 0: ``` if ! mysqldump ...;then rm ... fi ```
You could use `ps` or `pgrep` to see if the process is still running based on its name. Or you could use `lsof` on the SQL file to see if a process is accessing the file. However, if the process completes normally, that "open" connection will no longer be there.
40,931,089
Going to develop an `iOS VoIP` app as my final project, but not finding a proper `SDK` to be used for making app to work like `Skype/ Viber`, for Voice and Video Call. Or suggest me another FREE library. I working on this from the previous 2 months... Thanks. EDIT: [![](https://i.stack.imgur.com/6B1jL.png)](https://i.stack.imgur.com/6B1jL.png) When I perform 'lipo' command this occurs: ``` iMac-2:lib mac$ lipo -arch libpj-arm64-apple-darwin_ios.a -arch libpj-armv7-apple-darwin_ios.a -arch libpj-armv7s-apple-darwin_ios.a -arch libpj-x86_64-apple-darwin16.0.0.a -create -output libpjlib.a error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/lipo: unknown architecture specification flag: libpj-arm64-apple-darwin_ios.a in specifying input file -arch libpj-arm64-apple-darwin_ios.a -arch /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/lipo: known architecture flags are: any little big ppc64 x86_64 x86_64h arm64 ppc970-64 ppc i386 m68k hppa sparc m88k i860 veo arm ppc601 ppc603 ppc603e ppc603ev ppc604 ppc604e ppc750 ppc7400 ppc7450 ppc970 i486 i486SX pentium i586 pentpro i686 pentIIm3 pentIIm5 pentium4 m68030 m68040 hppa7100LC veo1 veo2 veo3 veo4 armv4t armv5 xscale armv6 armv6m armv7 armv7f armv7s armv7k armv7m armv7em arm64v8 fatal error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/lipo: Usage: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/lipo [input_file] ... [-arch <arch_type> input_file] ... [-info] [-detailed_info] [-output output_file] [-create] [-arch_blank <arch_type>] [-thin <arch_type>] [-remove <arch_type>] ... [-extract <arch_type>] ... [-extract_family <arch_type>] ... [-verify_arch <arch_type> ...] [-replace <arch_type> <file_name>] ... ```
2016/12/02
[ "https://Stackoverflow.com/questions/40931089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6940895/" ]
If you got errors in library means, Either you have not properly configure the PJSIP project in Your system (or) you missed any library that you want to add in your xcode project. If you want to run project in simulator or iphone? There is two different configuration for pjsip project. For iphone and simulator, configuring project is different. For properly configure your PJSIP Project in your system, follow this below link. Source : <https://trac.pjsip.org/repos/wiki/Getting-Started/iPhone> Please post the error message completely in your xcode, to solve the problem.
You missed architecture name **was:** ``` lipo -arch libpj-arm64-apple-darwin_ios.a -arch libpj-armv7-apple-darwin_ios.a ... ``` **Need:** ``` lipo -arch arm64 libpj-arm64-apple-darwin_ios.a -arch armv7 libpj-armv7-apple-darwin_ios.a ... ``` For each **-arch** you need set **name** and than lib name
31,208,949
I got a problem with SQL statment, I am trying to make START field unique. What I mean is to DELETE rest fields which has the same value in this field. My SQL query: ``` SELECT s.date AS START , s.machine_id, s.stop_id, o.date AS STOP FROM stops s LEFT JOIN performance_v2 o ON o.date > s.date AND o.machine_id = s.machine_id AND impuls_count > 0 ```
2015/07/03
[ "https://Stackoverflow.com/questions/31208949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4287406/" ]
I believe typically that means that the character is not recognized by the font.
here are couple of thing i would check, 1. are you using a custom font, do that custom font support   ? 2. did you declear a charset in your meta? 3. instead of using `&nbsp;` why can't you use regular `space`? 4. are you using a data base, make sure you set the connection to utf-8 too.
26,013,209
I'm using `Joomla 2.5` and it is not giving duplicate email address for the user registration. But I want create accounts using same email address. I know I've to edit the core and It may be not an issue because I'm not going to update the Joomla in future. How can I do that core hack? Thanks
2014/09/24
[ "https://Stackoverflow.com/questions/26013209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/795446/" ]
I'm a little shocked that you said you will never update Joomla in the future. 2.5 as you may not know will reach EOL (end of life) in December this year, therefore a lot of extension developers will stop support and developing extensions for 2.5, therefore if you have any issues, you may run into problems. Secondly, please just don't do a core hack, it's the most awful thing one can do. I needn't explain why. I would simply suggest using an extension such as [User Same Email](http://extensions.joomla.org/extensions/clients-a-communities/user-management/24599)
I agree with Lodder on his point of view that a "core hack" is bad, and that using an extension like "Users Same Email" (<http://extensions.joomla.org/extensions/clients-a-communities/user-management/24599>) is better. But however, if really you need so, you can have a look at the hack propose on the Joomla forum : <http://forum.joomla.org/viewtopic.php?p=2424367> It explain where to change the code in the \libraries\joomla\database\table\user.php file, to have the possibility to register many user with the same email.
34,652,499
I've just found a binary version [NSString to Print in in binary format](https://stackoverflow.com/questions/1286425/nsstring-to-print-in-in-binary-format), but I want to know if there is a flexible version. ``` let initialBits: UInt8 = 0b00001111 let invertedBits = ~initialBits // equals 11110000 let stringOfInvertedBits = String(invertedBits, radix: 2) // convert to string in binary print(stringOfInvertedBits) // 11110000 ``` `radix: 2` means binary, and `radix: 8` means octonary, etc...
2016/01/07
[ "https://Stackoverflow.com/questions/34652499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5756660/" ]
This is a modification of @Paul Griffiths answer, which is faster and more efficient as it avoids constant re-allocation of the `NSString`: ``` - (NSString *)formatStringFromInt:(int)value withRadix:(int)radix { if (value == 0) return @"0"; if (radix < 2 || radix > 36) radix = 10; const unsigned buffsize = 64; unichar buffer[buffsize]; unsigned offset = buffsize; static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int absValue = abs(value); while (absValue > 0) { buffer[--offset] = (unichar)digits[absValue % radix]; absValue /= radix; } if (value < 0) buffer[--offset] = '-'; return [[NSString alloc] initWithCharacters:buffer + offset length:buffsize - offset]; } ``` Produces: ``` 2016-01-08 11:52:53.644 stringformatprefix[7560:606490] D 2016-01-08 11:52:53.645 stringformatprefix[7560:606490] 13 2016-01-08 11:52:53.645 stringformatprefix[7560:606490] -15 2016-01-08 11:52:53.645 stringformatprefix[7560:606490] -23 2016-01-08 11:52:53.645 stringformatprefix[7560:606490] 1101 ```
Here's an easy modification: ``` #import <Foundation/Foundation.h> NSString * getBitStringForInt(const int value, const int radix) { static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; if ( radix < 2 || radix > 36 ) { return NULL; } NSString *bits = @""; int absValue = abs(value); while ( absValue ) { bits = [NSString stringWithFormat:@"%c%@", digits[absValue % radix], bits]; absValue /= radix; } if ( value < 0 ) { bits = [NSString stringWithFormat:@"-%@", bits]; } return bits; } int main(int argc, const char * argv[]) { @autoreleasepool { NSString * val = getBitStringForInt(13, 16); NSLog(@"%@", val); val = getBitStringForInt(13, 10); NSLog(@"%@", val); val = getBitStringForInt(-13, 8); NSLog(@"%@", val); val = getBitStringForInt(-13, 5); NSLog(@"%@", val); val = getBitStringForInt(13, 2); NSLog(@"%@", val); } return 0; } ``` with output: ``` 2016-01-07 21:59:59.144 TestCmdLine[49904:18135090] D 2016-01-07 21:59:59.145 TestCmdLine[49904:18135090] 13 2016-01-07 21:59:59.145 TestCmdLine[49904:18135090] -15 2016-01-07 21:59:59.145 TestCmdLine[49904:18135090] -23 2016-01-07 21:59:59.145 TestCmdLine[49904:18135090] 1101 Program ended with exit code: 0 ```
2,783
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
2009/05/01
[ "https://serverfault.com/questions/2783", "https://serverfault.com", "https://serverfault.com/users/1532/" ]
Some things that have tipped me off in the past: * High load on a system that should be idle * Weird segfaults, eg. from standard utilities like `ls` (this can happen with broken root kits) * Hidden directories in `/` or `/var/` (most script kiddies are too stupid or lazy to cover their tracks) * `netstat` shows open ports that shouldn't be there * Daemons in the process list that you normally use different flavours of (eg. `bind`, but you always use `djbdns`) Additionally I've found the there's one reliable sign that a box is compromised: if you have a bad feeling about the diligence (with updates, etc.) of the admin from whom you inherited a system, keep a close eye on it!
You should check out GuardRail. It can scan your server on a daily basis and tell you what's changed in a nice visual way. It doesn't require an agent and can connect over SSH so you don't need to junk up your machine and resources with an agent. Best of all, it's free for up to 5 servers. Check it out here: <https://www.scriptrock.com/>
2,783
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
2009/05/01
[ "https://serverfault.com/questions/2783", "https://serverfault.com", "https://serverfault.com/users/1532/" ]
Some things that have tipped me off in the past: * High load on a system that should be idle * Weird segfaults, eg. from standard utilities like `ls` (this can happen with broken root kits) * Hidden directories in `/` or `/var/` (most script kiddies are too stupid or lazy to cover their tracks) * `netstat` shows open ports that shouldn't be there * Daemons in the process list that you normally use different flavours of (eg. `bind`, but you always use `djbdns`) Additionally I've found the there's one reliable sign that a box is compromised: if you have a bad feeling about the diligence (with updates, etc.) of the admin from whom you inherited a system, keep a close eye on it!
I'll second the responses given here and add one of my own. ``` find /etc /var -mtime -2 ``` This will give you a quick indication if any of your main server files have changed in the last 2 days. This is from an article on hack detection [How to detect if your server has been hacked.](http://servermonitoringhq.com/blog/how_to_check_if_your_server_has_been_hacked)
2,783
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
2009/05/01
[ "https://serverfault.com/questions/2783", "https://serverfault.com", "https://serverfault.com/users/1532/" ]
There's a method of checking hacked servers via `kill` - Essentially, when you run "kill -0 $PID" you are sending a nop signal to process identifier $PID. If the process is running, the kill command will exit normally. (FWIW, since you're passing a nop kill signal, nothing will happen to the process). If a process isn't running, the kill command will fail (exit status less than zero). When your server is hacked / a rootkit is installed, one of the first things it does is tell the kernel to hide the affected processes from the process tables etc. However it can do all sorts of cool things in kernel space to muck around with the processes. And so this means that a) This check isn't an extensive check, since the well coded/intelligent rootkits will ensure that the kernel will reply with a "process doesn't exist" reply making this check redundant. b) Either way, when a hacked server has a "bad" process running, it's PID usually won't show under /proc. *So*, if you're here until now, the method is to kill -0 every available process in the system (anything from 1 -> /proc/sys/kernel/pid\_max) and see if there are processes that are running but not reported in /proc. If some processes do come up as running, but not reported in /proc, you probably do have a problem any way you look at it. Here's a bash script that implements all that - <https://gist.github.com/1032229> . Save that in some file and execute it, if you find a process that comes up unreported in proc, you should have some lead to start digging in. HTH.
After searching around a bit, there's this also, it does what I've listed above, amongst some other stuff: <http://www.chkrootkit.org/> and <http://www.rootkit.nl/projects/rootkit_hunter.html>
2,783
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
2009/05/01
[ "https://serverfault.com/questions/2783", "https://serverfault.com", "https://serverfault.com/users/1532/" ]
Some things that have tipped me off in the past: * High load on a system that should be idle * Weird segfaults, eg. from standard utilities like `ls` (this can happen with broken root kits) * Hidden directories in `/` or `/var/` (most script kiddies are too stupid or lazy to cover their tracks) * `netstat` shows open ports that shouldn't be there * Daemons in the process list that you normally use different flavours of (eg. `bind`, but you always use `djbdns`) Additionally I've found the there's one reliable sign that a box is compromised: if you have a bad feeling about the diligence (with updates, etc.) of the admin from whom you inherited a system, keep a close eye on it!
There's a method of checking hacked servers via `kill` - Essentially, when you run "kill -0 $PID" you are sending a nop signal to process identifier $PID. If the process is running, the kill command will exit normally. (FWIW, since you're passing a nop kill signal, nothing will happen to the process). If a process isn't running, the kill command will fail (exit status less than zero). When your server is hacked / a rootkit is installed, one of the first things it does is tell the kernel to hide the affected processes from the process tables etc. However it can do all sorts of cool things in kernel space to muck around with the processes. And so this means that a) This check isn't an extensive check, since the well coded/intelligent rootkits will ensure that the kernel will reply with a "process doesn't exist" reply making this check redundant. b) Either way, when a hacked server has a "bad" process running, it's PID usually won't show under /proc. *So*, if you're here until now, the method is to kill -0 every available process in the system (anything from 1 -> /proc/sys/kernel/pid\_max) and see if there are processes that are running but not reported in /proc. If some processes do come up as running, but not reported in /proc, you probably do have a problem any way you look at it. Here's a bash script that implements all that - <https://gist.github.com/1032229> . Save that in some file and execute it, if you find a process that comes up unreported in proc, you should have some lead to start digging in. HTH.
2,783
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
2009/05/01
[ "https://serverfault.com/questions/2783", "https://serverfault.com", "https://serverfault.com/users/1532/" ]
[Tripwire](http://sourceforge.net/projects/tripwire/) is a commonly used tool - it notifies you when system files have changed, although obviously you need to have it installed beforehand. Otherwise items such as new user accounts you don't know about, weird processes and files you don't recognize, or increased bandwidth usage for no apparent reason are the usual signs. Other monitoring systems such as [Zabbix](http://www.zabbix.com/) can be configured to alert you when files such as /etc/passwd are changed.
I'll second the responses given here and add one of my own. ``` find /etc /var -mtime -2 ``` This will give you a quick indication if any of your main server files have changed in the last 2 days. This is from an article on hack detection [How to detect if your server has been hacked.](http://servermonitoringhq.com/blog/how_to_check_if_your_server_has_been_hacked)
2,783
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
2009/05/01
[ "https://serverfault.com/questions/2783", "https://serverfault.com", "https://serverfault.com/users/1532/" ]
You don't. I know, I know - but it's the paranoid, sad truth, really ;) There are plenty of hints of course, but if the system was targeted specifically - it might be impossible to tell. It's good to understand that nothing is ever completely secure. But we need to work for more secure, so I will point at all the other answers instead ;) If your system was compromised, none of your system tools can be trusted to reveal the truth.
You should check out GuardRail. It can scan your server on a daily basis and tell you what's changed in a nice visual way. It doesn't require an agent and can connect over SSH so you don't need to junk up your machine and resources with an agent. Best of all, it's free for up to 5 servers. Check it out here: <https://www.scriptrock.com/>
2,783
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
2009/05/01
[ "https://serverfault.com/questions/2783", "https://serverfault.com", "https://serverfault.com/users/1532/" ]
I'll second the responses given here and add one of my own. ``` find /etc /var -mtime -2 ``` This will give you a quick indication if any of your main server files have changed in the last 2 days. This is from an article on hack detection [How to detect if your server has been hacked.](http://servermonitoringhq.com/blog/how_to_check_if_your_server_has_been_hacked)
After searching around a bit, there's this also, it does what I've listed above, amongst some other stuff: <http://www.chkrootkit.org/> and <http://www.rootkit.nl/projects/rootkit_hunter.html>
2,783
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
2009/05/01
[ "https://serverfault.com/questions/2783", "https://serverfault.com", "https://serverfault.com/users/1532/" ]
After searching around a bit, there's this also, it does what I've listed above, amongst some other stuff: <http://www.chkrootkit.org/> and <http://www.rootkit.nl/projects/rootkit_hunter.html>
You should check out GuardRail. It can scan your server on a daily basis and tell you what's changed in a nice visual way. It doesn't require an agent and can connect over SSH so you don't need to junk up your machine and resources with an agent. Best of all, it's free for up to 5 servers. Check it out here: <https://www.scriptrock.com/>
2,783
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
2009/05/01
[ "https://serverfault.com/questions/2783", "https://serverfault.com", "https://serverfault.com/users/1532/" ]
From [How can I detect unwanted intrusions on my servers?](https://serverfault.com/questions/650/how-can-i-detect-unwanted-intrusions-on-my-servers/800#800) * Use an IDS > > SNORT® is an open source network intrusion prevention and detection system utilizing a rule-driven language, which combines the benefits of signature, protocol and anomaly based inspection methods. With millions of downloads to date, Snort is the most widely deployed intrusion detection and prevention technology worldwide and has become the de facto standard for the industry. > > > Snort reads network traffic and can look for things like "drive by pen testing" where someone just runs an entire metasploit scan against your servers. Good to know these sort of things, in my opinion. * Use the logs... Depending on your usage you can set it up so you know whenever a user logs in, or logs in from an odd IP, or whenever root logs in, or whenever someone attempts to login. I actually have the server e-mail me *every* log message higher than Debug. Yes, even Notice. I filter some of them of course, but every morning when I get 10 emails about stuff it makes me want to fix it so it stops happening. * Monitor your configuration - I actually keep my entire /etc in subversion so I can track revisions. * Run scans. Tools like [Lynis](http://www.rootkit.nl/projects/lynis.html) and [Rootkit Hunter](http://www.rootkit.nl/) can give you alerts to possible security holes in your applications. There are programs that maintain a hash or hash tree of all your bins and can alert you to changes. * Monitor your server - Just like you mentioned diskspace - graphs can give you a hint if something is unusual. I use [Cacti](http://www.cacti.net/) to keep an eye on CPU, network traffic, disk space, temperatures, etc. If something *looks* odd it *is* odd and you should find out why it's odd.
I'd just like to add to this: Check your bash history, if it's empty and you haven’t unset it or emptied it, there a good possibility someone has compromised your server. Check last. Either you will see unknown I.P's or it will look very empty. Then as the accepted answer stated, system files are often changed, check the date modified. However they often tamper with the date modified. They often install another version of ssh running on a random port. This is often hidden in some really odd places. Note it will normally be renamed to something other than ssh. So check netstat(might not work as they often replace it) and use iptables to block any unknown ports. In any case, this is a situation where prevention is better than cure. If you have been compromised, it's best to just format and start again. It almost impossible to confirm you have successfully cleaned the hack. Take note of the following to prevent your server from being compromised. 1. Change ssh port 2. Prevent root from being able to login 3. only allow certain users 4. Prevent password login 5. Use ssh keys, preferable password protected keys 6. Where possible blacklist all ip's and whitelist the required ips. 7. Install and configure fail2ban 8. Use tripwire to detect intrusions 9. Monitor the number of users logged in with Nagios or zabbix. Even if you get notified every time you login, at least you will know when some else is playing. 10. If possible keep your server on a vpn, and only allow ssh via vpn ip. Secure your vpn. It's worth while taking note that once they in one server, they will check through your bash history and look for other servers you connected to via ssh from that server. They will then attempt to connect to those servers. So if you get brute forced due to a poor password, it's very possible they will be able connect to the other server and compromise those too. It's an ugly world out there, I reiterate prevention is better than cure.
2,783
What are the tell-tale signs that a Linux server has been hacked? Are there any tools that can generate and email an audit report on a scheduled basis?
2009/05/01
[ "https://serverfault.com/questions/2783", "https://serverfault.com", "https://serverfault.com/users/1532/" ]
From [How can I detect unwanted intrusions on my servers?](https://serverfault.com/questions/650/how-can-i-detect-unwanted-intrusions-on-my-servers/800#800) * Use an IDS > > SNORT® is an open source network intrusion prevention and detection system utilizing a rule-driven language, which combines the benefits of signature, protocol and anomaly based inspection methods. With millions of downloads to date, Snort is the most widely deployed intrusion detection and prevention technology worldwide and has become the de facto standard for the industry. > > > Snort reads network traffic and can look for things like "drive by pen testing" where someone just runs an entire metasploit scan against your servers. Good to know these sort of things, in my opinion. * Use the logs... Depending on your usage you can set it up so you know whenever a user logs in, or logs in from an odd IP, or whenever root logs in, or whenever someone attempts to login. I actually have the server e-mail me *every* log message higher than Debug. Yes, even Notice. I filter some of them of course, but every morning when I get 10 emails about stuff it makes me want to fix it so it stops happening. * Monitor your configuration - I actually keep my entire /etc in subversion so I can track revisions. * Run scans. Tools like [Lynis](http://www.rootkit.nl/projects/lynis.html) and [Rootkit Hunter](http://www.rootkit.nl/) can give you alerts to possible security holes in your applications. There are programs that maintain a hash or hash tree of all your bins and can alert you to changes. * Monitor your server - Just like you mentioned diskspace - graphs can give you a hint if something is unusual. I use [Cacti](http://www.cacti.net/) to keep an eye on CPU, network traffic, disk space, temperatures, etc. If something *looks* odd it *is* odd and you should find out why it's odd.
You should check out GuardRail. It can scan your server on a daily basis and tell you what's changed in a nice visual way. It doesn't require an agent and can connect over SSH so you don't need to junk up your machine and resources with an agent. Best of all, it's free for up to 5 servers. Check it out here: <https://www.scriptrock.com/>
3,334,716
I'm trying to execute the following query ``` SELECT * FROM person WHERE id IN ( SELECT user_id FROM participation WHERE activity_id = '1' AND application_id = '1' ) ``` The outer query returns about 4000 responses whilst the inner returns 29. When executed on my web server nothing happened and when I tested it locally mysql ended up using 100% CPU and still achieved nothing. Could the size be the cause? Specifically it causes the server to hang forever, I'm fairly sure the web server I ran the query on is in the process of crashing due to it (woops).
2010/07/26
[ "https://Stackoverflow.com/questions/3334716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/395082/" ]
why don't you use an inner join for this query? i think that would be faster (and easier to read) - and maybe it solves your problem (but i can't find a failure in your query). **EDIT:** the inner-join-solution would look like this: ``` SELECT person.* FROM person INNER JOIN participation ON person.id = participation.user_id WHERE participation.activity_id = '1' AND participation.application_id = '1' ```
How many rows are there in `participation` table and what indexes are there? A multi-column index on (user\_id, activity\_id, application\_id) could help here. Re comments: IN isn't slow. Subqueries within IN can be slow, if they're correlated to outer query.
53,816,896
I'm trying to do a custom radio button, I found some code on internet, and customed it. The probleme is, I need a padding 20px left/right in the label, and I need to keep the min-width at 110px and the li width is not wrapping content... He is my code if you want to see. ```css .ui-radio { margin:25px 0 0 0; padding:0; } .ui-radio li { float:left; margin:0 20px 0 0; min-width:110px; height:40px; position:relative; list-style-type: none; } .ui-radio label, .ui-radio input { display:block; position:absolute; top:0; left:0; right:0; bottom:0; } .ui-radio input[type="radio"] { opacity:0; z-index:100; } .ui-radio input[type="radio"]:checked + label { border-bottom: solid 4px BLUE; } .ui-radio label { padding:5px; cursor:pointer; z-index:90; box-shadow: 0 0 2px 0 rgba(0,0,0,0.12), 0 2px 2px 0 rgba(0,0,0,0.24); padding:0 20px; line-height:30px; border-radius:2px; } .ui-radio label:hover { background:#DDD; } ``` ```html <ul class="ui-radio"> <li> <input type="radio" id="choice1" name="personnel" /> <label for="choice1">Long_choice_1</label> </li> <li> <input type="radio" id="choice2" name="personnel" /> <label for="choice2">choice_2</label> </li> </ul> ```
2018/12/17
[ "https://Stackoverflow.com/questions/53816896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6380158/" ]
Remove `position: absolute;` from `.ui-radio label, .ui-radio input`. Absolute positioning causes item's parent not to be aware of the content size, that why the content was overflowing.
default display of label is "inline". first you should change his display to "inline-block" , "block" or ... for example : html : ``` <!DOCTYPE html> <html> <head> <link class="menu-bar" rel="stylesheet" href="../css/index.css"> <link class="container" rel="stylesheet" href="../css/menu.css"> <meta charset="utf-8"> <title>Cipher Program</title> </head> <body> <ul class="ui-radio"> <li> <input type="radio" id="choice1" name="personnel" /> <label for="choice1">Long_choice_1</label> </li> <li> <input type="radio" id="choice2" name="personnel" /> <label for="choice2">choice_2</label> </li> </ul> </body> </html> ``` css : ``` body { overflow: hidden; background: #8e2de2; background: -webkit-linear-gradient(to right, #4a00e0, #8e2de2); background: linear-gradient(to right, #4a00e0, #8e2de2); display: flex; align-items: center; justify-content: center; height: 100vh; } body .ui-radio { display: inline-flex; flex-direction: column; } body .ui-radio li { margin-bottom: 10px; border-radius: 5px; background: #fff; list-style: none; } body .ui-radio li input[type="radio"] { position: absolute; visibility: hidden; } body .ui-radio li input[type="radio"]:checked ~ label::before { background: #990099; } body .ui-radio li label { cursor: pointer; min-width: 110px; display: flex; align-items: center; padding: 10px; } body .ui-radio li label::before { transition: background ease 0.2s; content: ""; border-radius: 50%; display: inline-block; width: 15px; height: 15px; margin-right: 10px; border: 3px solid #777; box-sizing: border-box; } ```
50,952,648
I am pretty new to SQL. I have a 'Transactions' table with columns 'Model\_Id' and 'Tran\_date'. I have another 'Model' table with columns 'Model\_Id' and 'Model\_Name'. I want all the model names from 'Transactions' table which were sold in the year 2017 but not in the year 2018. How can I use the `Where` statement to get the required values in SQL Server?
2018/06/20
[ "https://Stackoverflow.com/questions/50952648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1644556/" ]
Welcome to Stack Overflow. Although I have supplied an answer here (in the form of pseudo-SQL) when posting a question like this you really need to supply Sample data and expected results as a bare minimum. Otherwise volunteers here have to guess your DDL and data, which is probably mean it'll be wrong (but possibly helpful). As I said above, however, this is pseudo-SQL, but should help you: ``` SELECT YourColumns FROM Model M WHERE EXISTS (SELECT 1 FROM [Transaction] T WHERE T.ModelID = M.ModelID AND T.TranactionDate >= '20170101' AND T.TranactionDate < '20180101') AND NOT EXISTS (SELECT 1 FROM [Transaction] T WHERE T.ModelID = M.ModelID AND T.TranactionDate >= '20180101' AND T.TranactionDate < '20190101'); ```
Hope this helps! ``` SELECT m.Model_Name FROM Transactions t JOIN Model m on m.model_id=t.model_id and year(t.tran_date)=2017 LEFT JOIN Model mm on mm.model_id=t.model_id and year(t.tran_date)=2018 WHERE mm.model_id is null ```
5,733,373
I have the following problem: when there is a space in between html tags, my code does not give me the text I want outputted. Instead of outputting: ``` year|salary|bonus 2005|100,000|50,000 2006|120,000|80,000 ``` I get this instead: ``` |salary|bonus 2005|100,000|50,000 2006|120,000|80,000 ``` the text "year" is not outputted. Here's my code: ``` from BeautifulSoup import BeautifulSoup import re html = '<html><body><table><tr><td> <p>year</p></td><td><p>salary</p></td><td>bonus</td></tr><tr><td>2005</td><td>100,000</td><td>50,000</td></tr><tr><td>2006</td><td>120,000</td><td>80,000</td></tr></table></html>' soup = BeautifulSoup(html) table = soup.find('table') rows = table.findAll('tr') store=[] for tr in rows: cols = tr.findAll('td') row = [] for td in cols: try: row.append(''.join(td.find(text=True))) except Exception: row.append('') store.append('|'.join(filter(None, row))) print '\n'.join(store) ``` The problem comes from the space in: ``` "<td> <p>year</p></td>" ``` Is there a way to get rid of that space when I pull up some html from the web?
2011/04/20
[ "https://Stackoverflow.com/questions/5733373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/714504/" ]
Instead of `row.append(''.join(td.find(text=True)))`, use : ``` row.append(''.join(td.text)) ``` Output: ``` year|salary|bonus 2005|100,000|50,000 2006|120,000|80,000 ```
As @Herman suggested, you should use `Tag.text` to find the relevant text for the tag you're currently parsing. A bit more detail on why `Tag.find()` didn't do what you want: BeautifulSoup's `Tag.find()` is very similar to to `Tag.findAll()`, in fact, its implementation of `Tag.find()` just invokes `Tag.findAll()` with a keyword argument limit, set to **1**. `Tag.findAll()` then recursively descends down the tag tree and returns once it finds some text that satisfies the `text` argument. Since you set `text` to `True`, the character "u' '" technically satisfies this condition and, thus, is what is returned by `Tag.find()`. In fact, you can see that year is returned if you print out `td.findAll(text=True, limit=2)`. You can also set `text` to a regular expression to ignore spaces, so you can then do `td.find(text=re.compile('[\S\w]'))`. I also noticed that you're using `store.append('|'.join(filter(None, row)))`. I think you should use the [CSV module](http://docs.python.org/library/csv.html), particularly the [csv.writer](http://docs.python.org/library/csv.html#csv.writer). The CSV module handles all the problems that you might face if you have a pipe somewhere in your parsed html files, and, makes your code much cleaner. Here's an example: ``` import csv import re from cStringIO import StringIO from BeautifulSoup import BeautifulSoup html = ('<html><body><table><tr><td> <p>year</p></td><td><p>salary</p></td>' '<td>bonus</td></tr><tr><td>2005</td><td>100,000</td><td>50,000</td>' '</tr><tr><td>2006</td><td>120,000</td><td>80,000</td></tr></table>' '</html>') soup = BeautifulSoup(html) table = soup.find('table') rows = table.findAll('tr') output = StringIO() writer = csv.writer(output, delimiter='|') for tr in rows: cols = tr.findAll('td') row = [] for td in cols: row.append(td.text) writer.writerow(filter(None, row)) print output.getvalue() ``` And the output is: ``` year|salary|bonus 2005|100,000|50,000 2006|120,000|80,000 ```
5,733,373
I have the following problem: when there is a space in between html tags, my code does not give me the text I want outputted. Instead of outputting: ``` year|salary|bonus 2005|100,000|50,000 2006|120,000|80,000 ``` I get this instead: ``` |salary|bonus 2005|100,000|50,000 2006|120,000|80,000 ``` the text "year" is not outputted. Here's my code: ``` from BeautifulSoup import BeautifulSoup import re html = '<html><body><table><tr><td> <p>year</p></td><td><p>salary</p></td><td>bonus</td></tr><tr><td>2005</td><td>100,000</td><td>50,000</td></tr><tr><td>2006</td><td>120,000</td><td>80,000</td></tr></table></html>' soup = BeautifulSoup(html) table = soup.find('table') rows = table.findAll('tr') store=[] for tr in rows: cols = tr.findAll('td') row = [] for td in cols: try: row.append(''.join(td.find(text=True))) except Exception: row.append('') store.append('|'.join(filter(None, row))) print '\n'.join(store) ``` The problem comes from the space in: ``` "<td> <p>year</p></td>" ``` Is there a way to get rid of that space when I pull up some html from the web?
2011/04/20
[ "https://Stackoverflow.com/questions/5733373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/714504/" ]
Instead of `row.append(''.join(td.find(text=True)))`, use : ``` row.append(''.join(td.text)) ``` Output: ``` year|salary|bonus 2005|100,000|50,000 2006|120,000|80,000 ```
use ``` html = re.sub(r'\s\s+', '', html) ```
185,678
I see a point in the throttling system, however for regular chat users and room owners it can become quite a nuisance. The room owners already have no star limits for the rooms they own, would it make much sense to remove the message throttling for those users in their rooms as well? I know many other room owners, as well as myself, who would benefit from this. So I'm opening this up as a feature request as well as a discussion, I would like to hear what other chat users think, as well as mods.
2013/06/24
[ "https://meta.stackexchange.com/questions/185678", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/167434/" ]
This answer isn't really for nor against what you want; but I will definitely vote on at least the time limit being upped, because it bugs me all the time when I'm "power-typing". I am not spamming, just having a lot of suggestions coming into my head quickly when discussing something. It's always saying "You can do this action in 2 seconds". This also happens when editing messages. You've spelled something wrong, so you *quickly* change it, then you spot another one... *quickly* change it. **OOPS** no, you can't do that, please wait. Gets quite annoying.
-1, sorry. I dislike the throttling system as it stands today, but see no reason to disable it for room owners only. The principle of SO chat is that room owners are not masters, gods, or supreme beings, and are generally subject to the same rules as everybody else. *They do not "moderate" anything!* The unlimited starring power is an arguably useful feature because it enables management of the starboard with notifications and the like, but I see nothing in the informal job description of a room owner that says they have any more right to spam the room than I do.
186,229
I often come into the situation where I am not sure how big is my variable, for instance: integer, short, long? I know that I can find size of variable with sizeof(); function in C. But now I'm in situation where I'm trying to parse some data from file and I have that file structure, when I realize that all that is written for an 8bit microcontroller, I am not sure how can I know how much data INT represents in that documentation? Is it 8 bit - 1B ? How size of variables depends on processor arhitecture? If I am correct max variable size in an 8bit processor is 1B, so char - int and all other variables are 1B maximum size?
2015/08/18
[ "https://electronics.stackexchange.com/questions/186229", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/81163/" ]
Even if your 8-bit processor only supports data handling at 8 bits, the compiler will handle all the necessary stuff for a 16-bit addition and passing on data, so the size in bits of int, short or others are purely based on your compilers settings. Normally you will find this information somewhere in the compiler manual. To get out of this trouble it is a good practice not to use the compiler defined types directly. You might want to include stdint.h (if available) which provides clearly named datatypes such as uint8\_t which is an unsigned integer with 8 bits. If you cannot use this, create your own version of it and create a header with something along those lines (or get a complete stdint.h and adapt it to your compiler): `typedef unsigned char uint8_t` where you of course have to check your compiler manual to get the right compiler types. This [wikibook](https://en.wikibooks.org/wiki/C_Programming/C_Reference/stdint.h) gives a nice explanation of stdint.h. There are some problems though, as especially for embedded devices not all data types are supported by all compilers. 64-bit data types are often missing, so there are two possible outcomes: either your program won't compile anymore (I think that is the good case) or someone has `typedef`ed the 64-bit data type to a smaller one and your program might return unexpected results because of that. In my opinion if a data type is not supported it should lead to a compilation error, so the programmer is actually aware of the problem before hitting it in the system. As an example on where to find that information for a compiler: The IAR Embedded Workbench comes with a bunch of documentation, for this kind of information, you have to look in the Development Guide, and there under the Reference Information you will find the Data representation. Under that point you will find all necessary details to handle data correctly. Alignment, Size and Range are all given there. ``` Data type Size Range Alignment bool 8 bits 0 to 1 1 char 8 bits 0 to 255 1 ... signed long long 64 bits -2^63 to 2^63-1 8 unsigned long long 64 bits 0 to 2^64-1 8 ```
You need to look at your C compiler documentation. It should spell out the answers you need. An 8-bit compiler may have "int" be 8-bits, 16-bits or something else. In some cases the number of bits in a default "int" may be selectable via a compiler command line switch or environment variable.
18,565,356
``` #!/bin/sh URL1=http://runescape.com/title.ws tot=`wget -qO- $URL1 | grep -i PlayerCount | cut -d\> -f4 | cut -d\< -f1 | sed -e's/,//'` URL2=http://oldschool.runescape.com b=`wget -qO- $URL2| grep "people playing" | awk '{print $4}'` a=`expr $tot - $b` export LC_ALL=en_US.UTF-8 a_with_comma=`echo $a | awk "{printf \"%'d\n\", \\$1}"` echo "$a_with_comma people `date '+%r %b %d %Y'`" ``` This grabs 2 numbers from URL1 and URL2 and subtracts URL1 from URL2. Trying to get the "48,877 Players Online Now" from <http://www.runescape.com/title.ws> (URL1) URL2 works fine I just can't get URL1.
2013/09/02
[ "https://Stackoverflow.com/questions/18565356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009123/" ]
Change this line: ``` ({_id:doc._id},$set:{scores:zz}); ``` To: ``` ({_id:doc._id}, { $set:{scores:zz}} ); ``` This should also probably be wrapped with a callback, to catch errors: ``` db.schools.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) { if (err) //do something. }); ```
I think you should do following code for solving issues ``` var lowScore = 9999.9; for ( var i=0; i<doc.scores.length; i++ ) { if ( doc.scores[i].type == "homework" && doc.scores[i].score < lowScore ) { lowScore = doc.scores[i].score; } } ``` and then update your collection using following query ``` collection.update({ "_id":doc._id }, { $pull : { "scores" : { $and: [ {"type":"homework"}, { "score":lowScore} ] } } }, { "safe":true }, function( err, result ) { if (err) { console.log(err); } } // update callback ); ``` for more info you can refer [here](https://gist.github.com/ronasta/4080463)
18,565,356
``` #!/bin/sh URL1=http://runescape.com/title.ws tot=`wget -qO- $URL1 | grep -i PlayerCount | cut -d\> -f4 | cut -d\< -f1 | sed -e's/,//'` URL2=http://oldschool.runescape.com b=`wget -qO- $URL2| grep "people playing" | awk '{print $4}'` a=`expr $tot - $b` export LC_ALL=en_US.UTF-8 a_with_comma=`echo $a | awk "{printf \"%'d\n\", \\$1}"` echo "$a_with_comma people `date '+%r %b %d %Y'`" ``` This grabs 2 numbers from URL1 and URL2 and subtracts URL1 from URL2. Trying to get the "48,877 Players Online Now" from <http://www.runescape.com/title.ws> (URL1) URL2 works fine I just can't get URL1.
2013/09/02
[ "https://Stackoverflow.com/questions/18565356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009123/" ]
Change this line: ``` ({_id:doc._id},$set:{scores:zz}); ``` To: ``` ({_id:doc._id}, { $set:{scores:zz}} ); ``` This should also probably be wrapped with a callback, to catch errors: ``` db.schools.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) { if (err) //do something. }); ```
I know it's a bit late to help you now, but maybe others can benefit as new cohorts pass through MongoDB University! `db.schools.update` should read `db.students.update`. @tymeJV's answer gives the rest: * Wrap the `$set` inside braces: `{$set:{scores:zz}}` * Add a callback function to catch errors: ``` db.collection( 'students' ).update ( { _id : doc._id }, { $set : { scores:zz } }, function( err, result ) { if ( err ) throw err; } ); ``` Funnily enough, I'm actually doing exactly the same assignment right now! I had a different issue that was answered by reading the docs, but I saw this question while googling for it. Hope I helped someone!
18,565,356
``` #!/bin/sh URL1=http://runescape.com/title.ws tot=`wget -qO- $URL1 | grep -i PlayerCount | cut -d\> -f4 | cut -d\< -f1 | sed -e's/,//'` URL2=http://oldschool.runescape.com b=`wget -qO- $URL2| grep "people playing" | awk '{print $4}'` a=`expr $tot - $b` export LC_ALL=en_US.UTF-8 a_with_comma=`echo $a | awk "{printf \"%'d\n\", \\$1}"` echo "$a_with_comma people `date '+%r %b %d %Y'`" ``` This grabs 2 numbers from URL1 and URL2 and subtracts URL1 from URL2. Trying to get the "48,877 Players Online Now" from <http://www.runescape.com/title.ws> (URL1) URL2 works fine I just can't get URL1.
2013/09/02
[ "https://Stackoverflow.com/questions/18565356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009123/" ]
Change this line: ``` ({_id:doc._id},$set:{scores:zz}); ``` To: ``` ({_id:doc._id}, { $set:{scores:zz}} ); ``` This should also probably be wrapped with a callback, to catch errors: ``` db.schools.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) { if (err) //do something. }); ```
``` var dbName = 'school' var tableName = 'classA' MongoClient.connect(dbName, function(err, db) { if (err) { console.log(err); } else { var collection = db.collection(tableName) collection.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) { if (err) { console.log(err); } else{ console.log(result); } }); } }); ```
18,565,356
``` #!/bin/sh URL1=http://runescape.com/title.ws tot=`wget -qO- $URL1 | grep -i PlayerCount | cut -d\> -f4 | cut -d\< -f1 | sed -e's/,//'` URL2=http://oldschool.runescape.com b=`wget -qO- $URL2| grep "people playing" | awk '{print $4}'` a=`expr $tot - $b` export LC_ALL=en_US.UTF-8 a_with_comma=`echo $a | awk "{printf \"%'d\n\", \\$1}"` echo "$a_with_comma people `date '+%r %b %d %Y'`" ``` This grabs 2 numbers from URL1 and URL2 and subtracts URL1 from URL2. Trying to get the "48,877 Players Online Now" from <http://www.runescape.com/title.ws> (URL1) URL2 works fine I just can't get URL1.
2013/09/02
[ "https://Stackoverflow.com/questions/18565356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009123/" ]
I know it's a bit late to help you now, but maybe others can benefit as new cohorts pass through MongoDB University! `db.schools.update` should read `db.students.update`. @tymeJV's answer gives the rest: * Wrap the `$set` inside braces: `{$set:{scores:zz}}` * Add a callback function to catch errors: ``` db.collection( 'students' ).update ( { _id : doc._id }, { $set : { scores:zz } }, function( err, result ) { if ( err ) throw err; } ); ``` Funnily enough, I'm actually doing exactly the same assignment right now! I had a different issue that was answered by reading the docs, but I saw this question while googling for it. Hope I helped someone!
I think you should do following code for solving issues ``` var lowScore = 9999.9; for ( var i=0; i<doc.scores.length; i++ ) { if ( doc.scores[i].type == "homework" && doc.scores[i].score < lowScore ) { lowScore = doc.scores[i].score; } } ``` and then update your collection using following query ``` collection.update({ "_id":doc._id }, { $pull : { "scores" : { $and: [ {"type":"homework"}, { "score":lowScore} ] } } }, { "safe":true }, function( err, result ) { if (err) { console.log(err); } } // update callback ); ``` for more info you can refer [here](https://gist.github.com/ronasta/4080463)
18,565,356
``` #!/bin/sh URL1=http://runescape.com/title.ws tot=`wget -qO- $URL1 | grep -i PlayerCount | cut -d\> -f4 | cut -d\< -f1 | sed -e's/,//'` URL2=http://oldschool.runescape.com b=`wget -qO- $URL2| grep "people playing" | awk '{print $4}'` a=`expr $tot - $b` export LC_ALL=en_US.UTF-8 a_with_comma=`echo $a | awk "{printf \"%'d\n\", \\$1}"` echo "$a_with_comma people `date '+%r %b %d %Y'`" ``` This grabs 2 numbers from URL1 and URL2 and subtracts URL1 from URL2. Trying to get the "48,877 Players Online Now" from <http://www.runescape.com/title.ws> (URL1) URL2 works fine I just can't get URL1.
2013/09/02
[ "https://Stackoverflow.com/questions/18565356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009123/" ]
``` var dbName = 'school' var tableName = 'classA' MongoClient.connect(dbName, function(err, db) { if (err) { console.log(err); } else { var collection = db.collection(tableName) collection.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) { if (err) { console.log(err); } else{ console.log(result); } }); } }); ```
I think you should do following code for solving issues ``` var lowScore = 9999.9; for ( var i=0; i<doc.scores.length; i++ ) { if ( doc.scores[i].type == "homework" && doc.scores[i].score < lowScore ) { lowScore = doc.scores[i].score; } } ``` and then update your collection using following query ``` collection.update({ "_id":doc._id }, { $pull : { "scores" : { $and: [ {"type":"homework"}, { "score":lowScore} ] } } }, { "safe":true }, function( err, result ) { if (err) { console.log(err); } } // update callback ); ``` for more info you can refer [here](https://gist.github.com/ronasta/4080463)
18,565,356
``` #!/bin/sh URL1=http://runescape.com/title.ws tot=`wget -qO- $URL1 | grep -i PlayerCount | cut -d\> -f4 | cut -d\< -f1 | sed -e's/,//'` URL2=http://oldschool.runescape.com b=`wget -qO- $URL2| grep "people playing" | awk '{print $4}'` a=`expr $tot - $b` export LC_ALL=en_US.UTF-8 a_with_comma=`echo $a | awk "{printf \"%'d\n\", \\$1}"` echo "$a_with_comma people `date '+%r %b %d %Y'`" ``` This grabs 2 numbers from URL1 and URL2 and subtracts URL1 from URL2. Trying to get the "48,877 Players Online Now" from <http://www.runescape.com/title.ws> (URL1) URL2 works fine I just can't get URL1.
2013/09/02
[ "https://Stackoverflow.com/questions/18565356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009123/" ]
I know it's a bit late to help you now, but maybe others can benefit as new cohorts pass through MongoDB University! `db.schools.update` should read `db.students.update`. @tymeJV's answer gives the rest: * Wrap the `$set` inside braces: `{$set:{scores:zz}}` * Add a callback function to catch errors: ``` db.collection( 'students' ).update ( { _id : doc._id }, { $set : { scores:zz } }, function( err, result ) { if ( err ) throw err; } ); ``` Funnily enough, I'm actually doing exactly the same assignment right now! I had a different issue that was answered by reading the docs, but I saw this question while googling for it. Hope I helped someone!
``` var dbName = 'school' var tableName = 'classA' MongoClient.connect(dbName, function(err, db) { if (err) { console.log(err); } else { var collection = db.collection(tableName) collection.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) { if (err) { console.log(err); } else{ console.log(result); } }); } }); ```
16,859,808
Came a cross this fiddle in the Highcharts API doc: <http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/exporting/buttons-text/> ``` printButton: { text: 'Print', onclick: function () { this.print(); } } ``` As you can see from hovering over "print" or "download", the tooltip is undefined. So, my question, simply, where do I define it? Best regards :)
2013/05/31
[ "https://Stackoverflow.com/questions/16859808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289573/" ]
If you want to add custom tooltip text for a button, you must add a 'lang' object in the chart's options, and define a key with some text. Then use that key in the custom button's definition. ``` var chart = new Highcharts.Chart({ chart: { // your chart options }, lang: { yourKey: "Custom button tooltip text" }, exporting: { buttons: { yourCustomButton: { text: "Click me", _titleKey: "yourKey", onclick: function() { // button functionality goes here } } } } }); ``` See <http://jsfiddle.net/7wEEj/>
Add directly `_titleKey`, see: <http://jsfiddle.net/x36qR/1/>
16,859,808
Came a cross this fiddle in the Highcharts API doc: <http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/exporting/buttons-text/> ``` printButton: { text: 'Print', onclick: function () { this.print(); } } ``` As you can see from hovering over "print" or "download", the tooltip is undefined. So, my question, simply, where do I define it? Best regards :)
2013/05/31
[ "https://Stackoverflow.com/questions/16859808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289573/" ]
Add directly `_titleKey`, see: <http://jsfiddle.net/x36qR/1/>
I'd like to add that the lang option works even if the button is not *custom*. For instance, ``` lang: { myKey: "Hello" }, exporting: { buttons: { exportButton: { _titleKey:"myKey", enabled: true }, printButton: { enabled: true } } }, ... ``` gives you the possibility to translate the tooltips of the export and print button.
16,859,808
Came a cross this fiddle in the Highcharts API doc: <http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/exporting/buttons-text/> ``` printButton: { text: 'Print', onclick: function () { this.print(); } } ``` As you can see from hovering over "print" or "download", the tooltip is undefined. So, my question, simply, where do I define it? Best regards :)
2013/05/31
[ "https://Stackoverflow.com/questions/16859808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289573/" ]
If you want to add custom tooltip text for a button, you must add a 'lang' object in the chart's options, and define a key with some text. Then use that key in the custom button's definition. ``` var chart = new Highcharts.Chart({ chart: { // your chart options }, lang: { yourKey: "Custom button tooltip text" }, exporting: { buttons: { yourCustomButton: { text: "Click me", _titleKey: "yourKey", onclick: function() { // button functionality goes here } } } } }); ``` See <http://jsfiddle.net/7wEEj/>
I'd like to add that the lang option works even if the button is not *custom*. For instance, ``` lang: { myKey: "Hello" }, exporting: { buttons: { exportButton: { _titleKey:"myKey", enabled: true }, printButton: { enabled: true } } }, ... ``` gives you the possibility to translate the tooltips of the export and print button.
37,874,939
I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :[Error Message](http://i.stack.imgur.com/OvE2R.jpg) This is the model : ``` public partial class tblArtist { public tblArtist() { this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>(); this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>(); this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>(); this.tblArtistRatings = new HashSet<tblArtistRating>(); this.tblArtistOverviews = new HashSet<tblArtistOverview>(); this.tblArtistSchedules = new HashSet<tblArtistSchedule>(); } public int ArtistId { get; set; } public string ArtistName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string Sex { get; set; } public string HouseNumber { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string Pin { get; set; } public string Email { get; set; } public string Website { get; set; } public string Phone { get; set; } public string Mobile { get; set; } public Nullable<bool> IsActive { get; set; } public Nullable<bool> IsGroup { get; set; } public Nullable<bool> IsFeatured { get; set; } public Nullable<System.DateTime> AddedOn { get; set; } public string AboutMe { get; set; } public Nullable<decimal> MinmumRates { get; set; } public string FB_FanLink { get; set; } public Nullable<int> FK_UserId { get; set; } public Nullable<bool> IsApproved { get; set; } public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; } public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; } public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; } public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; } public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; } public virtual tblUser tblUser { get; set; } public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; } } ``` In Controller page I take a list like : ``` List<tblArtist> artistList = new List<tblArtist>(); ``` This is the query : ``` artistList = (from ta in context.tblArtists join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true select new { ta.AboutMe, ta.AddedOn, ta.Address, ta.ArtistId, ta.ArtistName, ta.City, ta.Country, ta.DateOfBirth, ta.Email, ta.FB_FanLink, ta.FK_UserId, ta.HouseNumber, ta.IsActive, ta.IsApproved, ta.IsFeatured, ta.IsGroup, ta.MinmumRates, ta.Mobile, ta.Phone, ta.Pin, ta.Sex, ta.State, ta.Website }).ToList(); ```
2016/06/17
[ "https://Stackoverflow.com/questions/37874939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4757611/" ]
**UPDATE:** i would strongly recommend to upgrade to pandas 0.18.1 (currently the latest version), as each new version of pandas introduces nice new features and fixes tons of old bugs. And the actual version (0.18.1) will process your empty files just out of the box (see demo below). If you can't upgrade to a newer version, then make use of @MartijnPieters recommendation - catch the exception, instead of checking (follow the [Easier to ask for forgiveness than permission](https://docs.python.org/2/glossary.html#term-eafp) paradigm) **OLD answer:** a small demonstration (using pandas 0.18.1), which tolerates empty files, different number of columns, etc. I tried to reproduce your error (trying empty CSV.gz, different number of columns, etc.), but i didn't manage to reproduce your exception using pandas v. 0.18.1: ``` import os import glob import gzip import pandas as pd fmask = 'd:/temp/.data/37874936/*.csv.gz' files = glob.glob(fmask) cols = ['a','b','c'] for f in files: # actually there is no need to use `compression='gzip'` - pandas will guess it itself # i left it in order to be sure that we are using the same parameters ... df = pd.read_csv(f, header=None, names=cols, compression='gzip', sep=',') print('\nFILE: [{:^40}]'.format(f)) print('{:-^60}'.format(' ORIGINAL contents ')) print(gzip.open(f, 'rt').read()) print('{:-^60}'.format(' parsed DF ')) print(df) ``` Output: ``` FILE: [ d:/temp/.data/37874936\1.csv.gz ] -------------------- ORIGINAL contents --------------------- 11,12,13 14,15,16 ------------------------ parsed DF ------------------------- a b c 0 11 12 13 1 14 15 16 FILE: [ d:/temp/.data/37874936\empty.csv.gz ] -------------------- ORIGINAL contents --------------------- ------------------------ parsed DF ------------------------- Empty DataFrame Columns: [a, b, c] Index: [] FILE: [d:/temp/.data/37874936\zz_5_columns.csv.gz] -------------------- ORIGINAL contents --------------------- 1,2,3,4,5 11,22,33,44,55 ------------------------ parsed DF ------------------------- a b c 1 2 3 4 5 11 22 33 44 55 FILE: [d:/temp/.data/37874936\z_bad_CSV.csv.gz ] -------------------- ORIGINAL contents --------------------- 1 5,6,7 1,2 8,9,10,5,6 ------------------------ parsed DF ------------------------- a b c 0 1 NaN NaN 1 5 6.0 7.0 2 1 2.0 NaN 3 8 9.0 10.0 FILE: [d:/temp/.data/37874936\z_single_column.csv.gz] -------------------- ORIGINAL contents --------------------- 1 2 3 ------------------------ parsed DF ------------------------- a b c 0 1 NaN NaN 1 2 NaN NaN 2 3 NaN NaN ``` Can you post a sample CSV, causing this error or upload it somewhere and post here a link?
Looking through the [source code](https://github.com/python/cpython/blob/2.7/Lib/gzip.py) for the Python 2.7 version of the `gzip` module, it seems to immediately return EOF, not only in the case where the gzipped file is zero bytes, but also in the case that the gzip file is zero bytes, which is arguably a bug. However, for your particular use-case, we can do a little better, by also confirming the gzipped file is a valid CSV file. This code... ``` import csv import gzip # Returns true if the specified filename is a valid gzip'd CSV file # If the optional 'columns' parameter is specified, also check that # the first row has that many columns def is_valid(filename, columns=None): try: # Chain a CSV reader onto a gzip reader csv_file = csv.reader(gzip.open(filename)) # This will try to read the first line # If it's not a valid gzip, this will raise IOError for row in csv_file: # We got at least one row # Bail out here if we don't care how many columns we have if columns is None: return True # Check it has the right number of columns return len(row) == columns else: # There were no rows return False except IOError: # This is not a valid gzip file return False # Example to check whether File.txt.gz is valid result = is_valid('File.txt.gz') # Example to check whether File.txt.gz is valid, and has three columns result = is_valid('File.txt.gz', columns=3) ``` ...should correctly handle the following error cases... 1. The gzip file is zero bytes 2. The gzip file is not a valid gzip file 3. The gzipped file is zero bytes 4. The gzipped file is not zero bytes, but contains no CSV data 5. (Optionally) The gzipped file contains CSV data, but with the wrong number of columns
37,874,939
I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :[Error Message](http://i.stack.imgur.com/OvE2R.jpg) This is the model : ``` public partial class tblArtist { public tblArtist() { this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>(); this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>(); this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>(); this.tblArtistRatings = new HashSet<tblArtistRating>(); this.tblArtistOverviews = new HashSet<tblArtistOverview>(); this.tblArtistSchedules = new HashSet<tblArtistSchedule>(); } public int ArtistId { get; set; } public string ArtistName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string Sex { get; set; } public string HouseNumber { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string Pin { get; set; } public string Email { get; set; } public string Website { get; set; } public string Phone { get; set; } public string Mobile { get; set; } public Nullable<bool> IsActive { get; set; } public Nullable<bool> IsGroup { get; set; } public Nullable<bool> IsFeatured { get; set; } public Nullable<System.DateTime> AddedOn { get; set; } public string AboutMe { get; set; } public Nullable<decimal> MinmumRates { get; set; } public string FB_FanLink { get; set; } public Nullable<int> FK_UserId { get; set; } public Nullable<bool> IsApproved { get; set; } public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; } public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; } public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; } public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; } public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; } public virtual tblUser tblUser { get; set; } public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; } } ``` In Controller page I take a list like : ``` List<tblArtist> artistList = new List<tblArtist>(); ``` This is the query : ``` artistList = (from ta in context.tblArtists join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true select new { ta.AboutMe, ta.AddedOn, ta.Address, ta.ArtistId, ta.ArtistName, ta.City, ta.Country, ta.DateOfBirth, ta.Email, ta.FB_FanLink, ta.FK_UserId, ta.HouseNumber, ta.IsActive, ta.IsApproved, ta.IsFeatured, ta.IsGroup, ta.MinmumRates, ta.Mobile, ta.Phone, ta.Pin, ta.Sex, ta.State, ta.Website }).ToList(); ```
2016/06/17
[ "https://Stackoverflow.com/questions/37874939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4757611/" ]
**UPDATE:** i would strongly recommend to upgrade to pandas 0.18.1 (currently the latest version), as each new version of pandas introduces nice new features and fixes tons of old bugs. And the actual version (0.18.1) will process your empty files just out of the box (see demo below). If you can't upgrade to a newer version, then make use of @MartijnPieters recommendation - catch the exception, instead of checking (follow the [Easier to ask for forgiveness than permission](https://docs.python.org/2/glossary.html#term-eafp) paradigm) **OLD answer:** a small demonstration (using pandas 0.18.1), which tolerates empty files, different number of columns, etc. I tried to reproduce your error (trying empty CSV.gz, different number of columns, etc.), but i didn't manage to reproduce your exception using pandas v. 0.18.1: ``` import os import glob import gzip import pandas as pd fmask = 'd:/temp/.data/37874936/*.csv.gz' files = glob.glob(fmask) cols = ['a','b','c'] for f in files: # actually there is no need to use `compression='gzip'` - pandas will guess it itself # i left it in order to be sure that we are using the same parameters ... df = pd.read_csv(f, header=None, names=cols, compression='gzip', sep=',') print('\nFILE: [{:^40}]'.format(f)) print('{:-^60}'.format(' ORIGINAL contents ')) print(gzip.open(f, 'rt').read()) print('{:-^60}'.format(' parsed DF ')) print(df) ``` Output: ``` FILE: [ d:/temp/.data/37874936\1.csv.gz ] -------------------- ORIGINAL contents --------------------- 11,12,13 14,15,16 ------------------------ parsed DF ------------------------- a b c 0 11 12 13 1 14 15 16 FILE: [ d:/temp/.data/37874936\empty.csv.gz ] -------------------- ORIGINAL contents --------------------- ------------------------ parsed DF ------------------------- Empty DataFrame Columns: [a, b, c] Index: [] FILE: [d:/temp/.data/37874936\zz_5_columns.csv.gz] -------------------- ORIGINAL contents --------------------- 1,2,3,4,5 11,22,33,44,55 ------------------------ parsed DF ------------------------- a b c 1 2 3 4 5 11 22 33 44 55 FILE: [d:/temp/.data/37874936\z_bad_CSV.csv.gz ] -------------------- ORIGINAL contents --------------------- 1 5,6,7 1,2 8,9,10,5,6 ------------------------ parsed DF ------------------------- a b c 0 1 NaN NaN 1 5 6.0 7.0 2 1 2.0 NaN 3 8 9.0 10.0 FILE: [d:/temp/.data/37874936\z_single_column.csv.gz] -------------------- ORIGINAL contents --------------------- 1 2 3 ------------------------ parsed DF ------------------------- a b c 0 1 NaN NaN 1 2 NaN NaN 2 3 NaN NaN ``` Can you post a sample CSV, causing this error or upload it somewhere and post here a link?
``` import gzip with gzip.open("pCSV.csv.gz", 'r') as f: f.seek(3) couterA = f.tell() f.seek(2,0) counterB = f.tell() if(couterA > counterB): print "NOT EMPTY" else: print "EMPTY" ``` This should do it without reading the file.
37,874,939
I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :[Error Message](http://i.stack.imgur.com/OvE2R.jpg) This is the model : ``` public partial class tblArtist { public tblArtist() { this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>(); this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>(); this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>(); this.tblArtistRatings = new HashSet<tblArtistRating>(); this.tblArtistOverviews = new HashSet<tblArtistOverview>(); this.tblArtistSchedules = new HashSet<tblArtistSchedule>(); } public int ArtistId { get; set; } public string ArtistName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string Sex { get; set; } public string HouseNumber { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string Pin { get; set; } public string Email { get; set; } public string Website { get; set; } public string Phone { get; set; } public string Mobile { get; set; } public Nullable<bool> IsActive { get; set; } public Nullable<bool> IsGroup { get; set; } public Nullable<bool> IsFeatured { get; set; } public Nullable<System.DateTime> AddedOn { get; set; } public string AboutMe { get; set; } public Nullable<decimal> MinmumRates { get; set; } public string FB_FanLink { get; set; } public Nullable<int> FK_UserId { get; set; } public Nullable<bool> IsApproved { get; set; } public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; } public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; } public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; } public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; } public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; } public virtual tblUser tblUser { get; set; } public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; } } ``` In Controller page I take a list like : ``` List<tblArtist> artistList = new List<tblArtist>(); ``` This is the query : ``` artistList = (from ta in context.tblArtists join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true select new { ta.AboutMe, ta.AddedOn, ta.Address, ta.ArtistId, ta.ArtistName, ta.City, ta.Country, ta.DateOfBirth, ta.Email, ta.FB_FanLink, ta.FK_UserId, ta.HouseNumber, ta.IsActive, ta.IsApproved, ta.IsFeatured, ta.IsGroup, ta.MinmumRates, ta.Mobile, ta.Phone, ta.Pin, ta.Sex, ta.State, ta.Website }).ToList(); ```
2016/06/17
[ "https://Stackoverflow.com/questions/37874939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4757611/" ]
Unfortunately, the `gzip` module does not expose any functionality equivalent to the `-l` list option of the `gzip` program. But in Python 3 you can easily get the size of the uncompressed data by calling the `.seek` method with a `whence` argument of 2, which signifies positioning relative to the end of the (uncompressed) data stream. `.seek` returns the new byte position, so `.seek(0, 2)` returns the byte offset of the end of the uncompressed file, i.e., the file size. Thus if the uncompressed file is empty the `.seek` call will return 0. ``` import gzip def gz_size(fname): with gzip.open(fname, 'rb') as f: return f.seek(0, whence=2) ``` Here's a function that will work on Python 2, tested on Python 2.6.6. ``` def gz_size(fname): f = gzip.open(fname, 'rb') data = f.read() f.close() return len(data) ``` You can read about `.seek` and other methods of the `GzipFile` class using the `pydoc` program. Just run `pydoc gzip` in the shell. --- Alternatively, if you wish to avoid decompressing the file you can (sort of) read the uncompressed data size directly from the `.gz` file. The size is stored in the last 4 bytes of the file as a little-endian unsigned long, so it's actually the size modulo 2\*\*32, therefore it will not be the true size if the uncompressed data size is >= 4GB. This code works on both Python 2 and Python 3. ``` import gzip import struct def gz_size(fname): with open(fname, 'rb') as f: f.seek(-4, 2) data = f.read(4) size = struct.unpack('<L', data)[0] return size ``` However, this method is not reliable, as Mark Adler (*gzip* co-author) mentions in the comments: > > There are other reasons that the length at the end of the gzip file > would not represent the length of the uncompressed data. (Concatenated > gzip streams, padding at the end of the gzip file.) It should not be > used for this purpose. It's only there as an integrity check on the > data. > > > --- Here is another solution. It does not decompress the whole file. It returns `True` if the uncompressed data in the input file is of zero length, but it also returns `True` if the input file itself is of zero length. If the input file is not of zero length and is not a gzip file then `OSError` is raised. ``` import gzip def gz_is_empty(fname): ''' Test if gzip file fname is empty Return True if the uncompressed data in fname has zero length or if fname itself has zero length Raises OSError if fname has non-zero length and is not a gzip file ''' with gzip.open(fname, 'rb') as f: data = f.read(1) return len(data) == 0 ```
**UPDATE:** i would strongly recommend to upgrade to pandas 0.18.1 (currently the latest version), as each new version of pandas introduces nice new features and fixes tons of old bugs. And the actual version (0.18.1) will process your empty files just out of the box (see demo below). If you can't upgrade to a newer version, then make use of @MartijnPieters recommendation - catch the exception, instead of checking (follow the [Easier to ask for forgiveness than permission](https://docs.python.org/2/glossary.html#term-eafp) paradigm) **OLD answer:** a small demonstration (using pandas 0.18.1), which tolerates empty files, different number of columns, etc. I tried to reproduce your error (trying empty CSV.gz, different number of columns, etc.), but i didn't manage to reproduce your exception using pandas v. 0.18.1: ``` import os import glob import gzip import pandas as pd fmask = 'd:/temp/.data/37874936/*.csv.gz' files = glob.glob(fmask) cols = ['a','b','c'] for f in files: # actually there is no need to use `compression='gzip'` - pandas will guess it itself # i left it in order to be sure that we are using the same parameters ... df = pd.read_csv(f, header=None, names=cols, compression='gzip', sep=',') print('\nFILE: [{:^40}]'.format(f)) print('{:-^60}'.format(' ORIGINAL contents ')) print(gzip.open(f, 'rt').read()) print('{:-^60}'.format(' parsed DF ')) print(df) ``` Output: ``` FILE: [ d:/temp/.data/37874936\1.csv.gz ] -------------------- ORIGINAL contents --------------------- 11,12,13 14,15,16 ------------------------ parsed DF ------------------------- a b c 0 11 12 13 1 14 15 16 FILE: [ d:/temp/.data/37874936\empty.csv.gz ] -------------------- ORIGINAL contents --------------------- ------------------------ parsed DF ------------------------- Empty DataFrame Columns: [a, b, c] Index: [] FILE: [d:/temp/.data/37874936\zz_5_columns.csv.gz] -------------------- ORIGINAL contents --------------------- 1,2,3,4,5 11,22,33,44,55 ------------------------ parsed DF ------------------------- a b c 1 2 3 4 5 11 22 33 44 55 FILE: [d:/temp/.data/37874936\z_bad_CSV.csv.gz ] -------------------- ORIGINAL contents --------------------- 1 5,6,7 1,2 8,9,10,5,6 ------------------------ parsed DF ------------------------- a b c 0 1 NaN NaN 1 5 6.0 7.0 2 1 2.0 NaN 3 8 9.0 10.0 FILE: [d:/temp/.data/37874936\z_single_column.csv.gz] -------------------- ORIGINAL contents --------------------- 1 2 3 ------------------------ parsed DF ------------------------- a b c 0 1 NaN NaN 1 2 NaN NaN 2 3 NaN NaN ``` Can you post a sample CSV, causing this error or upload it somewhere and post here a link?
37,874,939
I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :[Error Message](http://i.stack.imgur.com/OvE2R.jpg) This is the model : ``` public partial class tblArtist { public tblArtist() { this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>(); this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>(); this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>(); this.tblArtistRatings = new HashSet<tblArtistRating>(); this.tblArtistOverviews = new HashSet<tblArtistOverview>(); this.tblArtistSchedules = new HashSet<tblArtistSchedule>(); } public int ArtistId { get; set; } public string ArtistName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string Sex { get; set; } public string HouseNumber { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string Pin { get; set; } public string Email { get; set; } public string Website { get; set; } public string Phone { get; set; } public string Mobile { get; set; } public Nullable<bool> IsActive { get; set; } public Nullable<bool> IsGroup { get; set; } public Nullable<bool> IsFeatured { get; set; } public Nullable<System.DateTime> AddedOn { get; set; } public string AboutMe { get; set; } public Nullable<decimal> MinmumRates { get; set; } public string FB_FanLink { get; set; } public Nullable<int> FK_UserId { get; set; } public Nullable<bool> IsApproved { get; set; } public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; } public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; } public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; } public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; } public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; } public virtual tblUser tblUser { get; set; } public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; } } ``` In Controller page I take a list like : ``` List<tblArtist> artistList = new List<tblArtist>(); ``` This is the query : ``` artistList = (from ta in context.tblArtists join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true select new { ta.AboutMe, ta.AddedOn, ta.Address, ta.ArtistId, ta.ArtistName, ta.City, ta.Country, ta.DateOfBirth, ta.Email, ta.FB_FanLink, ta.FK_UserId, ta.HouseNumber, ta.IsActive, ta.IsApproved, ta.IsFeatured, ta.IsGroup, ta.MinmumRates, ta.Mobile, ta.Phone, ta.Pin, ta.Sex, ta.State, ta.Website }).ToList(); ```
2016/06/17
[ "https://Stackoverflow.com/questions/37874939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4757611/" ]
``` import gzip with gzip.open("pCSV.csv.gz", 'r') as f: f.seek(3) couterA = f.tell() f.seek(2,0) counterB = f.tell() if(couterA > counterB): print "NOT EMPTY" else: print "EMPTY" ``` This should do it without reading the file.
I had a few hundred thousand gzip files, only a few of which are zero-sized, mounted on a network share. I was forced to use the following optimization. It is brittle, but in the (very frequent) case in which you have a large number of files generated using the same method, the sum of all the bytes other than the name of the payload are a constant. Then you can check for a zero-sized payload by: 1. Computing that constant over **one** file. [You can code it up](https://stackoverflow.com/a/33592860/414125), but I find it simpler to just use command-line gzip (and this whole answer is an ugly hack anyway). 2. examining only the inode for the rest of the files, instead of opening each file, which can be orders of magnitude faster: ``` from os import stat from os.path import basename # YMMV with len_minus_file_name def is_gzip_empty(file_name, len_minus_file_name=23): return os.stat(file_name).st_size - len(basename(file_name)) == len_minus_file_name ``` This could break in many ways. Caveat emptor. Only use it if other methods are not practical.
37,874,939
I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :[Error Message](http://i.stack.imgur.com/OvE2R.jpg) This is the model : ``` public partial class tblArtist { public tblArtist() { this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>(); this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>(); this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>(); this.tblArtistRatings = new HashSet<tblArtistRating>(); this.tblArtistOverviews = new HashSet<tblArtistOverview>(); this.tblArtistSchedules = new HashSet<tblArtistSchedule>(); } public int ArtistId { get; set; } public string ArtistName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string Sex { get; set; } public string HouseNumber { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string Pin { get; set; } public string Email { get; set; } public string Website { get; set; } public string Phone { get; set; } public string Mobile { get; set; } public Nullable<bool> IsActive { get; set; } public Nullable<bool> IsGroup { get; set; } public Nullable<bool> IsFeatured { get; set; } public Nullable<System.DateTime> AddedOn { get; set; } public string AboutMe { get; set; } public Nullable<decimal> MinmumRates { get; set; } public string FB_FanLink { get; set; } public Nullable<int> FK_UserId { get; set; } public Nullable<bool> IsApproved { get; set; } public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; } public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; } public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; } public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; } public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; } public virtual tblUser tblUser { get; set; } public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; } } ``` In Controller page I take a list like : ``` List<tblArtist> artistList = new List<tblArtist>(); ``` This is the query : ``` artistList = (from ta in context.tblArtists join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true select new { ta.AboutMe, ta.AddedOn, ta.Address, ta.ArtistId, ta.ArtistName, ta.City, ta.Country, ta.DateOfBirth, ta.Email, ta.FB_FanLink, ta.FK_UserId, ta.HouseNumber, ta.IsActive, ta.IsApproved, ta.IsFeatured, ta.IsGroup, ta.MinmumRates, ta.Mobile, ta.Phone, ta.Pin, ta.Sex, ta.State, ta.Website }).ToList(); ```
2016/06/17
[ "https://Stackoverflow.com/questions/37874939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4757611/" ]
If you want to check whether a file is a valid Gzip file, you can open it and read one byte from it. If it succeeds, the file is quite probably a gzip file, with one caveat: an *empty* file also succeeds this test. Thus we get ``` def is_gz_file(name): with gzip.open(name, 'rb') as f: try: file_content = f.read(1) return True except: return False ``` However, as I stated earlier, a file which is empty (0 bytes), still succeeds this test, so you'd perhaps want to ensure that the file is not empty: ``` def is_gz_file(name): if os.stat(name).ST_SIZE == 0: return False with gzip.open(name, 'rb') as f: try: file_content = f.read(1) return True except: return False ``` EDIT: as the question was now changed to "a gzip file that doesn't have empty contents", then: ``` def is_nonempty_gz_file(name): with gzip.open(name, 'rb') as f: try: file_content = f.read(1) return len(file_content) > 0 except: return False ```
I had a few hundred thousand gzip files, only a few of which are zero-sized, mounted on a network share. I was forced to use the following optimization. It is brittle, but in the (very frequent) case in which you have a large number of files generated using the same method, the sum of all the bytes other than the name of the payload are a constant. Then you can check for a zero-sized payload by: 1. Computing that constant over **one** file. [You can code it up](https://stackoverflow.com/a/33592860/414125), but I find it simpler to just use command-line gzip (and this whole answer is an ugly hack anyway). 2. examining only the inode for the rest of the files, instead of opening each file, which can be orders of magnitude faster: ``` from os import stat from os.path import basename # YMMV with len_minus_file_name def is_gzip_empty(file_name, len_minus_file_name=23): return os.stat(file_name).st_size - len(basename(file_name)) == len_minus_file_name ``` This could break in many ways. Caveat emptor. Only use it if other methods are not practical.
37,874,939
I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :[Error Message](http://i.stack.imgur.com/OvE2R.jpg) This is the model : ``` public partial class tblArtist { public tblArtist() { this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>(); this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>(); this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>(); this.tblArtistRatings = new HashSet<tblArtistRating>(); this.tblArtistOverviews = new HashSet<tblArtistOverview>(); this.tblArtistSchedules = new HashSet<tblArtistSchedule>(); } public int ArtistId { get; set; } public string ArtistName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string Sex { get; set; } public string HouseNumber { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string Pin { get; set; } public string Email { get; set; } public string Website { get; set; } public string Phone { get; set; } public string Mobile { get; set; } public Nullable<bool> IsActive { get; set; } public Nullable<bool> IsGroup { get; set; } public Nullable<bool> IsFeatured { get; set; } public Nullable<System.DateTime> AddedOn { get; set; } public string AboutMe { get; set; } public Nullable<decimal> MinmumRates { get; set; } public string FB_FanLink { get; set; } public Nullable<int> FK_UserId { get; set; } public Nullable<bool> IsApproved { get; set; } public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; } public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; } public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; } public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; } public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; } public virtual tblUser tblUser { get; set; } public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; } } ``` In Controller page I take a list like : ``` List<tblArtist> artistList = new List<tblArtist>(); ``` This is the query : ``` artistList = (from ta in context.tblArtists join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true select new { ta.AboutMe, ta.AddedOn, ta.Address, ta.ArtistId, ta.ArtistName, ta.City, ta.Country, ta.DateOfBirth, ta.Email, ta.FB_FanLink, ta.FK_UserId, ta.HouseNumber, ta.IsActive, ta.IsApproved, ta.IsFeatured, ta.IsGroup, ta.MinmumRates, ta.Mobile, ta.Phone, ta.Pin, ta.Sex, ta.State, ta.Website }).ToList(); ```
2016/06/17
[ "https://Stackoverflow.com/questions/37874939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4757611/" ]
Try something like this: ``` def is_empty(gzfile): size = gzfile.read(). if len(size) > 0: gzfile.rewind() return False else: return True ```
I had a few hundred thousand gzip files, only a few of which are zero-sized, mounted on a network share. I was forced to use the following optimization. It is brittle, but in the (very frequent) case in which you have a large number of files generated using the same method, the sum of all the bytes other than the name of the payload are a constant. Then you can check for a zero-sized payload by: 1. Computing that constant over **one** file. [You can code it up](https://stackoverflow.com/a/33592860/414125), but I find it simpler to just use command-line gzip (and this whole answer is an ugly hack anyway). 2. examining only the inode for the rest of the files, instead of opening each file, which can be orders of magnitude faster: ``` from os import stat from os.path import basename # YMMV with len_minus_file_name def is_gzip_empty(file_name, len_minus_file_name=23): return os.stat(file_name).st_size - len(basename(file_name)) == len_minus_file_name ``` This could break in many ways. Caveat emptor. Only use it if other methods are not practical.
37,874,939
I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :[Error Message](http://i.stack.imgur.com/OvE2R.jpg) This is the model : ``` public partial class tblArtist { public tblArtist() { this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>(); this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>(); this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>(); this.tblArtistRatings = new HashSet<tblArtistRating>(); this.tblArtistOverviews = new HashSet<tblArtistOverview>(); this.tblArtistSchedules = new HashSet<tblArtistSchedule>(); } public int ArtistId { get; set; } public string ArtistName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string Sex { get; set; } public string HouseNumber { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string Pin { get; set; } public string Email { get; set; } public string Website { get; set; } public string Phone { get; set; } public string Mobile { get; set; } public Nullable<bool> IsActive { get; set; } public Nullable<bool> IsGroup { get; set; } public Nullable<bool> IsFeatured { get; set; } public Nullable<System.DateTime> AddedOn { get; set; } public string AboutMe { get; set; } public Nullable<decimal> MinmumRates { get; set; } public string FB_FanLink { get; set; } public Nullable<int> FK_UserId { get; set; } public Nullable<bool> IsApproved { get; set; } public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; } public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; } public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; } public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; } public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; } public virtual tblUser tblUser { get; set; } public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; } } ``` In Controller page I take a list like : ``` List<tblArtist> artistList = new List<tblArtist>(); ``` This is the query : ``` artistList = (from ta in context.tblArtists join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true select new { ta.AboutMe, ta.AddedOn, ta.Address, ta.ArtistId, ta.ArtistName, ta.City, ta.Country, ta.DateOfBirth, ta.Email, ta.FB_FanLink, ta.FK_UserId, ta.HouseNumber, ta.IsActive, ta.IsApproved, ta.IsFeatured, ta.IsGroup, ta.MinmumRates, ta.Mobile, ta.Phone, ta.Pin, ta.Sex, ta.State, ta.Website }).ToList(); ```
2016/06/17
[ "https://Stackoverflow.com/questions/37874939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4757611/" ]
If you want to check whether a file is a valid Gzip file, you can open it and read one byte from it. If it succeeds, the file is quite probably a gzip file, with one caveat: an *empty* file also succeeds this test. Thus we get ``` def is_gz_file(name): with gzip.open(name, 'rb') as f: try: file_content = f.read(1) return True except: return False ``` However, as I stated earlier, a file which is empty (0 bytes), still succeeds this test, so you'd perhaps want to ensure that the file is not empty: ``` def is_gz_file(name): if os.stat(name).ST_SIZE == 0: return False with gzip.open(name, 'rb') as f: try: file_content = f.read(1) return True except: return False ``` EDIT: as the question was now changed to "a gzip file that doesn't have empty contents", then: ``` def is_nonempty_gz_file(name): with gzip.open(name, 'rb') as f: try: file_content = f.read(1) return len(file_content) > 0 except: return False ```
Try something like this: ``` def is_empty(gzfile): size = gzfile.read(). if len(size) > 0: gzfile.rewind() return False else: return True ```
37,874,939
I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :[Error Message](http://i.stack.imgur.com/OvE2R.jpg) This is the model : ``` public partial class tblArtist { public tblArtist() { this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>(); this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>(); this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>(); this.tblArtistRatings = new HashSet<tblArtistRating>(); this.tblArtistOverviews = new HashSet<tblArtistOverview>(); this.tblArtistSchedules = new HashSet<tblArtistSchedule>(); } public int ArtistId { get; set; } public string ArtistName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string Sex { get; set; } public string HouseNumber { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string Pin { get; set; } public string Email { get; set; } public string Website { get; set; } public string Phone { get; set; } public string Mobile { get; set; } public Nullable<bool> IsActive { get; set; } public Nullable<bool> IsGroup { get; set; } public Nullable<bool> IsFeatured { get; set; } public Nullable<System.DateTime> AddedOn { get; set; } public string AboutMe { get; set; } public Nullable<decimal> MinmumRates { get; set; } public string FB_FanLink { get; set; } public Nullable<int> FK_UserId { get; set; } public Nullable<bool> IsApproved { get; set; } public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; } public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; } public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; } public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; } public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; } public virtual tblUser tblUser { get; set; } public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; } } ``` In Controller page I take a list like : ``` List<tblArtist> artistList = new List<tblArtist>(); ``` This is the query : ``` artistList = (from ta in context.tblArtists join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true select new { ta.AboutMe, ta.AddedOn, ta.Address, ta.ArtistId, ta.ArtistName, ta.City, ta.Country, ta.DateOfBirth, ta.Email, ta.FB_FanLink, ta.FK_UserId, ta.HouseNumber, ta.IsActive, ta.IsApproved, ta.IsFeatured, ta.IsGroup, ta.MinmumRates, ta.Mobile, ta.Phone, ta.Pin, ta.Sex, ta.State, ta.Website }).ToList(); ```
2016/06/17
[ "https://Stackoverflow.com/questions/37874939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4757611/" ]
Unfortunately, any such attempt will likely have a fair bit of overhead, it would likely be cheaper to catch the exception, such as users commented above. A [gzip](http://www.zlib.org/rfc-gzip.html#member-format) file defines a few fixed size regions, as follows: **Fixed Regions** First, there are 2 bytes for the Gzip magic number, 1 byte for the compression method, 1 byte for the flags, then 4 more bytes for the MTIME (file creation time), 2 bytes for extra flags, and two more bytes for the operating system, giving us a total of 12 bytes so far. This looks as follows (from the link above): ``` +---+---+---+---+---+---+---+---+---+---+ |ID1|ID2|CM |FLG| MTIME |XFL|OS | (more-->) +---+---+---+---+---+---+---+---+---+---+ ``` **Variable Regions** However, this is where things get tricky (and impossible to check without using a gzip module or another deflator). If extra fields were set, there is a variable region of XLEN bytes set afterwards, which looks as follows: ``` (if FLG.FEXTRA set) +---+---+=================================+ | XLEN |...XLEN bytes of "extra field"...| (more-->) +---+---+=================================+ ``` After this, there is then a region of N bytes, with a zero-terminated string for the file name (which is, by default, stored): ``` (if FLG.FNAME set) +=========================================+ |...original file name, zero-terminated...| (more-->) +=========================================+ ``` We then have comments: ``` (if FLG.FCOMMENT set) +===================================+ |...file comment, zero-terminated...| (more-->) +===================================+ ``` And finally, a CRC16 (a cyclic redundancy check, in order to make sure the file header then works, all before we get into the variable, compressed data. **Solution** So, any sort of fixed size check will be dependent on whether the filename, or if it was written via pipe (`gzip -c "Compress this data" > myfile.gz`), other fields, and comments, all which can be defined for null files. So, how do we get around this? Simple, use the gzip module: ``` import gzip def check_null(path): ''' Returns an empty string for a null file, which is falsey, and returns a non-empty string otherwise (which is truthey) ''' with gzip.GzipFile(path, 'rb') as f: return f.read(1) ``` This will check if any data exists inside the created file, while only reading a small section of the data. However, this takes a while, it's easier to ask for forgiveness than ask permission. ``` import contextlib # python3 only, use a try/except block for Py2 import pandas as pd with contexlib.suppress(pd.parser.CParserError as error): df = pd.read_csv(path, compression='gzip', names={'a', 'b', 'c'}, header=False) # do something here ```
I had a few hundred thousand gzip files, only a few of which are zero-sized, mounted on a network share. I was forced to use the following optimization. It is brittle, but in the (very frequent) case in which you have a large number of files generated using the same method, the sum of all the bytes other than the name of the payload are a constant. Then you can check for a zero-sized payload by: 1. Computing that constant over **one** file. [You can code it up](https://stackoverflow.com/a/33592860/414125), but I find it simpler to just use command-line gzip (and this whole answer is an ugly hack anyway). 2. examining only the inode for the rest of the files, instead of opening each file, which can be orders of magnitude faster: ``` from os import stat from os.path import basename # YMMV with len_minus_file_name def is_gzip_empty(file_name, len_minus_file_name=23): return os.stat(file_name).st_size - len(basename(file_name)) == len_minus_file_name ``` This could break in many ways. Caveat emptor. Only use it if other methods are not practical.
37,874,939
I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :[Error Message](http://i.stack.imgur.com/OvE2R.jpg) This is the model : ``` public partial class tblArtist { public tblArtist() { this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>(); this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>(); this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>(); this.tblArtistRatings = new HashSet<tblArtistRating>(); this.tblArtistOverviews = new HashSet<tblArtistOverview>(); this.tblArtistSchedules = new HashSet<tblArtistSchedule>(); } public int ArtistId { get; set; } public string ArtistName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string Sex { get; set; } public string HouseNumber { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string Pin { get; set; } public string Email { get; set; } public string Website { get; set; } public string Phone { get; set; } public string Mobile { get; set; } public Nullable<bool> IsActive { get; set; } public Nullable<bool> IsGroup { get; set; } public Nullable<bool> IsFeatured { get; set; } public Nullable<System.DateTime> AddedOn { get; set; } public string AboutMe { get; set; } public Nullable<decimal> MinmumRates { get; set; } public string FB_FanLink { get; set; } public Nullable<int> FK_UserId { get; set; } public Nullable<bool> IsApproved { get; set; } public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; } public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; } public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; } public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; } public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; } public virtual tblUser tblUser { get; set; } public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; } } ``` In Controller page I take a list like : ``` List<tblArtist> artistList = new List<tblArtist>(); ``` This is the query : ``` artistList = (from ta in context.tblArtists join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true select new { ta.AboutMe, ta.AddedOn, ta.Address, ta.ArtistId, ta.ArtistName, ta.City, ta.Country, ta.DateOfBirth, ta.Email, ta.FB_FanLink, ta.FK_UserId, ta.HouseNumber, ta.IsActive, ta.IsApproved, ta.IsFeatured, ta.IsGroup, ta.MinmumRates, ta.Mobile, ta.Phone, ta.Pin, ta.Sex, ta.State, ta.Website }).ToList(); ```
2016/06/17
[ "https://Stackoverflow.com/questions/37874939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4757611/" ]
Unfortunately, the `gzip` module does not expose any functionality equivalent to the `-l` list option of the `gzip` program. But in Python 3 you can easily get the size of the uncompressed data by calling the `.seek` method with a `whence` argument of 2, which signifies positioning relative to the end of the (uncompressed) data stream. `.seek` returns the new byte position, so `.seek(0, 2)` returns the byte offset of the end of the uncompressed file, i.e., the file size. Thus if the uncompressed file is empty the `.seek` call will return 0. ``` import gzip def gz_size(fname): with gzip.open(fname, 'rb') as f: return f.seek(0, whence=2) ``` Here's a function that will work on Python 2, tested on Python 2.6.6. ``` def gz_size(fname): f = gzip.open(fname, 'rb') data = f.read() f.close() return len(data) ``` You can read about `.seek` and other methods of the `GzipFile` class using the `pydoc` program. Just run `pydoc gzip` in the shell. --- Alternatively, if you wish to avoid decompressing the file you can (sort of) read the uncompressed data size directly from the `.gz` file. The size is stored in the last 4 bytes of the file as a little-endian unsigned long, so it's actually the size modulo 2\*\*32, therefore it will not be the true size if the uncompressed data size is >= 4GB. This code works on both Python 2 and Python 3. ``` import gzip import struct def gz_size(fname): with open(fname, 'rb') as f: f.seek(-4, 2) data = f.read(4) size = struct.unpack('<L', data)[0] return size ``` However, this method is not reliable, as Mark Adler (*gzip* co-author) mentions in the comments: > > There are other reasons that the length at the end of the gzip file > would not represent the length of the uncompressed data. (Concatenated > gzip streams, padding at the end of the gzip file.) It should not be > used for this purpose. It's only there as an integrity check on the > data. > > > --- Here is another solution. It does not decompress the whole file. It returns `True` if the uncompressed data in the input file is of zero length, but it also returns `True` if the input file itself is of zero length. If the input file is not of zero length and is not a gzip file then `OSError` is raised. ``` import gzip def gz_is_empty(fname): ''' Test if gzip file fname is empty Return True if the uncompressed data in fname has zero length or if fname itself has zero length Raises OSError if fname has non-zero length and is not a gzip file ''' with gzip.open(fname, 'rb') as f: data = f.read(1) return len(data) == 0 ```
If you want to check whether a file is a valid Gzip file, you can open it and read one byte from it. If it succeeds, the file is quite probably a gzip file, with one caveat: an *empty* file also succeeds this test. Thus we get ``` def is_gz_file(name): with gzip.open(name, 'rb') as f: try: file_content = f.read(1) return True except: return False ``` However, as I stated earlier, a file which is empty (0 bytes), still succeeds this test, so you'd perhaps want to ensure that the file is not empty: ``` def is_gz_file(name): if os.stat(name).ST_SIZE == 0: return False with gzip.open(name, 'rb') as f: try: file_content = f.read(1) return True except: return False ``` EDIT: as the question was now changed to "a gzip file that doesn't have empty contents", then: ``` def is_nonempty_gz_file(name): with gzip.open(name, 'rb') as f: try: file_content = f.read(1) return len(file_content) > 0 except: return False ```
37,874,939
I can take value of this query in a variable but when I am trying to take value of this query in the "artistList " it shows error :[Error Message](http://i.stack.imgur.com/OvE2R.jpg) This is the model : ``` public partial class tblArtist { public tblArtist() { this.tblArtistCategoryMappings = new HashSet<tblArtistCategoryMapping>(); this.tblArtistGroupMembers = new HashSet<tblArtistGroupMember>(); this.tblArtistPortfolios = new HashSet<tblArtistPortfolio>(); this.tblArtistRatings = new HashSet<tblArtistRating>(); this.tblArtistOverviews = new HashSet<tblArtistOverview>(); this.tblArtistSchedules = new HashSet<tblArtistSchedule>(); } public int ArtistId { get; set; } public string ArtistName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string Sex { get; set; } public string HouseNumber { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string Pin { get; set; } public string Email { get; set; } public string Website { get; set; } public string Phone { get; set; } public string Mobile { get; set; } public Nullable<bool> IsActive { get; set; } public Nullable<bool> IsGroup { get; set; } public Nullable<bool> IsFeatured { get; set; } public Nullable<System.DateTime> AddedOn { get; set; } public string AboutMe { get; set; } public Nullable<decimal> MinmumRates { get; set; } public string FB_FanLink { get; set; } public Nullable<int> FK_UserId { get; set; } public Nullable<bool> IsApproved { get; set; } public virtual ICollection<tblArtistCategoryMapping> tblArtistCategoryMappings { get; set; } public virtual ICollection<tblArtistGroupMember> tblArtistGroupMembers { get; set; } public virtual ICollection<tblArtistPortfolio> tblArtistPortfolios { get; set; } public virtual ICollection<tblArtistRating> tblArtistRatings { get; set; } public virtual ICollection<tblArtistOverview> tblArtistOverviews { get; set; } public virtual tblUser tblUser { get; set; } public virtual ICollection<tblArtistSchedule> tblArtistSchedules { get; set; } } ``` In Controller page I take a list like : ``` List<tblArtist> artistList = new List<tblArtist>(); ``` This is the query : ``` artistList = (from ta in context.tblArtists join tm in context.tblArtistCategoryMappings on ta.ArtistId equals tm.FK_ArtistId join tc in context.tblArtistCategories on tm.FK_CategoryId equals tc.ArtistCategoryId join tct in context.tblArtistCategoryTypes on tc.FK_ArtistCategoryTypeId equals tct.ArtistCategoryTypeId where tct.ArtistCategoryTypeId == TypesId && ta.IsFeatured == true select new { ta.AboutMe, ta.AddedOn, ta.Address, ta.ArtistId, ta.ArtistName, ta.City, ta.Country, ta.DateOfBirth, ta.Email, ta.FB_FanLink, ta.FK_UserId, ta.HouseNumber, ta.IsActive, ta.IsApproved, ta.IsFeatured, ta.IsGroup, ta.MinmumRates, ta.Mobile, ta.Phone, ta.Pin, ta.Sex, ta.State, ta.Website }).ToList(); ```
2016/06/17
[ "https://Stackoverflow.com/questions/37874939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4757611/" ]
**UPDATE:** i would strongly recommend to upgrade to pandas 0.18.1 (currently the latest version), as each new version of pandas introduces nice new features and fixes tons of old bugs. And the actual version (0.18.1) will process your empty files just out of the box (see demo below). If you can't upgrade to a newer version, then make use of @MartijnPieters recommendation - catch the exception, instead of checking (follow the [Easier to ask for forgiveness than permission](https://docs.python.org/2/glossary.html#term-eafp) paradigm) **OLD answer:** a small demonstration (using pandas 0.18.1), which tolerates empty files, different number of columns, etc. I tried to reproduce your error (trying empty CSV.gz, different number of columns, etc.), but i didn't manage to reproduce your exception using pandas v. 0.18.1: ``` import os import glob import gzip import pandas as pd fmask = 'd:/temp/.data/37874936/*.csv.gz' files = glob.glob(fmask) cols = ['a','b','c'] for f in files: # actually there is no need to use `compression='gzip'` - pandas will guess it itself # i left it in order to be sure that we are using the same parameters ... df = pd.read_csv(f, header=None, names=cols, compression='gzip', sep=',') print('\nFILE: [{:^40}]'.format(f)) print('{:-^60}'.format(' ORIGINAL contents ')) print(gzip.open(f, 'rt').read()) print('{:-^60}'.format(' parsed DF ')) print(df) ``` Output: ``` FILE: [ d:/temp/.data/37874936\1.csv.gz ] -------------------- ORIGINAL contents --------------------- 11,12,13 14,15,16 ------------------------ parsed DF ------------------------- a b c 0 11 12 13 1 14 15 16 FILE: [ d:/temp/.data/37874936\empty.csv.gz ] -------------------- ORIGINAL contents --------------------- ------------------------ parsed DF ------------------------- Empty DataFrame Columns: [a, b, c] Index: [] FILE: [d:/temp/.data/37874936\zz_5_columns.csv.gz] -------------------- ORIGINAL contents --------------------- 1,2,3,4,5 11,22,33,44,55 ------------------------ parsed DF ------------------------- a b c 1 2 3 4 5 11 22 33 44 55 FILE: [d:/temp/.data/37874936\z_bad_CSV.csv.gz ] -------------------- ORIGINAL contents --------------------- 1 5,6,7 1,2 8,9,10,5,6 ------------------------ parsed DF ------------------------- a b c 0 1 NaN NaN 1 5 6.0 7.0 2 1 2.0 NaN 3 8 9.0 10.0 FILE: [d:/temp/.data/37874936\z_single_column.csv.gz] -------------------- ORIGINAL contents --------------------- 1 2 3 ------------------------ parsed DF ------------------------- a b c 0 1 NaN NaN 1 2 NaN NaN 2 3 NaN NaN ``` Can you post a sample CSV, causing this error or upload it somewhere and post here a link?
I had a few hundred thousand gzip files, only a few of which are zero-sized, mounted on a network share. I was forced to use the following optimization. It is brittle, but in the (very frequent) case in which you have a large number of files generated using the same method, the sum of all the bytes other than the name of the payload are a constant. Then you can check for a zero-sized payload by: 1. Computing that constant over **one** file. [You can code it up](https://stackoverflow.com/a/33592860/414125), but I find it simpler to just use command-line gzip (and this whole answer is an ugly hack anyway). 2. examining only the inode for the rest of the files, instead of opening each file, which can be orders of magnitude faster: ``` from os import stat from os.path import basename # YMMV with len_minus_file_name def is_gzip_empty(file_name, len_minus_file_name=23): return os.stat(file_name).st_size - len(basename(file_name)) == len_minus_file_name ``` This could break in many ways. Caveat emptor. Only use it if other methods are not practical.
67,358,520
I have a long string in R with a series of values that have this pattern: ``` list <- '{s:K_01.01, y:01}="whatever" and {s:K_02.01, y:02}="whatever" and {s:K_03.01, y:03}="whatever" and {s:K_01.01, y:01}="whatever2" and {s:K_01.01, y:01}="whatever3"' ``` I would like to extract and store in a data frame one column with all the strings that start with **{s:K\_01.01** and end with **"**, and disregard all the other strings. ### Expected output: ``` {s:K_01.01, y:01}="whatever" {s:K_01.01, y:01}="whatever2" {s:K_01.01, y:01}="whatever3" ``` Does anyone know how?
2021/05/02
[ "https://Stackoverflow.com/questions/67358520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7845823/" ]
You can extract all the matching using a pattern ``` {s:K_01\.01[^{}]*}="[^"]+" ``` * `{s:K_01\.01` Match a string that starts with `{s:K_01.01` * `[^{}]*}=` Match any char except `{` or `}` and match `}=` * `"[^"]+"` Match from `"` till `"` [See a regex demo](https://regex101.com/r/Gat1m3/1) | [R demo](https://ideone.com/fr1xnR) ``` library(stringr) list <- '{s:K_01.01, y:01}="whatever" and {s:K_02.01, y:02}="whatever" and {s:K_03.01, y:03}="whatever" and {s:K_01.01, y:01}="whatever2" and {s:K_01.01, y:01}="whatever3"' str_extract_all(list, "\\{s:K_01\\.01[^\\{}]*\\}=\"[^\"]+\"") ``` Output ``` [[1]] [1] "{s:K_01.01, y:01}=\"whatever\"" "{s:K_01.01, y:01}=\"whatever2\"" [3] "{s:K_01.01, y:01}=\"whatever3\"" ```
A base R approach: ``` list <- '{s:K_01.01, y:01}="whatever" and {s:K_02.01, y:02}="whatever" and {s:K_03.01, y:03}="whatever" and {s:K_01.01, y:01}="whatever2" and {s:K_01.01, y:01}="whatever3"' regmatches(list, gregexpr("\\{s:K_01\\.01.*?\\}=\".*?\"", list))[[1]] [1] "{s:K_01.01, y:01}=\"whatever\"" "{s:K_01.01, y:01}=\"whatever2\"" [3] "{s:K_01.01, y:01}=\"whatever3\"" ```
12,856,559
My new component (TComponent) uses DsgnIntf since I use custom property editors. The problem is when using the component in a custom VCL application - DSGNINTF.DCU not found! One solution is to add a command line switch to a compiler (dont remember any more what is it), but I don't like that solution. The second solution is a unit segregation. I found this: <http://edn.embarcadero.com/article/27717> The problem is - I don't understand this article so well.. I don't know what exactly I need to do in my component unit to separate design-time from runtime code. Could someone please make the simplest example and explain it? I just want to avoid problems with "dsgnintf.dcu not found" when people using my component. Thank you. EDIT: I looked the article a bit more and I realize the second unit registers the first one. To avoid dsgnintf.dcu problem I presume the second unit must be in it's own .pas file?
2012/10/12
[ "https://Stackoverflow.com/questions/12856559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659758/" ]
Usually you create a single unit to register your package in IDE, something like that: ``` unit RegPackage; interface uses Classes, MyUnit; procedure Register; implementation procedure Register; begin RegisterComponents('MyPage', [TMyComponent]); end; end. ``` and include this unit into design-only package: ``` package MyPackD; {$R *.res} .. requires rtl, MyPackR; // your runtime package contains RegPackage in 'RegPackage.pas'; end. ``` The article you link covers also property editors. All package code not related to IDE should be contained in run-only package: ``` package MyPackR; {$R *.res} .. requires rtl, vcl; contains MyUnit in 'MyUnit.pas'; end. ```
You must separate your run-time code and design-time code into separate packages. Create a runtime-only package that contains just your component code. Create a designtime-only package that specifies your runtime-only package and the IDE's `DesignIDE` package in its `requires` list, and contains just your property editor and registration code. Then you can install the designtime-only package into the IDE, and refer to the runtime-only package in your projects. The `DesignIDE` package resolves the `DsgnInf` reference, but it is **NOT** allowed to be linked into runtime executables! It is for the IDE's use only.
57,004,193
I'm making a music app, and I'm trying to search my storage for songs and then display the cover art on the layout. I'm already able to display the song name and album. ``` private void loadSongs() { Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; //String selection = Cursor cursor = getContentResolver().query(uri, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { do { String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)); String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)); String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)); String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); Song newSong = new Song(name, artist, album, url); songs.add(newSong); displaySongs.add(name + "\n" + album + "\n" + artist + "\n" + url); } while (cursor.moveToNext()); } cursor.close(); } } public void showSongs() { listView = (ListView) findViewById(R.id.ListView); displaySongs = new ArrayList<>(); loadSongs(); adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, displaySongs); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } }); } ```
2019/07/12
[ "https://Stackoverflow.com/questions/57004193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11774694/" ]
Yes, you can. You'd basically need to get the image from the URI and set it to an `ImageView`. I'd probably recommend you to use a image loading library like [Glide](https://github.com/bumptech/glide) or [Picasso](https://github.com/square/picasso) to reduce the boilerplate code and not have to worry about caching and stuff.
Yes you must get the Uri or the Url of the image location. I suggest you to use [Glide](https://github.com/bumptech/glide) to load the image into an ImageView. First import Glide in your `module:app` ``` dependencies { ... //Glide implementation 'com.github.bumptech.glide:glide:4.9.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0' } ``` To use Glide : ``` Glide.with(context).load(url).into(imageView); ```
18,265
**TL;DR:** I drive to work at my own expense. My friend gets a free ride from me, saving her money and time. I say "don't be late" sometimes, and she freaks out. --- So I live in a metropolitan area and have a vehicle. I have a friend/coworker who ditched her car when she moved here so she takes the metro by default. She has been late before but I have too, and I have a history of oversleeping as I am a heavy sleeper. Sometimes, and infrequently, I will simply say when I will plan on picking her up from the metro (as she takes a much shorter metro ride to my place to get carpool ride vs taking the metro all the way to work) so will say something like "I'm leaving at 600. Don't be late!". For whatever reason, she freaks out that I have the audacity to say "don't be late" when I have overslept before, which I said last night and overslept today. I tried to explain that I'm not being a hypocrite and only say it as a friendly reminder, as we are not infallible but she's not having it. Some details: * I have a car, she does not * My commute is 20-30 min in my vehicle, her commute on metro is about an hour, her commute when carpooling is about 25-35 min (short metro ride and then carpool) * I spend a minimum of $70 in gas a month just commuting, she would spent at most $160 a month ($8 round trip per day x ~20 work days in a month) BUT she's part of a subsidy program for mass transit users which has a max allowance of $245/mo but I don't know how much she's receiving. * She does not pay me anything, ever. I don't ask but she never offers anything more than a "thanks". * Half the time, she doesn't even ride home with me because she decides to stay later to build credit hours at work or will make me wait for her * I was a GS-07 and she is a GS-09 (roughly $45k/year and $55k/year respectively, but I am a 09 now and she is becoming an 11 ($55 and $65 respectively). This is only relevant because she complains about money and not being able to afford the metro (despite the subsidy). * She also has another coworker that gives her rides (same situation but he lives close enough that he picks her up directly and she doesn't need the short metro ride over). It's not my fault she **GAVE** her car to her sister back at home. Just an example of how she acts, this one time she asked to stay 15 min later to build 15 min of credit hours, which is ridiculous if you ask me. I said I didn't want to but she insisted so I said okay and said I'll work on my project. I needed 15 min more than she did and when the first 15 min passed and she said she was done, I said I need 15 min more and she acted like that was ridiculous and she didn't want to have to wait for me, so we ended up staying 30 min past the work day. **How do I let her know that she's the one benefitting at my expense for something that is completely voluntary by myself and only serves to help her?** I refuse to stop asking her not to be late or to take back what I said before because I think I'm being perfectly reasonable. She thinks me saying that is "disrespectful and dictatorish". I'd prefer for this to not be the reason to end a friendship but I won't stand for disrespect. I don't mind this arrangement but I do mind her attitude. I think I'm only doing her a favor. Sure I oversleep sometimes but I literally have 35+ alarms set over a 60 min period between my phone and 5 different clocks. I know, ridiculous. So it's not like I try to oversleep. I have a half-hearted apology which I could do better but the reason I don't drop the subject is because she demands respect and acts like only she's in the right (mind you I don't have to give her rides at all and they're free for her).
2018/09/06
[ "https://interpersonal.stackexchange.com/questions/18265", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/21520/" ]
I don't think you're being unreasonable at all. There are many reasons why this arrangement is to your disadvantage, and there seems to be no benefit to yourself. Regarding the fact she sometimes makes you late: you mention that you are sometimes late yourself even without her. Well, almost everybody is sometimes, but would you agree that most people know how much lateness they can afford? Irrespective of whether you need to be in work by a time stipulated by your employer or because it suits your own schedule, if you can be "late" yourself then you probably can't afford for someone else to make you late too. It doesn't matter whether your colleague thinks you are a hypocrite for asking her not to be late, fact is that she could make *you* late when you can't afford to be. This fact alone would make many conclude it might be better for you each to be responsible for getting your own selves to work on time. Regarding her lack of contribution: well, this is a matter of *her* etiquette, not yours. Perhaps she reasons that as there is no additional cost to you (the details you give suggest you don't go out of your way, and she meets you en route) that she isn't *costing* you anything so there is no need to contribute. Of course, this isn't really in the spirit of carpooling. It is supposed to be a *sharing of resources* to save money and be more environmentally friendly among other things. Most people would offer to share the costs, especially if a fair percentage of your fuel costs is less than their public transport costs. Also, I believe your two incomes are completely irrelevant to the situation. Sure, the fact she earns more than you does make her complaints about her salary and also her lack of contribution to you a little more insulting, but even if the salaries were the other way around it would only be good etiquette to offer you a contribution. Considering all of this, and after further discussion with you, to be honest I don't think what you have with this colleague even fits the definition of "[carpooling](https://en.wikipedia.org/wiki/Carpool)". There are no shared savings from the arrangement. In fact there isn't much of an arrangement either - she rides with other people or you as and when she feels like it. It seems that what you do is entirely for her benefit. This isn't a site for telling you what to do. Rather we try to help address problems in an interpersonal way. Whether you choose to end the arrangement or try and fix it you would need to talk to her. In either case, we advocate honesty and you should just be straight with her to avoid any ambiguity. If you want to end the arrangement you could perhaps say: > > I've been thinking about our car pooling, and it seems that on the whole we have different schedules. I want to be in work by 06:00 each day because this supports my preferred finishing time. **Sorry, but that means it isn't possible for me to give you a ride anymore.** > > > Alternatively, if you feel the situation could be rescued you could say: > > I've been thinking about our car pooling, and it seems that on the whole we have different schedules. I want to be in work by 06:00 each day because this supports my preferred finishing time. **I'd be happy to continue giving you a ride if you can fit in with that preference**. > > > And see what she says. She may choose to get a ride with the other colleague instead, which is win-win. You don't *owe* it to anybody to take them into work. Your employer will see you all as individually responsible for getting to work. What you have been doing for her is a kind gesture, even if she contributed, because you do not have to do it. I believe the approach above which focuses on *your* preference to be in work on time will be better received than if you tackle her about *her* attitude or lack of contribution. Getting her to see it from your point of view may even prompt her to address the latter.
Your arrangement is operating on the basis of **[social norms](https://whistlinginthewind.org/2013/01/15/predictably-irrational-chapter-4-the-cost-of-social-norms/)**, and it isn't working out because she's not taking care to be socially acceptable. I suggest you change your arrangement to operate on **market norms**. As I noted above, even your $70/month for gas doesn't reflect the true costs of owning a car: * gas * maintenance * insurance * wear-and-tear (eventually requiring the purchase of a replacement car) A better reflection would be a standard mileage rate, such as the [IRS mileage reimbursement rate of **54.5c/mile** for 2018](https://www.irs.gov/newsroom/standard-mileage-rates-for-2018-up-from-rates-for-2017). I'm going to guess that your commute is about 12 miles one way. At 54.5 cents per mile, that's $6.54 per one-way trip. On that basis, commuting by car is costing you about $283/month. Now you know the cost of her ride: **$3.27 per one-way trip.** And now that you know that, you can decide how you want her to pay. One option is for her to pay when she rides with you, but not when she doesn't because she's late. That way she can be less upset about being late, because she's saving $3.27 each time. Another option is to allow her to continue not paying, but impose a penalty whenever she's late. How much would be enough to leave you happy to be getting the extra cash rather than upset about the lateness? Perhaps $2 per 5 minutes of lateness, for example. Her 15 minutes of extra "credit time" would net you $6 in exchange for waiting for her, and she can decide if it's worth $6 to her to get credit time and make you late. Sometimes it's a bad idea to replace social norms with market norms, because it allows people to shamelessly pay to continue to engage in bad behavior. But in this case she doesn't seem to have any shame (in fact, **she's** trying to shame **you**!), so you have nothing to lose here.
18,265
**TL;DR:** I drive to work at my own expense. My friend gets a free ride from me, saving her money and time. I say "don't be late" sometimes, and she freaks out. --- So I live in a metropolitan area and have a vehicle. I have a friend/coworker who ditched her car when she moved here so she takes the metro by default. She has been late before but I have too, and I have a history of oversleeping as I am a heavy sleeper. Sometimes, and infrequently, I will simply say when I will plan on picking her up from the metro (as she takes a much shorter metro ride to my place to get carpool ride vs taking the metro all the way to work) so will say something like "I'm leaving at 600. Don't be late!". For whatever reason, she freaks out that I have the audacity to say "don't be late" when I have overslept before, which I said last night and overslept today. I tried to explain that I'm not being a hypocrite and only say it as a friendly reminder, as we are not infallible but she's not having it. Some details: * I have a car, she does not * My commute is 20-30 min in my vehicle, her commute on metro is about an hour, her commute when carpooling is about 25-35 min (short metro ride and then carpool) * I spend a minimum of $70 in gas a month just commuting, she would spent at most $160 a month ($8 round trip per day x ~20 work days in a month) BUT she's part of a subsidy program for mass transit users which has a max allowance of $245/mo but I don't know how much she's receiving. * She does not pay me anything, ever. I don't ask but she never offers anything more than a "thanks". * Half the time, she doesn't even ride home with me because she decides to stay later to build credit hours at work or will make me wait for her * I was a GS-07 and she is a GS-09 (roughly $45k/year and $55k/year respectively, but I am a 09 now and she is becoming an 11 ($55 and $65 respectively). This is only relevant because she complains about money and not being able to afford the metro (despite the subsidy). * She also has another coworker that gives her rides (same situation but he lives close enough that he picks her up directly and she doesn't need the short metro ride over). It's not my fault she **GAVE** her car to her sister back at home. Just an example of how she acts, this one time she asked to stay 15 min later to build 15 min of credit hours, which is ridiculous if you ask me. I said I didn't want to but she insisted so I said okay and said I'll work on my project. I needed 15 min more than she did and when the first 15 min passed and she said she was done, I said I need 15 min more and she acted like that was ridiculous and she didn't want to have to wait for me, so we ended up staying 30 min past the work day. **How do I let her know that she's the one benefitting at my expense for something that is completely voluntary by myself and only serves to help her?** I refuse to stop asking her not to be late or to take back what I said before because I think I'm being perfectly reasonable. She thinks me saying that is "disrespectful and dictatorish". I'd prefer for this to not be the reason to end a friendship but I won't stand for disrespect. I don't mind this arrangement but I do mind her attitude. I think I'm only doing her a favor. Sure I oversleep sometimes but I literally have 35+ alarms set over a 60 min period between my phone and 5 different clocks. I know, ridiculous. So it's not like I try to oversleep. I have a half-hearted apology which I could do better but the reason I don't drop the subject is because she demands respect and acts like only she's in the right (mind you I don't have to give her rides at all and they're free for her).
2018/09/06
[ "https://interpersonal.stackexchange.com/questions/18265", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/21520/" ]
I don't think you're being unreasonable at all. There are many reasons why this arrangement is to your disadvantage, and there seems to be no benefit to yourself. Regarding the fact she sometimes makes you late: you mention that you are sometimes late yourself even without her. Well, almost everybody is sometimes, but would you agree that most people know how much lateness they can afford? Irrespective of whether you need to be in work by a time stipulated by your employer or because it suits your own schedule, if you can be "late" yourself then you probably can't afford for someone else to make you late too. It doesn't matter whether your colleague thinks you are a hypocrite for asking her not to be late, fact is that she could make *you* late when you can't afford to be. This fact alone would make many conclude it might be better for you each to be responsible for getting your own selves to work on time. Regarding her lack of contribution: well, this is a matter of *her* etiquette, not yours. Perhaps she reasons that as there is no additional cost to you (the details you give suggest you don't go out of your way, and she meets you en route) that she isn't *costing* you anything so there is no need to contribute. Of course, this isn't really in the spirit of carpooling. It is supposed to be a *sharing of resources* to save money and be more environmentally friendly among other things. Most people would offer to share the costs, especially if a fair percentage of your fuel costs is less than their public transport costs. Also, I believe your two incomes are completely irrelevant to the situation. Sure, the fact she earns more than you does make her complaints about her salary and also her lack of contribution to you a little more insulting, but even if the salaries were the other way around it would only be good etiquette to offer you a contribution. Considering all of this, and after further discussion with you, to be honest I don't think what you have with this colleague even fits the definition of "[carpooling](https://en.wikipedia.org/wiki/Carpool)". There are no shared savings from the arrangement. In fact there isn't much of an arrangement either - she rides with other people or you as and when she feels like it. It seems that what you do is entirely for her benefit. This isn't a site for telling you what to do. Rather we try to help address problems in an interpersonal way. Whether you choose to end the arrangement or try and fix it you would need to talk to her. In either case, we advocate honesty and you should just be straight with her to avoid any ambiguity. If you want to end the arrangement you could perhaps say: > > I've been thinking about our car pooling, and it seems that on the whole we have different schedules. I want to be in work by 06:00 each day because this supports my preferred finishing time. **Sorry, but that means it isn't possible for me to give you a ride anymore.** > > > Alternatively, if you feel the situation could be rescued you could say: > > I've been thinking about our car pooling, and it seems that on the whole we have different schedules. I want to be in work by 06:00 each day because this supports my preferred finishing time. **I'd be happy to continue giving you a ride if you can fit in with that preference**. > > > And see what she says. She may choose to get a ride with the other colleague instead, which is win-win. You don't *owe* it to anybody to take them into work. Your employer will see you all as individually responsible for getting to work. What you have been doing for her is a kind gesture, even if she contributed, because you do not have to do it. I believe the approach above which focuses on *your* preference to be in work on time will be better received than if you tackle her about *her* attitude or lack of contribution. Getting her to see it from your point of view may even prompt her to address the latter.
I have been in a similar situation with carpooling but we were always 3-4 people going together. The system that we used was quite simple. If you were not where you are supposed to be on time you got left behind as it is not fair for 3 other people to be late if you can't make it. At the end of the day you are the one doing a favour to that person. You set the rules. If she is not happy she doesn't have to carpool with you. Just stick to your schedule and offer rides if she wants them. You are under no obligation to stay late and wait for her or leave the moment she wants you to leave. I can tell you that nobody was late more than once as we were carpooling to a nearby town and it was generally a pain to get there if you missed the car.
18,265
**TL;DR:** I drive to work at my own expense. My friend gets a free ride from me, saving her money and time. I say "don't be late" sometimes, and she freaks out. --- So I live in a metropolitan area and have a vehicle. I have a friend/coworker who ditched her car when she moved here so she takes the metro by default. She has been late before but I have too, and I have a history of oversleeping as I am a heavy sleeper. Sometimes, and infrequently, I will simply say when I will plan on picking her up from the metro (as she takes a much shorter metro ride to my place to get carpool ride vs taking the metro all the way to work) so will say something like "I'm leaving at 600. Don't be late!". For whatever reason, she freaks out that I have the audacity to say "don't be late" when I have overslept before, which I said last night and overslept today. I tried to explain that I'm not being a hypocrite and only say it as a friendly reminder, as we are not infallible but she's not having it. Some details: * I have a car, she does not * My commute is 20-30 min in my vehicle, her commute on metro is about an hour, her commute when carpooling is about 25-35 min (short metro ride and then carpool) * I spend a minimum of $70 in gas a month just commuting, she would spent at most $160 a month ($8 round trip per day x ~20 work days in a month) BUT she's part of a subsidy program for mass transit users which has a max allowance of $245/mo but I don't know how much she's receiving. * She does not pay me anything, ever. I don't ask but she never offers anything more than a "thanks". * Half the time, she doesn't even ride home with me because she decides to stay later to build credit hours at work or will make me wait for her * I was a GS-07 and she is a GS-09 (roughly $45k/year and $55k/year respectively, but I am a 09 now and she is becoming an 11 ($55 and $65 respectively). This is only relevant because she complains about money and not being able to afford the metro (despite the subsidy). * She also has another coworker that gives her rides (same situation but he lives close enough that he picks her up directly and she doesn't need the short metro ride over). It's not my fault she **GAVE** her car to her sister back at home. Just an example of how she acts, this one time she asked to stay 15 min later to build 15 min of credit hours, which is ridiculous if you ask me. I said I didn't want to but she insisted so I said okay and said I'll work on my project. I needed 15 min more than she did and when the first 15 min passed and she said she was done, I said I need 15 min more and she acted like that was ridiculous and she didn't want to have to wait for me, so we ended up staying 30 min past the work day. **How do I let her know that she's the one benefitting at my expense for something that is completely voluntary by myself and only serves to help her?** I refuse to stop asking her not to be late or to take back what I said before because I think I'm being perfectly reasonable. She thinks me saying that is "disrespectful and dictatorish". I'd prefer for this to not be the reason to end a friendship but I won't stand for disrespect. I don't mind this arrangement but I do mind her attitude. I think I'm only doing her a favor. Sure I oversleep sometimes but I literally have 35+ alarms set over a 60 min period between my phone and 5 different clocks. I know, ridiculous. So it's not like I try to oversleep. I have a half-hearted apology which I could do better but the reason I don't drop the subject is because she demands respect and acts like only she's in the right (mind you I don't have to give her rides at all and they're free for her).
2018/09/06
[ "https://interpersonal.stackexchange.com/questions/18265", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/21520/" ]
I have been in a similar situation with carpooling but we were always 3-4 people going together. The system that we used was quite simple. If you were not where you are supposed to be on time you got left behind as it is not fair for 3 other people to be late if you can't make it. At the end of the day you are the one doing a favour to that person. You set the rules. If she is not happy she doesn't have to carpool with you. Just stick to your schedule and offer rides if she wants them. You are under no obligation to stay late and wait for her or leave the moment she wants you to leave. I can tell you that nobody was late more than once as we were carpooling to a nearby town and it was generally a pain to get there if you missed the car.
**Train here**. You want to ride... I vow that I will never leave the station early. *That*, I can control. As for "late", you gotta understand. Stuff happens, paperwork, responsibil-- ok look, at the end of the day, it's because **I'm the train and that's how it is for trains**. That might seem unfair, that she owes you timekeeping and you don't owe it back in equal measure, but that is a reality when you are the train. So from my perspective... if she's at the agreed place at the scheduled time, and you're not, the only possible reason is that you're late. You didn't leave early - you *wouldn't*. So she can wait a few minutes and along you'll come. And then, you do your fair level best to stick to timekeeping. End of the day, if *your best* isn't good enough for the customer, this mode of transport may not be for them. Main thing is: **You do the best you can do, *and don't worry about it***. Since you only have one passenger, lucky you, you're free to negotiate of course. If she runs late and calls you, and you're agreeable, you can wait if you want, but you don't owe her that. Just stick to what works for you. In your case, your friend always has a plan-B to get home, so she's not dependent. *One more thing, I'll tell you a secret. Running a couple minutes late actually helps stragglers. Even with cell phones pulling time off satellites, not everyone's phone is synchronized to the second. Happens all the time where a straggler rolls up to the station with their watch showing 7:00 and mine says 7:01, and I'da been gone.* Let the schedule slide a minute or two, and a bunch of passenger complaints just go away.
18,265
**TL;DR:** I drive to work at my own expense. My friend gets a free ride from me, saving her money and time. I say "don't be late" sometimes, and she freaks out. --- So I live in a metropolitan area and have a vehicle. I have a friend/coworker who ditched her car when she moved here so she takes the metro by default. She has been late before but I have too, and I have a history of oversleeping as I am a heavy sleeper. Sometimes, and infrequently, I will simply say when I will plan on picking her up from the metro (as she takes a much shorter metro ride to my place to get carpool ride vs taking the metro all the way to work) so will say something like "I'm leaving at 600. Don't be late!". For whatever reason, she freaks out that I have the audacity to say "don't be late" when I have overslept before, which I said last night and overslept today. I tried to explain that I'm not being a hypocrite and only say it as a friendly reminder, as we are not infallible but she's not having it. Some details: * I have a car, she does not * My commute is 20-30 min in my vehicle, her commute on metro is about an hour, her commute when carpooling is about 25-35 min (short metro ride and then carpool) * I spend a minimum of $70 in gas a month just commuting, she would spent at most $160 a month ($8 round trip per day x ~20 work days in a month) BUT she's part of a subsidy program for mass transit users which has a max allowance of $245/mo but I don't know how much she's receiving. * She does not pay me anything, ever. I don't ask but she never offers anything more than a "thanks". * Half the time, she doesn't even ride home with me because she decides to stay later to build credit hours at work or will make me wait for her * I was a GS-07 and she is a GS-09 (roughly $45k/year and $55k/year respectively, but I am a 09 now and she is becoming an 11 ($55 and $65 respectively). This is only relevant because she complains about money and not being able to afford the metro (despite the subsidy). * She also has another coworker that gives her rides (same situation but he lives close enough that he picks her up directly and she doesn't need the short metro ride over). It's not my fault she **GAVE** her car to her sister back at home. Just an example of how she acts, this one time she asked to stay 15 min later to build 15 min of credit hours, which is ridiculous if you ask me. I said I didn't want to but she insisted so I said okay and said I'll work on my project. I needed 15 min more than she did and when the first 15 min passed and she said she was done, I said I need 15 min more and she acted like that was ridiculous and she didn't want to have to wait for me, so we ended up staying 30 min past the work day. **How do I let her know that she's the one benefitting at my expense for something that is completely voluntary by myself and only serves to help her?** I refuse to stop asking her not to be late or to take back what I said before because I think I'm being perfectly reasonable. She thinks me saying that is "disrespectful and dictatorish". I'd prefer for this to not be the reason to end a friendship but I won't stand for disrespect. I don't mind this arrangement but I do mind her attitude. I think I'm only doing her a favor. Sure I oversleep sometimes but I literally have 35+ alarms set over a 60 min period between my phone and 5 different clocks. I know, ridiculous. So it's not like I try to oversleep. I have a half-hearted apology which I could do better but the reason I don't drop the subject is because she demands respect and acts like only she's in the right (mind you I don't have to give her rides at all and they're free for her).
2018/09/06
[ "https://interpersonal.stackexchange.com/questions/18265", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/21520/" ]
I don't think you're being unreasonable at all. There are many reasons why this arrangement is to your disadvantage, and there seems to be no benefit to yourself. Regarding the fact she sometimes makes you late: you mention that you are sometimes late yourself even without her. Well, almost everybody is sometimes, but would you agree that most people know how much lateness they can afford? Irrespective of whether you need to be in work by a time stipulated by your employer or because it suits your own schedule, if you can be "late" yourself then you probably can't afford for someone else to make you late too. It doesn't matter whether your colleague thinks you are a hypocrite for asking her not to be late, fact is that she could make *you* late when you can't afford to be. This fact alone would make many conclude it might be better for you each to be responsible for getting your own selves to work on time. Regarding her lack of contribution: well, this is a matter of *her* etiquette, not yours. Perhaps she reasons that as there is no additional cost to you (the details you give suggest you don't go out of your way, and she meets you en route) that she isn't *costing* you anything so there is no need to contribute. Of course, this isn't really in the spirit of carpooling. It is supposed to be a *sharing of resources* to save money and be more environmentally friendly among other things. Most people would offer to share the costs, especially if a fair percentage of your fuel costs is less than their public transport costs. Also, I believe your two incomes are completely irrelevant to the situation. Sure, the fact she earns more than you does make her complaints about her salary and also her lack of contribution to you a little more insulting, but even if the salaries were the other way around it would only be good etiquette to offer you a contribution. Considering all of this, and after further discussion with you, to be honest I don't think what you have with this colleague even fits the definition of "[carpooling](https://en.wikipedia.org/wiki/Carpool)". There are no shared savings from the arrangement. In fact there isn't much of an arrangement either - she rides with other people or you as and when she feels like it. It seems that what you do is entirely for her benefit. This isn't a site for telling you what to do. Rather we try to help address problems in an interpersonal way. Whether you choose to end the arrangement or try and fix it you would need to talk to her. In either case, we advocate honesty and you should just be straight with her to avoid any ambiguity. If you want to end the arrangement you could perhaps say: > > I've been thinking about our car pooling, and it seems that on the whole we have different schedules. I want to be in work by 06:00 each day because this supports my preferred finishing time. **Sorry, but that means it isn't possible for me to give you a ride anymore.** > > > Alternatively, if you feel the situation could be rescued you could say: > > I've been thinking about our car pooling, and it seems that on the whole we have different schedules. I want to be in work by 06:00 each day because this supports my preferred finishing time. **I'd be happy to continue giving you a ride if you can fit in with that preference**. > > > And see what she says. She may choose to get a ride with the other colleague instead, which is win-win. You don't *owe* it to anybody to take them into work. Your employer will see you all as individually responsible for getting to work. What you have been doing for her is a kind gesture, even if she contributed, because you do not have to do it. I believe the approach above which focuses on *your* preference to be in work on time will be better received than if you tackle her about *her* attitude or lack of contribution. Getting her to see it from your point of view may even prompt her to address the latter.
Desperate times require desperate measures. Here I make assumption that your pooling buddy doesn't really react well to verbal pleads made in "good will". And also due to their personality/identity/character your buddy fails to realize that this behaviour is not acceptable. Basically your buddy is getting a "free ride" and doesn't "feel pain" of being late or smth. Basically we need your buddy to start feeling the "pain of responsibility". And IMHO the best way to do it - to introduce "financial responsibility" or so it "hurts financially". Asking for .50$ per mile is pointless, as it doesn't really give you any advantage. Now when the person is late - they can claim that they pay you for mileage and you're still bugging them with being late and "do not hold on to your side of responsibility" (that would be cheeky, but some people don't have boundaries... and twist situations to their advantage...) The idea of @Kyralessa is good, but $6 for being late still feels like a free ride, plus actually the actual process of getting paid (finding notes, finding change, will be annoying and taxing to you). I would proppose, that you introduce "carpool driver respect deposit". The deposit may be "topped up" in the beginning of the month. Your buddy gives you $100 as the deposit (yes, it can't be small money like $10). Remember that this money is NOT "payment" for the ride (you still hold the claim that you give them the ride for free and maintain leverage). The purpose of the deposit - is to give your buddy flexibility to be late when they want, but under given conditions and with the price to pay for being late. (Again, remember, that the ride is still free!) Now the interesting part: **The Being Late Tarifs** * every time buddy is late [1min-5min] from the deposit is deduced a $5 fee * every time buddy is late [6min-10min] from deposit deducted $20 fee * every time buddy is late [11min-15min] from deposit deducted $50 fee * [16min+] you can either just charge $100 or just take off The purpose here is to use **exponential raise** in tariff to drive necessary behaviour from your buddy: * If you're little late (happens to all of us, once a week you can afford to pay $5) * if you're late - shell out $20 and try harder next time * if you're very late - well, the annoyance one feels shelling out $50 bucks for being late should make person feel the pain you feel when being very late. Also on shaming, etc. Important part is that - you still offer the ride for free, so you have the upper hand. No one can have any decent arguments against you, as you're giving person free rides. It's them paying for the "disrespect" or "being late" or whatever you prefer to call them. They're absolutely free to arrive on time and get free ride. The only "iron rule" you should define since the very early stage and stick to it: > > **No money in the "driver respect deposit" - no ride** > > > The argument you can make: "You want a free ride - show me some respect!" HTH ps. Of course such financial ways of motivation may look from first sight weird and awkward and shouldn't occur when people respect each other's time. But as I wrote in the opening: desperate times require desperate measures.
18,265
**TL;DR:** I drive to work at my own expense. My friend gets a free ride from me, saving her money and time. I say "don't be late" sometimes, and she freaks out. --- So I live in a metropolitan area and have a vehicle. I have a friend/coworker who ditched her car when she moved here so she takes the metro by default. She has been late before but I have too, and I have a history of oversleeping as I am a heavy sleeper. Sometimes, and infrequently, I will simply say when I will plan on picking her up from the metro (as she takes a much shorter metro ride to my place to get carpool ride vs taking the metro all the way to work) so will say something like "I'm leaving at 600. Don't be late!". For whatever reason, she freaks out that I have the audacity to say "don't be late" when I have overslept before, which I said last night and overslept today. I tried to explain that I'm not being a hypocrite and only say it as a friendly reminder, as we are not infallible but she's not having it. Some details: * I have a car, she does not * My commute is 20-30 min in my vehicle, her commute on metro is about an hour, her commute when carpooling is about 25-35 min (short metro ride and then carpool) * I spend a minimum of $70 in gas a month just commuting, she would spent at most $160 a month ($8 round trip per day x ~20 work days in a month) BUT she's part of a subsidy program for mass transit users which has a max allowance of $245/mo but I don't know how much she's receiving. * She does not pay me anything, ever. I don't ask but she never offers anything more than a "thanks". * Half the time, she doesn't even ride home with me because she decides to stay later to build credit hours at work or will make me wait for her * I was a GS-07 and she is a GS-09 (roughly $45k/year and $55k/year respectively, but I am a 09 now and she is becoming an 11 ($55 and $65 respectively). This is only relevant because she complains about money and not being able to afford the metro (despite the subsidy). * She also has another coworker that gives her rides (same situation but he lives close enough that he picks her up directly and she doesn't need the short metro ride over). It's not my fault she **GAVE** her car to her sister back at home. Just an example of how she acts, this one time she asked to stay 15 min later to build 15 min of credit hours, which is ridiculous if you ask me. I said I didn't want to but she insisted so I said okay and said I'll work on my project. I needed 15 min more than she did and when the first 15 min passed and she said she was done, I said I need 15 min more and she acted like that was ridiculous and she didn't want to have to wait for me, so we ended up staying 30 min past the work day. **How do I let her know that she's the one benefitting at my expense for something that is completely voluntary by myself and only serves to help her?** I refuse to stop asking her not to be late or to take back what I said before because I think I'm being perfectly reasonable. She thinks me saying that is "disrespectful and dictatorish". I'd prefer for this to not be the reason to end a friendship but I won't stand for disrespect. I don't mind this arrangement but I do mind her attitude. I think I'm only doing her a favor. Sure I oversleep sometimes but I literally have 35+ alarms set over a 60 min period between my phone and 5 different clocks. I know, ridiculous. So it's not like I try to oversleep. I have a half-hearted apology which I could do better but the reason I don't drop the subject is because she demands respect and acts like only she's in the right (mind you I don't have to give her rides at all and they're free for her).
2018/09/06
[ "https://interpersonal.stackexchange.com/questions/18265", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/21520/" ]
Your arrangement is operating on the basis of **[social norms](https://whistlinginthewind.org/2013/01/15/predictably-irrational-chapter-4-the-cost-of-social-norms/)**, and it isn't working out because she's not taking care to be socially acceptable. I suggest you change your arrangement to operate on **market norms**. As I noted above, even your $70/month for gas doesn't reflect the true costs of owning a car: * gas * maintenance * insurance * wear-and-tear (eventually requiring the purchase of a replacement car) A better reflection would be a standard mileage rate, such as the [IRS mileage reimbursement rate of **54.5c/mile** for 2018](https://www.irs.gov/newsroom/standard-mileage-rates-for-2018-up-from-rates-for-2017). I'm going to guess that your commute is about 12 miles one way. At 54.5 cents per mile, that's $6.54 per one-way trip. On that basis, commuting by car is costing you about $283/month. Now you know the cost of her ride: **$3.27 per one-way trip.** And now that you know that, you can decide how you want her to pay. One option is for her to pay when she rides with you, but not when she doesn't because she's late. That way she can be less upset about being late, because she's saving $3.27 each time. Another option is to allow her to continue not paying, but impose a penalty whenever she's late. How much would be enough to leave you happy to be getting the extra cash rather than upset about the lateness? Perhaps $2 per 5 minutes of lateness, for example. Her 15 minutes of extra "credit time" would net you $6 in exchange for waiting for her, and she can decide if it's worth $6 to her to get credit time and make you late. Sometimes it's a bad idea to replace social norms with market norms, because it allows people to shamelessly pay to continue to engage in bad behavior. But in this case she doesn't seem to have any shame (in fact, **she's** trying to shame **you**!), so you have nothing to lose here.
Desperate times require desperate measures. Here I make assumption that your pooling buddy doesn't really react well to verbal pleads made in "good will". And also due to their personality/identity/character your buddy fails to realize that this behaviour is not acceptable. Basically your buddy is getting a "free ride" and doesn't "feel pain" of being late or smth. Basically we need your buddy to start feeling the "pain of responsibility". And IMHO the best way to do it - to introduce "financial responsibility" or so it "hurts financially". Asking for .50$ per mile is pointless, as it doesn't really give you any advantage. Now when the person is late - they can claim that they pay you for mileage and you're still bugging them with being late and "do not hold on to your side of responsibility" (that would be cheeky, but some people don't have boundaries... and twist situations to their advantage...) The idea of @Kyralessa is good, but $6 for being late still feels like a free ride, plus actually the actual process of getting paid (finding notes, finding change, will be annoying and taxing to you). I would proppose, that you introduce "carpool driver respect deposit". The deposit may be "topped up" in the beginning of the month. Your buddy gives you $100 as the deposit (yes, it can't be small money like $10). Remember that this money is NOT "payment" for the ride (you still hold the claim that you give them the ride for free and maintain leverage). The purpose of the deposit - is to give your buddy flexibility to be late when they want, but under given conditions and with the price to pay for being late. (Again, remember, that the ride is still free!) Now the interesting part: **The Being Late Tarifs** * every time buddy is late [1min-5min] from the deposit is deduced a $5 fee * every time buddy is late [6min-10min] from deposit deducted $20 fee * every time buddy is late [11min-15min] from deposit deducted $50 fee * [16min+] you can either just charge $100 or just take off The purpose here is to use **exponential raise** in tariff to drive necessary behaviour from your buddy: * If you're little late (happens to all of us, once a week you can afford to pay $5) * if you're late - shell out $20 and try harder next time * if you're very late - well, the annoyance one feels shelling out $50 bucks for being late should make person feel the pain you feel when being very late. Also on shaming, etc. Important part is that - you still offer the ride for free, so you have the upper hand. No one can have any decent arguments against you, as you're giving person free rides. It's them paying for the "disrespect" or "being late" or whatever you prefer to call them. They're absolutely free to arrive on time and get free ride. The only "iron rule" you should define since the very early stage and stick to it: > > **No money in the "driver respect deposit" - no ride** > > > The argument you can make: "You want a free ride - show me some respect!" HTH ps. Of course such financial ways of motivation may look from first sight weird and awkward and shouldn't occur when people respect each other's time. But as I wrote in the opening: desperate times require desperate measures.
18,265
**TL;DR:** I drive to work at my own expense. My friend gets a free ride from me, saving her money and time. I say "don't be late" sometimes, and she freaks out. --- So I live in a metropolitan area and have a vehicle. I have a friend/coworker who ditched her car when she moved here so she takes the metro by default. She has been late before but I have too, and I have a history of oversleeping as I am a heavy sleeper. Sometimes, and infrequently, I will simply say when I will plan on picking her up from the metro (as she takes a much shorter metro ride to my place to get carpool ride vs taking the metro all the way to work) so will say something like "I'm leaving at 600. Don't be late!". For whatever reason, she freaks out that I have the audacity to say "don't be late" when I have overslept before, which I said last night and overslept today. I tried to explain that I'm not being a hypocrite and only say it as a friendly reminder, as we are not infallible but she's not having it. Some details: * I have a car, she does not * My commute is 20-30 min in my vehicle, her commute on metro is about an hour, her commute when carpooling is about 25-35 min (short metro ride and then carpool) * I spend a minimum of $70 in gas a month just commuting, she would spent at most $160 a month ($8 round trip per day x ~20 work days in a month) BUT she's part of a subsidy program for mass transit users which has a max allowance of $245/mo but I don't know how much she's receiving. * She does not pay me anything, ever. I don't ask but she never offers anything more than a "thanks". * Half the time, she doesn't even ride home with me because she decides to stay later to build credit hours at work or will make me wait for her * I was a GS-07 and she is a GS-09 (roughly $45k/year and $55k/year respectively, but I am a 09 now and she is becoming an 11 ($55 and $65 respectively). This is only relevant because she complains about money and not being able to afford the metro (despite the subsidy). * She also has another coworker that gives her rides (same situation but he lives close enough that he picks her up directly and she doesn't need the short metro ride over). It's not my fault she **GAVE** her car to her sister back at home. Just an example of how she acts, this one time she asked to stay 15 min later to build 15 min of credit hours, which is ridiculous if you ask me. I said I didn't want to but she insisted so I said okay and said I'll work on my project. I needed 15 min more than she did and when the first 15 min passed and she said she was done, I said I need 15 min more and she acted like that was ridiculous and she didn't want to have to wait for me, so we ended up staying 30 min past the work day. **How do I let her know that she's the one benefitting at my expense for something that is completely voluntary by myself and only serves to help her?** I refuse to stop asking her not to be late or to take back what I said before because I think I'm being perfectly reasonable. She thinks me saying that is "disrespectful and dictatorish". I'd prefer for this to not be the reason to end a friendship but I won't stand for disrespect. I don't mind this arrangement but I do mind her attitude. I think I'm only doing her a favor. Sure I oversleep sometimes but I literally have 35+ alarms set over a 60 min period between my phone and 5 different clocks. I know, ridiculous. So it's not like I try to oversleep. I have a half-hearted apology which I could do better but the reason I don't drop the subject is because she demands respect and acts like only she's in the right (mind you I don't have to give her rides at all and they're free for her).
2018/09/06
[ "https://interpersonal.stackexchange.com/questions/18265", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/21520/" ]
**Train here**. You want to ride... I vow that I will never leave the station early. *That*, I can control. As for "late", you gotta understand. Stuff happens, paperwork, responsibil-- ok look, at the end of the day, it's because **I'm the train and that's how it is for trains**. That might seem unfair, that she owes you timekeeping and you don't owe it back in equal measure, but that is a reality when you are the train. So from my perspective... if she's at the agreed place at the scheduled time, and you're not, the only possible reason is that you're late. You didn't leave early - you *wouldn't*. So she can wait a few minutes and along you'll come. And then, you do your fair level best to stick to timekeeping. End of the day, if *your best* isn't good enough for the customer, this mode of transport may not be for them. Main thing is: **You do the best you can do, *and don't worry about it***. Since you only have one passenger, lucky you, you're free to negotiate of course. If she runs late and calls you, and you're agreeable, you can wait if you want, but you don't owe her that. Just stick to what works for you. In your case, your friend always has a plan-B to get home, so she's not dependent. *One more thing, I'll tell you a secret. Running a couple minutes late actually helps stragglers. Even with cell phones pulling time off satellites, not everyone's phone is synchronized to the second. Happens all the time where a straggler rolls up to the station with their watch showing 7:00 and mine says 7:01, and I'da been gone.* Let the schedule slide a minute or two, and a bunch of passenger complaints just go away.
If you want your colleague to be on time ---------------------------------------- First off, **try to always be on time yourself**. It's much easier to demand other people to be on time if you set an example. Second, stop calling it "carpooling". What you do is not really a case of car sharing, instead **you give her a ride**. Use this exact wording, e.g. "sorry I can't give you a ride tomorrow" or "I can give you a ride at 6:30". That should serve as a reminder that your colleague is the one to benefit from the arrangement. Finally, **announce the hours which suit you** often and make her agree: "I'm driving to work at 6:30 and plan to drive back at 5:00, is that OK?". If she says "no" you simply tell her she'll have to use the subway. If she agrees, that gives you a fresh argument against her being late in the morning or wanting to stay late in the evening. Alternatively ------------- Consider asking her to contribute to the rides. If you split gas expenses 50/50, perhaps it wouldn't be so much of a problem for you to occasionally wait for her 5-7 minutes in the morning when she's late, and stay 15 extra minutes in the evening when she has something urgent to finish.
18,265
**TL;DR:** I drive to work at my own expense. My friend gets a free ride from me, saving her money and time. I say "don't be late" sometimes, and she freaks out. --- So I live in a metropolitan area and have a vehicle. I have a friend/coworker who ditched her car when she moved here so she takes the metro by default. She has been late before but I have too, and I have a history of oversleeping as I am a heavy sleeper. Sometimes, and infrequently, I will simply say when I will plan on picking her up from the metro (as she takes a much shorter metro ride to my place to get carpool ride vs taking the metro all the way to work) so will say something like "I'm leaving at 600. Don't be late!". For whatever reason, she freaks out that I have the audacity to say "don't be late" when I have overslept before, which I said last night and overslept today. I tried to explain that I'm not being a hypocrite and only say it as a friendly reminder, as we are not infallible but she's not having it. Some details: * I have a car, she does not * My commute is 20-30 min in my vehicle, her commute on metro is about an hour, her commute when carpooling is about 25-35 min (short metro ride and then carpool) * I spend a minimum of $70 in gas a month just commuting, she would spent at most $160 a month ($8 round trip per day x ~20 work days in a month) BUT she's part of a subsidy program for mass transit users which has a max allowance of $245/mo but I don't know how much she's receiving. * She does not pay me anything, ever. I don't ask but she never offers anything more than a "thanks". * Half the time, she doesn't even ride home with me because she decides to stay later to build credit hours at work or will make me wait for her * I was a GS-07 and she is a GS-09 (roughly $45k/year and $55k/year respectively, but I am a 09 now and she is becoming an 11 ($55 and $65 respectively). This is only relevant because she complains about money and not being able to afford the metro (despite the subsidy). * She also has another coworker that gives her rides (same situation but he lives close enough that he picks her up directly and she doesn't need the short metro ride over). It's not my fault she **GAVE** her car to her sister back at home. Just an example of how she acts, this one time she asked to stay 15 min later to build 15 min of credit hours, which is ridiculous if you ask me. I said I didn't want to but she insisted so I said okay and said I'll work on my project. I needed 15 min more than she did and when the first 15 min passed and she said she was done, I said I need 15 min more and she acted like that was ridiculous and she didn't want to have to wait for me, so we ended up staying 30 min past the work day. **How do I let her know that she's the one benefitting at my expense for something that is completely voluntary by myself and only serves to help her?** I refuse to stop asking her not to be late or to take back what I said before because I think I'm being perfectly reasonable. She thinks me saying that is "disrespectful and dictatorish". I'd prefer for this to not be the reason to end a friendship but I won't stand for disrespect. I don't mind this arrangement but I do mind her attitude. I think I'm only doing her a favor. Sure I oversleep sometimes but I literally have 35+ alarms set over a 60 min period between my phone and 5 different clocks. I know, ridiculous. So it's not like I try to oversleep. I have a half-hearted apology which I could do better but the reason I don't drop the subject is because she demands respect and acts like only she's in the right (mind you I don't have to give her rides at all and they're free for her).
2018/09/06
[ "https://interpersonal.stackexchange.com/questions/18265", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/21520/" ]
If you want your colleague to be on time ---------------------------------------- First off, **try to always be on time yourself**. It's much easier to demand other people to be on time if you set an example. Second, stop calling it "carpooling". What you do is not really a case of car sharing, instead **you give her a ride**. Use this exact wording, e.g. "sorry I can't give you a ride tomorrow" or "I can give you a ride at 6:30". That should serve as a reminder that your colleague is the one to benefit from the arrangement. Finally, **announce the hours which suit you** often and make her agree: "I'm driving to work at 6:30 and plan to drive back at 5:00, is that OK?". If she says "no" you simply tell her she'll have to use the subway. If she agrees, that gives you a fresh argument against her being late in the morning or wanting to stay late in the evening. Alternatively ------------- Consider asking her to contribute to the rides. If you split gas expenses 50/50, perhaps it wouldn't be so much of a problem for you to occasionally wait for her 5-7 minutes in the morning when she's late, and stay 15 extra minutes in the evening when she has something urgent to finish.
Desperate times require desperate measures. Here I make assumption that your pooling buddy doesn't really react well to verbal pleads made in "good will". And also due to their personality/identity/character your buddy fails to realize that this behaviour is not acceptable. Basically your buddy is getting a "free ride" and doesn't "feel pain" of being late or smth. Basically we need your buddy to start feeling the "pain of responsibility". And IMHO the best way to do it - to introduce "financial responsibility" or so it "hurts financially". Asking for .50$ per mile is pointless, as it doesn't really give you any advantage. Now when the person is late - they can claim that they pay you for mileage and you're still bugging them with being late and "do not hold on to your side of responsibility" (that would be cheeky, but some people don't have boundaries... and twist situations to their advantage...) The idea of @Kyralessa is good, but $6 for being late still feels like a free ride, plus actually the actual process of getting paid (finding notes, finding change, will be annoying and taxing to you). I would proppose, that you introduce "carpool driver respect deposit". The deposit may be "topped up" in the beginning of the month. Your buddy gives you $100 as the deposit (yes, it can't be small money like $10). Remember that this money is NOT "payment" for the ride (you still hold the claim that you give them the ride for free and maintain leverage). The purpose of the deposit - is to give your buddy flexibility to be late when they want, but under given conditions and with the price to pay for being late. (Again, remember, that the ride is still free!) Now the interesting part: **The Being Late Tarifs** * every time buddy is late [1min-5min] from the deposit is deduced a $5 fee * every time buddy is late [6min-10min] from deposit deducted $20 fee * every time buddy is late [11min-15min] from deposit deducted $50 fee * [16min+] you can either just charge $100 or just take off The purpose here is to use **exponential raise** in tariff to drive necessary behaviour from your buddy: * If you're little late (happens to all of us, once a week you can afford to pay $5) * if you're late - shell out $20 and try harder next time * if you're very late - well, the annoyance one feels shelling out $50 bucks for being late should make person feel the pain you feel when being very late. Also on shaming, etc. Important part is that - you still offer the ride for free, so you have the upper hand. No one can have any decent arguments against you, as you're giving person free rides. It's them paying for the "disrespect" or "being late" or whatever you prefer to call them. They're absolutely free to arrive on time and get free ride. The only "iron rule" you should define since the very early stage and stick to it: > > **No money in the "driver respect deposit" - no ride** > > > The argument you can make: "You want a free ride - show me some respect!" HTH ps. Of course such financial ways of motivation may look from first sight weird and awkward and shouldn't occur when people respect each other's time. But as I wrote in the opening: desperate times require desperate measures.
18,265
**TL;DR:** I drive to work at my own expense. My friend gets a free ride from me, saving her money and time. I say "don't be late" sometimes, and she freaks out. --- So I live in a metropolitan area and have a vehicle. I have a friend/coworker who ditched her car when she moved here so she takes the metro by default. She has been late before but I have too, and I have a history of oversleeping as I am a heavy sleeper. Sometimes, and infrequently, I will simply say when I will plan on picking her up from the metro (as she takes a much shorter metro ride to my place to get carpool ride vs taking the metro all the way to work) so will say something like "I'm leaving at 600. Don't be late!". For whatever reason, she freaks out that I have the audacity to say "don't be late" when I have overslept before, which I said last night and overslept today. I tried to explain that I'm not being a hypocrite and only say it as a friendly reminder, as we are not infallible but she's not having it. Some details: * I have a car, she does not * My commute is 20-30 min in my vehicle, her commute on metro is about an hour, her commute when carpooling is about 25-35 min (short metro ride and then carpool) * I spend a minimum of $70 in gas a month just commuting, she would spent at most $160 a month ($8 round trip per day x ~20 work days in a month) BUT she's part of a subsidy program for mass transit users which has a max allowance of $245/mo but I don't know how much she's receiving. * She does not pay me anything, ever. I don't ask but she never offers anything more than a "thanks". * Half the time, she doesn't even ride home with me because she decides to stay later to build credit hours at work or will make me wait for her * I was a GS-07 and she is a GS-09 (roughly $45k/year and $55k/year respectively, but I am a 09 now and she is becoming an 11 ($55 and $65 respectively). This is only relevant because she complains about money and not being able to afford the metro (despite the subsidy). * She also has another coworker that gives her rides (same situation but he lives close enough that he picks her up directly and she doesn't need the short metro ride over). It's not my fault she **GAVE** her car to her sister back at home. Just an example of how she acts, this one time she asked to stay 15 min later to build 15 min of credit hours, which is ridiculous if you ask me. I said I didn't want to but she insisted so I said okay and said I'll work on my project. I needed 15 min more than she did and when the first 15 min passed and she said she was done, I said I need 15 min more and she acted like that was ridiculous and she didn't want to have to wait for me, so we ended up staying 30 min past the work day. **How do I let her know that she's the one benefitting at my expense for something that is completely voluntary by myself and only serves to help her?** I refuse to stop asking her not to be late or to take back what I said before because I think I'm being perfectly reasonable. She thinks me saying that is "disrespectful and dictatorish". I'd prefer for this to not be the reason to end a friendship but I won't stand for disrespect. I don't mind this arrangement but I do mind her attitude. I think I'm only doing her a favor. Sure I oversleep sometimes but I literally have 35+ alarms set over a 60 min period between my phone and 5 different clocks. I know, ridiculous. So it's not like I try to oversleep. I have a half-hearted apology which I could do better but the reason I don't drop the subject is because she demands respect and acts like only she's in the right (mind you I don't have to give her rides at all and they're free for her).
2018/09/06
[ "https://interpersonal.stackexchange.com/questions/18265", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/21520/" ]
**Train here**. You want to ride... I vow that I will never leave the station early. *That*, I can control. As for "late", you gotta understand. Stuff happens, paperwork, responsibil-- ok look, at the end of the day, it's because **I'm the train and that's how it is for trains**. That might seem unfair, that she owes you timekeeping and you don't owe it back in equal measure, but that is a reality when you are the train. So from my perspective... if she's at the agreed place at the scheduled time, and you're not, the only possible reason is that you're late. You didn't leave early - you *wouldn't*. So she can wait a few minutes and along you'll come. And then, you do your fair level best to stick to timekeeping. End of the day, if *your best* isn't good enough for the customer, this mode of transport may not be for them. Main thing is: **You do the best you can do, *and don't worry about it***. Since you only have one passenger, lucky you, you're free to negotiate of course. If she runs late and calls you, and you're agreeable, you can wait if you want, but you don't owe her that. Just stick to what works for you. In your case, your friend always has a plan-B to get home, so she's not dependent. *One more thing, I'll tell you a secret. Running a couple minutes late actually helps stragglers. Even with cell phones pulling time off satellites, not everyone's phone is synchronized to the second. Happens all the time where a straggler rolls up to the station with their watch showing 7:00 and mine says 7:01, and I'da been gone.* Let the schedule slide a minute or two, and a bunch of passenger complaints just go away.
Your arrangement is operating on the basis of **[social norms](https://whistlinginthewind.org/2013/01/15/predictably-irrational-chapter-4-the-cost-of-social-norms/)**, and it isn't working out because she's not taking care to be socially acceptable. I suggest you change your arrangement to operate on **market norms**. As I noted above, even your $70/month for gas doesn't reflect the true costs of owning a car: * gas * maintenance * insurance * wear-and-tear (eventually requiring the purchase of a replacement car) A better reflection would be a standard mileage rate, such as the [IRS mileage reimbursement rate of **54.5c/mile** for 2018](https://www.irs.gov/newsroom/standard-mileage-rates-for-2018-up-from-rates-for-2017). I'm going to guess that your commute is about 12 miles one way. At 54.5 cents per mile, that's $6.54 per one-way trip. On that basis, commuting by car is costing you about $283/month. Now you know the cost of her ride: **$3.27 per one-way trip.** And now that you know that, you can decide how you want her to pay. One option is for her to pay when she rides with you, but not when she doesn't because she's late. That way she can be less upset about being late, because she's saving $3.27 each time. Another option is to allow her to continue not paying, but impose a penalty whenever she's late. How much would be enough to leave you happy to be getting the extra cash rather than upset about the lateness? Perhaps $2 per 5 minutes of lateness, for example. Her 15 minutes of extra "credit time" would net you $6 in exchange for waiting for her, and she can decide if it's worth $6 to her to get credit time and make you late. Sometimes it's a bad idea to replace social norms with market norms, because it allows people to shamelessly pay to continue to engage in bad behavior. But in this case she doesn't seem to have any shame (in fact, **she's** trying to shame **you**!), so you have nothing to lose here.
18,265
**TL;DR:** I drive to work at my own expense. My friend gets a free ride from me, saving her money and time. I say "don't be late" sometimes, and she freaks out. --- So I live in a metropolitan area and have a vehicle. I have a friend/coworker who ditched her car when she moved here so she takes the metro by default. She has been late before but I have too, and I have a history of oversleeping as I am a heavy sleeper. Sometimes, and infrequently, I will simply say when I will plan on picking her up from the metro (as she takes a much shorter metro ride to my place to get carpool ride vs taking the metro all the way to work) so will say something like "I'm leaving at 600. Don't be late!". For whatever reason, she freaks out that I have the audacity to say "don't be late" when I have overslept before, which I said last night and overslept today. I tried to explain that I'm not being a hypocrite and only say it as a friendly reminder, as we are not infallible but she's not having it. Some details: * I have a car, she does not * My commute is 20-30 min in my vehicle, her commute on metro is about an hour, her commute when carpooling is about 25-35 min (short metro ride and then carpool) * I spend a minimum of $70 in gas a month just commuting, she would spent at most $160 a month ($8 round trip per day x ~20 work days in a month) BUT she's part of a subsidy program for mass transit users which has a max allowance of $245/mo but I don't know how much she's receiving. * She does not pay me anything, ever. I don't ask but she never offers anything more than a "thanks". * Half the time, she doesn't even ride home with me because she decides to stay later to build credit hours at work or will make me wait for her * I was a GS-07 and she is a GS-09 (roughly $45k/year and $55k/year respectively, but I am a 09 now and she is becoming an 11 ($55 and $65 respectively). This is only relevant because she complains about money and not being able to afford the metro (despite the subsidy). * She also has another coworker that gives her rides (same situation but he lives close enough that he picks her up directly and she doesn't need the short metro ride over). It's not my fault she **GAVE** her car to her sister back at home. Just an example of how she acts, this one time she asked to stay 15 min later to build 15 min of credit hours, which is ridiculous if you ask me. I said I didn't want to but she insisted so I said okay and said I'll work on my project. I needed 15 min more than she did and when the first 15 min passed and she said she was done, I said I need 15 min more and she acted like that was ridiculous and she didn't want to have to wait for me, so we ended up staying 30 min past the work day. **How do I let her know that she's the one benefitting at my expense for something that is completely voluntary by myself and only serves to help her?** I refuse to stop asking her not to be late or to take back what I said before because I think I'm being perfectly reasonable. She thinks me saying that is "disrespectful and dictatorish". I'd prefer for this to not be the reason to end a friendship but I won't stand for disrespect. I don't mind this arrangement but I do mind her attitude. I think I'm only doing her a favor. Sure I oversleep sometimes but I literally have 35+ alarms set over a 60 min period between my phone and 5 different clocks. I know, ridiculous. So it's not like I try to oversleep. I have a half-hearted apology which I could do better but the reason I don't drop the subject is because she demands respect and acts like only she's in the right (mind you I don't have to give her rides at all and they're free for her).
2018/09/06
[ "https://interpersonal.stackexchange.com/questions/18265", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/21520/" ]
I don't think you're being unreasonable at all. There are many reasons why this arrangement is to your disadvantage, and there seems to be no benefit to yourself. Regarding the fact she sometimes makes you late: you mention that you are sometimes late yourself even without her. Well, almost everybody is sometimes, but would you agree that most people know how much lateness they can afford? Irrespective of whether you need to be in work by a time stipulated by your employer or because it suits your own schedule, if you can be "late" yourself then you probably can't afford for someone else to make you late too. It doesn't matter whether your colleague thinks you are a hypocrite for asking her not to be late, fact is that she could make *you* late when you can't afford to be. This fact alone would make many conclude it might be better for you each to be responsible for getting your own selves to work on time. Regarding her lack of contribution: well, this is a matter of *her* etiquette, not yours. Perhaps she reasons that as there is no additional cost to you (the details you give suggest you don't go out of your way, and she meets you en route) that she isn't *costing* you anything so there is no need to contribute. Of course, this isn't really in the spirit of carpooling. It is supposed to be a *sharing of resources* to save money and be more environmentally friendly among other things. Most people would offer to share the costs, especially if a fair percentage of your fuel costs is less than their public transport costs. Also, I believe your two incomes are completely irrelevant to the situation. Sure, the fact she earns more than you does make her complaints about her salary and also her lack of contribution to you a little more insulting, but even if the salaries were the other way around it would only be good etiquette to offer you a contribution. Considering all of this, and after further discussion with you, to be honest I don't think what you have with this colleague even fits the definition of "[carpooling](https://en.wikipedia.org/wiki/Carpool)". There are no shared savings from the arrangement. In fact there isn't much of an arrangement either - she rides with other people or you as and when she feels like it. It seems that what you do is entirely for her benefit. This isn't a site for telling you what to do. Rather we try to help address problems in an interpersonal way. Whether you choose to end the arrangement or try and fix it you would need to talk to her. In either case, we advocate honesty and you should just be straight with her to avoid any ambiguity. If you want to end the arrangement you could perhaps say: > > I've been thinking about our car pooling, and it seems that on the whole we have different schedules. I want to be in work by 06:00 each day because this supports my preferred finishing time. **Sorry, but that means it isn't possible for me to give you a ride anymore.** > > > Alternatively, if you feel the situation could be rescued you could say: > > I've been thinking about our car pooling, and it seems that on the whole we have different schedules. I want to be in work by 06:00 each day because this supports my preferred finishing time. **I'd be happy to continue giving you a ride if you can fit in with that preference**. > > > And see what she says. She may choose to get a ride with the other colleague instead, which is win-win. You don't *owe* it to anybody to take them into work. Your employer will see you all as individually responsible for getting to work. What you have been doing for her is a kind gesture, even if she contributed, because you do not have to do it. I believe the approach above which focuses on *your* preference to be in work on time will be better received than if you tackle her about *her* attitude or lack of contribution. Getting her to see it from your point of view may even prompt her to address the latter.
If you want your colleague to be on time ---------------------------------------- First off, **try to always be on time yourself**. It's much easier to demand other people to be on time if you set an example. Second, stop calling it "carpooling". What you do is not really a case of car sharing, instead **you give her a ride**. Use this exact wording, e.g. "sorry I can't give you a ride tomorrow" or "I can give you a ride at 6:30". That should serve as a reminder that your colleague is the one to benefit from the arrangement. Finally, **announce the hours which suit you** often and make her agree: "I'm driving to work at 6:30 and plan to drive back at 5:00, is that OK?". If she says "no" you simply tell her she'll have to use the subway. If she agrees, that gives you a fresh argument against her being late in the morning or wanting to stay late in the evening. Alternatively ------------- Consider asking her to contribute to the rides. If you split gas expenses 50/50, perhaps it wouldn't be so much of a problem for you to occasionally wait for her 5-7 minutes in the morning when she's late, and stay 15 extra minutes in the evening when she has something urgent to finish.