qid
int64
469
74.7M
question
stringlengths
36
37.8k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
5
31.5k
response_k
stringlengths
10
31.6k
15,012,098
I know this is a very dumb question, but I can't install CherryPy. In the documentation is written: > > To install, change to the directory where setup.py is located and type (python-2.3 or later needed): > > > > ``` > python setup.py install > > ``` > > Which is what I do, I type this in Python Shell and it gives me error `Invalid syntax`, but I don't think I have any syntax errors.
2013/02/21
[ "https://Stackoverflow.com/questions/15012098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025568/" ]
I have found out the steps to install via command prompt, please fer to the attachment below. For me "python setup.py install" does not work but it works find for "setup.py install" after I pointed it properly to the directory> Hope my experiment helps: [Step1](https://i.stack.imgur.com/A0LlF.jpg) [Step2](https://i.stack.imgur.com/sFspL.jpg)
If you are installing on Mac and say you are using python 3, you would want to use: ``` sudo python3.3 setup.py build ``` Then after build is finished. ``` sudo python3.3 setup.py install ```
56,187,994
Hello I have solved this leetcode question <https://leetcode.com/problems/single-number-ii>. The objective is to solve the problem in O(n) time and 0(1) space. The code I wrote is the following: ``` class Solution: def singleNumber(self, nums: List[int]) -> int: counter = [0 for i in range(32)] result = 0 for i in range(32): for num in nums: if ((num >> i) & 1): counter[i] += 1 result = result | ((counter[i] % 3) << i) return self.convert(result) #return result def convert(self,x): if x >= 2**31: x = (~x & 0xffffffff) + 1 x = -x return x ``` Now the interesting part is in the `convert` function, since python uses objects to store `int` as opposed to a 32 bit word or something, it does not know that the result is negative when the MSB of my `counter` is set to 1. I handle that by converting it to its 2's complement and returning the negative value. Now someone else posted their solution with: ``` def convert(self, x): if x >= 2**31: x -= 2**32 return x ``` And I can't figure out why that works. I need help understanding why this subtraction works.
2019/05/17
[ "https://Stackoverflow.com/questions/56187994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10495398/" ]
32-bit signed integers wrap around every `2**32`, so a positive number with the the sign bit set (ie `>= 2**31`) has the same binary representation as the negative number `2**32` less.
That is the very definition of two's complement code of a number A on n bits. * if number A is positive use the binary code of A * if A is negative, use the binary code of 2^n+A (or 2^n-|A|). This number is the one you have to add to |A| to get 2^n (i.e. the complement of |A| to 2^n, hence the name of the two's complement method). So, if you have a negative number B coded in two's complement, what is actually in its code is 2^N+B. To get its value, you have to substract 2^N from B. There are many other definitions of two's complement (~A+1, ~(A-1), etc), but this one is the most useful as it explains why adding signed two's complement numbers is absolutely identical to adding positive numbers. The number is in the code (with 2^32 added if negative) and the addition result will be correct, provided you ignore the 2^32 that may be generated as a carry out (and there is no overflow). This arithmetic property is the main reason why two's complement is used in computers.
56,187,994
Hello I have solved this leetcode question <https://leetcode.com/problems/single-number-ii>. The objective is to solve the problem in O(n) time and 0(1) space. The code I wrote is the following: ``` class Solution: def singleNumber(self, nums: List[int]) -> int: counter = [0 for i in range(32)] result = 0 for i in range(32): for num in nums: if ((num >> i) & 1): counter[i] += 1 result = result | ((counter[i] % 3) << i) return self.convert(result) #return result def convert(self,x): if x >= 2**31: x = (~x & 0xffffffff) + 1 x = -x return x ``` Now the interesting part is in the `convert` function, since python uses objects to store `int` as opposed to a 32 bit word or something, it does not know that the result is negative when the MSB of my `counter` is set to 1. I handle that by converting it to its 2's complement and returning the negative value. Now someone else posted their solution with: ``` def convert(self, x): if x >= 2**31: x -= 2**32 return x ``` And I can't figure out why that works. I need help understanding why this subtraction works.
2019/05/17
[ "https://Stackoverflow.com/questions/56187994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10495398/" ]
Python integers are infinitely large. They will not turn negative as you add more bits so two's complement may not work as expected. You could manage negatives differently. ``` def singleNumber(nums): result = 0 sign = [1,-1][sum(int(n<0) for n in nums)%3] for i in range(32): counter = 0 for num in nums: counter += (abs(num) >> i) & 1 result = result | ((counter % 3) << i) return result * sign ``` This binary approach can be optimized and simplified like this: ``` def singleNumber(nums): result = 0 for i in range(32): counter = sum(1 for n in nums if (n>>i)&1) if counter > 0: result |= (counter % 3) << i return result - 2*(result&(1<<31)) ``` If you like one liners, you can implement it using reduce() from functools: ``` result = reduce(lambda r,i:r|sum(1&(n>>i) for n in nums)%3<<i,range(32),sum(n<0 for n in nums)%3*(-1<<32)) ``` *Note that this approach will always do 32 passes through the data and will be limited to numbers in the range -2^31...2^31. Increasing this range will systematically augment the number of passes through the list of numbers (even if the list only contains small values). Also, since you're not using counter[i] outside of the i loop, you don't need a list to store the counters.* You could leverage base 3 instead of base 2 using a very similar approach (which also responds in O(n) time and O(1) space): ``` def singleNumber(nums): result = sign = 0 for num in nums: if num<0 : sign += 1 base3 = 1 num = abs(num) while num > 0 : num,rest = divmod(num,3) rest,base3 = rest*base3, 3*base3 if rest == 0 : continue digit = result % base3 result = result - digit + (digit+rest)%base3 return result * (1-sign%3*2) ``` *This one has the advantage that it will go through the list only once (thus supporting iterators as input). It does not limit the range of values and will perform the nested while loop as few times as possible (in accordance with the magnitude of each value)* The way it works is by adding digits independently in a base 3 representation and cycling the result (digit by digit) without applying a carry. For example: [ 16, 16, 32, 16 ] ``` Base10 Base 3 Base 3 digits result (cumulative) ------ ------ ------------- ------ 16 121 0 | 1 | 2 | 1 121 16 121 0 | 1 | 2 | 1 212 32 2012 2 | 0 | 1 | 2 2221 16 121 0 | 1 | 2 | 1 2012 ------------- sum of digits % 3 2 | 0 | 1 | 2 ==> 32 ``` The `while num > 0` loop processes the digits. It will run at most log(V,3) times where V is the largest absolute value in the numbers list. As such it is similar to the `for i in range(32)` loop in the base 2 solution except that it always uses the smallest possible range. For any given pattern of values, the number of iterations of that while loop is going to be less or equal to a constant thus preserving the O(n) complexity of the main loop. I made a few performance tests and, in practice, the base3 version is only faster than the base2 approach when values are small. The base3 approach always performs fewer iterations but, when values are large, it loses out in total execution time because of the overhead of modulo vs bitwise operations. In order for the base2 solution to always be faster than the base 3 approach, it needs to optimize its iterations through the bits by reversing the loop nesting (bits inside numbers instead of numbers inside bits): ``` def singleNumber(nums): bits = [0]*len(bin(max(nums,key=abs))) sign = 0 for num in nums: if num<0 : sign += 1 num = abs(num) bit = 0 while num > 0: if num&1 : bits[bit] += 1 bit += 1 num >>= 1 result = sum(1<<bit for bit,count in enumerate(bits) if count%3) return result * [1,-1][sign%3] ``` *Now it will outperform the base 3 approach every time. As a side benefit, it is no longer limited by a value range and will support iterators as input. Note that the size of the bits array can be treated as a constant so this is also a O(1) space solution* But, to be fair, if we apply the same optimization to the base 3 approach (i.e. using a list of base 3 'bits'), its performance comes back in front for all value sizes: ``` def singleNumber(nums): tribits = [0]*len(bin(max(nums,key=abs))) # enough base 2 -> enough 3 sign = 0 for num in nums: if num<0 : sign += 1 num = abs(num) base3 = 0 while num > 0: digit = num%3 if digit: tribits[base3] += digit base3 += 1 num //= 3 result = sum(count%3 * 3**base3 for base3,count in enumerate(tribits) if count%3) return result * [1,-1][sign%3] ``` . Counter from collections would give the expected result in O(n) time with a single line of code: ``` from collections import Counter numbers = [1,0,1,0,1,0,99] singleN = next(n for n,count in Counter(numbers).items() if count == 1) ``` Sets would also work in O(n): ``` distinct = set() multiple = [n for n in numbers if n in distinct or distinct.add(n)] singleN = min(distinct.difference(multiple)) ``` *These last two solutions do use a variable amount of extra memory that is proportional to the size of the list (i.e. not O(1) space). On the other hand, they run 30 times faster and they will support any data type in the list. They also support iterators*
That is the very definition of two's complement code of a number A on n bits. * if number A is positive use the binary code of A * if A is negative, use the binary code of 2^n+A (or 2^n-|A|). This number is the one you have to add to |A| to get 2^n (i.e. the complement of |A| to 2^n, hence the name of the two's complement method). So, if you have a negative number B coded in two's complement, what is actually in its code is 2^N+B. To get its value, you have to substract 2^N from B. There are many other definitions of two's complement (~A+1, ~(A-1), etc), but this one is the most useful as it explains why adding signed two's complement numbers is absolutely identical to adding positive numbers. The number is in the code (with 2^32 added if negative) and the addition result will be correct, provided you ignore the 2^32 that may be generated as a carry out (and there is no overflow). This arithmetic property is the main reason why two's complement is used in computers.
56,187,994
Hello I have solved this leetcode question <https://leetcode.com/problems/single-number-ii>. The objective is to solve the problem in O(n) time and 0(1) space. The code I wrote is the following: ``` class Solution: def singleNumber(self, nums: List[int]) -> int: counter = [0 for i in range(32)] result = 0 for i in range(32): for num in nums: if ((num >> i) & 1): counter[i] += 1 result = result | ((counter[i] % 3) << i) return self.convert(result) #return result def convert(self,x): if x >= 2**31: x = (~x & 0xffffffff) + 1 x = -x return x ``` Now the interesting part is in the `convert` function, since python uses objects to store `int` as opposed to a 32 bit word or something, it does not know that the result is negative when the MSB of my `counter` is set to 1. I handle that by converting it to its 2's complement and returning the negative value. Now someone else posted their solution with: ``` def convert(self, x): if x >= 2**31: x -= 2**32 return x ``` And I can't figure out why that works. I need help understanding why this subtraction works.
2019/05/17
[ "https://Stackoverflow.com/questions/56187994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10495398/" ]
The value of the highest bit of an **unsigned** n-bit number is **2n-1**. The value of the highest bit of a **signed** two's complement n-bit number is **-2n-1**. The **difference** between those two values is **2n**. So if a unsigned n-bit number has the highest bit set, to convert to a two's complement signed number subtract **2n**. In a 32-bit number, if bit 31 is set, the number will be >= 231, so the formula would be: ``` if n >= 2**31: n -= 2**32 ``` I hope that makes it clear.
That is the very definition of two's complement code of a number A on n bits. * if number A is positive use the binary code of A * if A is negative, use the binary code of 2^n+A (or 2^n-|A|). This number is the one you have to add to |A| to get 2^n (i.e. the complement of |A| to 2^n, hence the name of the two's complement method). So, if you have a negative number B coded in two's complement, what is actually in its code is 2^N+B. To get its value, you have to substract 2^N from B. There are many other definitions of two's complement (~A+1, ~(A-1), etc), but this one is the most useful as it explains why adding signed two's complement numbers is absolutely identical to adding positive numbers. The number is in the code (with 2^32 added if negative) and the addition result will be correct, provided you ignore the 2^32 that may be generated as a carry out (and there is no overflow). This arithmetic property is the main reason why two's complement is used in computers.
56,187,994
Hello I have solved this leetcode question <https://leetcode.com/problems/single-number-ii>. The objective is to solve the problem in O(n) time and 0(1) space. The code I wrote is the following: ``` class Solution: def singleNumber(self, nums: List[int]) -> int: counter = [0 for i in range(32)] result = 0 for i in range(32): for num in nums: if ((num >> i) & 1): counter[i] += 1 result = result | ((counter[i] % 3) << i) return self.convert(result) #return result def convert(self,x): if x >= 2**31: x = (~x & 0xffffffff) + 1 x = -x return x ``` Now the interesting part is in the `convert` function, since python uses objects to store `int` as opposed to a 32 bit word or something, it does not know that the result is negative when the MSB of my `counter` is set to 1. I handle that by converting it to its 2's complement and returning the negative value. Now someone else posted their solution with: ``` def convert(self, x): if x >= 2**31: x -= 2**32 return x ``` And I can't figure out why that works. I need help understanding why this subtraction works.
2019/05/17
[ "https://Stackoverflow.com/questions/56187994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10495398/" ]
Python integers are infinitely large. They will not turn negative as you add more bits so two's complement may not work as expected. You could manage negatives differently. ``` def singleNumber(nums): result = 0 sign = [1,-1][sum(int(n<0) for n in nums)%3] for i in range(32): counter = 0 for num in nums: counter += (abs(num) >> i) & 1 result = result | ((counter % 3) << i) return result * sign ``` This binary approach can be optimized and simplified like this: ``` def singleNumber(nums): result = 0 for i in range(32): counter = sum(1 for n in nums if (n>>i)&1) if counter > 0: result |= (counter % 3) << i return result - 2*(result&(1<<31)) ``` If you like one liners, you can implement it using reduce() from functools: ``` result = reduce(lambda r,i:r|sum(1&(n>>i) for n in nums)%3<<i,range(32),sum(n<0 for n in nums)%3*(-1<<32)) ``` *Note that this approach will always do 32 passes through the data and will be limited to numbers in the range -2^31...2^31. Increasing this range will systematically augment the number of passes through the list of numbers (even if the list only contains small values). Also, since you're not using counter[i] outside of the i loop, you don't need a list to store the counters.* You could leverage base 3 instead of base 2 using a very similar approach (which also responds in O(n) time and O(1) space): ``` def singleNumber(nums): result = sign = 0 for num in nums: if num<0 : sign += 1 base3 = 1 num = abs(num) while num > 0 : num,rest = divmod(num,3) rest,base3 = rest*base3, 3*base3 if rest == 0 : continue digit = result % base3 result = result - digit + (digit+rest)%base3 return result * (1-sign%3*2) ``` *This one has the advantage that it will go through the list only once (thus supporting iterators as input). It does not limit the range of values and will perform the nested while loop as few times as possible (in accordance with the magnitude of each value)* The way it works is by adding digits independently in a base 3 representation and cycling the result (digit by digit) without applying a carry. For example: [ 16, 16, 32, 16 ] ``` Base10 Base 3 Base 3 digits result (cumulative) ------ ------ ------------- ------ 16 121 0 | 1 | 2 | 1 121 16 121 0 | 1 | 2 | 1 212 32 2012 2 | 0 | 1 | 2 2221 16 121 0 | 1 | 2 | 1 2012 ------------- sum of digits % 3 2 | 0 | 1 | 2 ==> 32 ``` The `while num > 0` loop processes the digits. It will run at most log(V,3) times where V is the largest absolute value in the numbers list. As such it is similar to the `for i in range(32)` loop in the base 2 solution except that it always uses the smallest possible range. For any given pattern of values, the number of iterations of that while loop is going to be less or equal to a constant thus preserving the O(n) complexity of the main loop. I made a few performance tests and, in practice, the base3 version is only faster than the base2 approach when values are small. The base3 approach always performs fewer iterations but, when values are large, it loses out in total execution time because of the overhead of modulo vs bitwise operations. In order for the base2 solution to always be faster than the base 3 approach, it needs to optimize its iterations through the bits by reversing the loop nesting (bits inside numbers instead of numbers inside bits): ``` def singleNumber(nums): bits = [0]*len(bin(max(nums,key=abs))) sign = 0 for num in nums: if num<0 : sign += 1 num = abs(num) bit = 0 while num > 0: if num&1 : bits[bit] += 1 bit += 1 num >>= 1 result = sum(1<<bit for bit,count in enumerate(bits) if count%3) return result * [1,-1][sign%3] ``` *Now it will outperform the base 3 approach every time. As a side benefit, it is no longer limited by a value range and will support iterators as input. Note that the size of the bits array can be treated as a constant so this is also a O(1) space solution* But, to be fair, if we apply the same optimization to the base 3 approach (i.e. using a list of base 3 'bits'), its performance comes back in front for all value sizes: ``` def singleNumber(nums): tribits = [0]*len(bin(max(nums,key=abs))) # enough base 2 -> enough 3 sign = 0 for num in nums: if num<0 : sign += 1 num = abs(num) base3 = 0 while num > 0: digit = num%3 if digit: tribits[base3] += digit base3 += 1 num //= 3 result = sum(count%3 * 3**base3 for base3,count in enumerate(tribits) if count%3) return result * [1,-1][sign%3] ``` . Counter from collections would give the expected result in O(n) time with a single line of code: ``` from collections import Counter numbers = [1,0,1,0,1,0,99] singleN = next(n for n,count in Counter(numbers).items() if count == 1) ``` Sets would also work in O(n): ``` distinct = set() multiple = [n for n in numbers if n in distinct or distinct.add(n)] singleN = min(distinct.difference(multiple)) ``` *These last two solutions do use a variable amount of extra memory that is proportional to the size of the list (i.e. not O(1) space). On the other hand, they run 30 times faster and they will support any data type in the list. They also support iterators*
32-bit signed integers wrap around every `2**32`, so a positive number with the the sign bit set (ie `>= 2**31`) has the same binary representation as the negative number `2**32` less.
56,187,994
Hello I have solved this leetcode question <https://leetcode.com/problems/single-number-ii>. The objective is to solve the problem in O(n) time and 0(1) space. The code I wrote is the following: ``` class Solution: def singleNumber(self, nums: List[int]) -> int: counter = [0 for i in range(32)] result = 0 for i in range(32): for num in nums: if ((num >> i) & 1): counter[i] += 1 result = result | ((counter[i] % 3) << i) return self.convert(result) #return result def convert(self,x): if x >= 2**31: x = (~x & 0xffffffff) + 1 x = -x return x ``` Now the interesting part is in the `convert` function, since python uses objects to store `int` as opposed to a 32 bit word or something, it does not know that the result is negative when the MSB of my `counter` is set to 1. I handle that by converting it to its 2's complement and returning the negative value. Now someone else posted their solution with: ``` def convert(self, x): if x >= 2**31: x -= 2**32 return x ``` And I can't figure out why that works. I need help understanding why this subtraction works.
2019/05/17
[ "https://Stackoverflow.com/questions/56187994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10495398/" ]
The value of the highest bit of an **unsigned** n-bit number is **2n-1**. The value of the highest bit of a **signed** two's complement n-bit number is **-2n-1**. The **difference** between those two values is **2n**. So if a unsigned n-bit number has the highest bit set, to convert to a two's complement signed number subtract **2n**. In a 32-bit number, if bit 31 is set, the number will be >= 231, so the formula would be: ``` if n >= 2**31: n -= 2**32 ``` I hope that makes it clear.
32-bit signed integers wrap around every `2**32`, so a positive number with the the sign bit set (ie `>= 2**31`) has the same binary representation as the negative number `2**32` less.
56,187,994
Hello I have solved this leetcode question <https://leetcode.com/problems/single-number-ii>. The objective is to solve the problem in O(n) time and 0(1) space. The code I wrote is the following: ``` class Solution: def singleNumber(self, nums: List[int]) -> int: counter = [0 for i in range(32)] result = 0 for i in range(32): for num in nums: if ((num >> i) & 1): counter[i] += 1 result = result | ((counter[i] % 3) << i) return self.convert(result) #return result def convert(self,x): if x >= 2**31: x = (~x & 0xffffffff) + 1 x = -x return x ``` Now the interesting part is in the `convert` function, since python uses objects to store `int` as opposed to a 32 bit word or something, it does not know that the result is negative when the MSB of my `counter` is set to 1. I handle that by converting it to its 2's complement and returning the negative value. Now someone else posted their solution with: ``` def convert(self, x): if x >= 2**31: x -= 2**32 return x ``` And I can't figure out why that works. I need help understanding why this subtraction works.
2019/05/17
[ "https://Stackoverflow.com/questions/56187994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10495398/" ]
The value of the highest bit of an **unsigned** n-bit number is **2n-1**. The value of the highest bit of a **signed** two's complement n-bit number is **-2n-1**. The **difference** between those two values is **2n**. So if a unsigned n-bit number has the highest bit set, to convert to a two's complement signed number subtract **2n**. In a 32-bit number, if bit 31 is set, the number will be >= 231, so the formula would be: ``` if n >= 2**31: n -= 2**32 ``` I hope that makes it clear.
Python integers are infinitely large. They will not turn negative as you add more bits so two's complement may not work as expected. You could manage negatives differently. ``` def singleNumber(nums): result = 0 sign = [1,-1][sum(int(n<0) for n in nums)%3] for i in range(32): counter = 0 for num in nums: counter += (abs(num) >> i) & 1 result = result | ((counter % 3) << i) return result * sign ``` This binary approach can be optimized and simplified like this: ``` def singleNumber(nums): result = 0 for i in range(32): counter = sum(1 for n in nums if (n>>i)&1) if counter > 0: result |= (counter % 3) << i return result - 2*(result&(1<<31)) ``` If you like one liners, you can implement it using reduce() from functools: ``` result = reduce(lambda r,i:r|sum(1&(n>>i) for n in nums)%3<<i,range(32),sum(n<0 for n in nums)%3*(-1<<32)) ``` *Note that this approach will always do 32 passes through the data and will be limited to numbers in the range -2^31...2^31. Increasing this range will systematically augment the number of passes through the list of numbers (even if the list only contains small values). Also, since you're not using counter[i] outside of the i loop, you don't need a list to store the counters.* You could leverage base 3 instead of base 2 using a very similar approach (which also responds in O(n) time and O(1) space): ``` def singleNumber(nums): result = sign = 0 for num in nums: if num<0 : sign += 1 base3 = 1 num = abs(num) while num > 0 : num,rest = divmod(num,3) rest,base3 = rest*base3, 3*base3 if rest == 0 : continue digit = result % base3 result = result - digit + (digit+rest)%base3 return result * (1-sign%3*2) ``` *This one has the advantage that it will go through the list only once (thus supporting iterators as input). It does not limit the range of values and will perform the nested while loop as few times as possible (in accordance with the magnitude of each value)* The way it works is by adding digits independently in a base 3 representation and cycling the result (digit by digit) without applying a carry. For example: [ 16, 16, 32, 16 ] ``` Base10 Base 3 Base 3 digits result (cumulative) ------ ------ ------------- ------ 16 121 0 | 1 | 2 | 1 121 16 121 0 | 1 | 2 | 1 212 32 2012 2 | 0 | 1 | 2 2221 16 121 0 | 1 | 2 | 1 2012 ------------- sum of digits % 3 2 | 0 | 1 | 2 ==> 32 ``` The `while num > 0` loop processes the digits. It will run at most log(V,3) times where V is the largest absolute value in the numbers list. As such it is similar to the `for i in range(32)` loop in the base 2 solution except that it always uses the smallest possible range. For any given pattern of values, the number of iterations of that while loop is going to be less or equal to a constant thus preserving the O(n) complexity of the main loop. I made a few performance tests and, in practice, the base3 version is only faster than the base2 approach when values are small. The base3 approach always performs fewer iterations but, when values are large, it loses out in total execution time because of the overhead of modulo vs bitwise operations. In order for the base2 solution to always be faster than the base 3 approach, it needs to optimize its iterations through the bits by reversing the loop nesting (bits inside numbers instead of numbers inside bits): ``` def singleNumber(nums): bits = [0]*len(bin(max(nums,key=abs))) sign = 0 for num in nums: if num<0 : sign += 1 num = abs(num) bit = 0 while num > 0: if num&1 : bits[bit] += 1 bit += 1 num >>= 1 result = sum(1<<bit for bit,count in enumerate(bits) if count%3) return result * [1,-1][sign%3] ``` *Now it will outperform the base 3 approach every time. As a side benefit, it is no longer limited by a value range and will support iterators as input. Note that the size of the bits array can be treated as a constant so this is also a O(1) space solution* But, to be fair, if we apply the same optimization to the base 3 approach (i.e. using a list of base 3 'bits'), its performance comes back in front for all value sizes: ``` def singleNumber(nums): tribits = [0]*len(bin(max(nums,key=abs))) # enough base 2 -> enough 3 sign = 0 for num in nums: if num<0 : sign += 1 num = abs(num) base3 = 0 while num > 0: digit = num%3 if digit: tribits[base3] += digit base3 += 1 num //= 3 result = sum(count%3 * 3**base3 for base3,count in enumerate(tribits) if count%3) return result * [1,-1][sign%3] ``` . Counter from collections would give the expected result in O(n) time with a single line of code: ``` from collections import Counter numbers = [1,0,1,0,1,0,99] singleN = next(n for n,count in Counter(numbers).items() if count == 1) ``` Sets would also work in O(n): ``` distinct = set() multiple = [n for n in numbers if n in distinct or distinct.add(n)] singleN = min(distinct.difference(multiple)) ``` *These last two solutions do use a variable amount of extra memory that is proportional to the size of the list (i.e. not O(1) space). On the other hand, they run 30 times faster and they will support any data type in the list. They also support iterators*
54,801,513
I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Anaconda's [download](https://www.anaconda.com/distribution/#download-section) page, there are only two versions i.e for Python 3.7 and Python 2.7 but I need for Python 3.6. Any help would be great.
2019/02/21
[ "https://Stackoverflow.com/questions/54801513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033492/" ]
You can download the 3.7 version and then [use](https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html) ``` conda create -n mygreatenvironment python=3.6 <add other packages here> ``` and then: ``` conda activate mygreatenvironment ``` This environment will use Python 3.6.
Following [this answer](https://stackoverflow.com/questions/41535881/how-do-i-upgrade-to-python-3-6-with-conda), this solution is working for me on windows 10, From the anaconda prompt : 1. Create a custom environnement and specify the repository channel to find the version (in my case 3.6.5) ``` conda create --name py365 python=3.6.5 --channel conda-forge ``` 2. Activate the new environment ``` conda activate py365 ``` But the activation won't be permanent, you will need to activate each time you start the anaconda prompt 3. Create a shortcut to Anaconda prompt with your choosen environment In order to activate permanently your custom environment, you can create a anaconda prompt shortcut which new target. Go to ``` C:\Users\Your_Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit) ``` And Copy and rename the file `Anaconda Prompt (Anaconda3)` to `Anaconda 3.6.5`. Then right-click on the new file and click on "Properties". Then change the target : ``` %windir%\System32\cmd.exe "/K" C:\Users\Your_Name\Anaconda3\Scripts\activate.bat C:\Users\Your_Name\Anaconda3 ``` to ``` %windir%\System32\cmd.exe "/K" C:\Users\Your_Name\Anaconda3\Scripts\activate.bat C:\Users\Your_Name\Anaconda3\envs\py365 ``` (be aware to change "Your\_Name" by your "real" name ) Finally, if you go to your Windows Start menu, you will see your new shortcut "Anaconda 3.6.5" which launch the Anaconda Prompt with your choosen environment !
54,801,513
I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Anaconda's [download](https://www.anaconda.com/distribution/#download-section) page, there are only two versions i.e for Python 3.7 and Python 2.7 but I need for Python 3.6. Any help would be great.
2019/02/21
[ "https://Stackoverflow.com/questions/54801513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033492/" ]
[This link](https://repo.continuum.io/archive/) has history version about Anaconda, you could download from this website. At version 5.3.0 python 3.6 support was dropped... > > Anaconda 5.3.0 (Sept 28, 2018) > ------------------------------ > > > ### User-facing changes > > > The Anaconda3 installers ship with python 3.7 instead of python 3.6 > > > python 3.6.5 -> 3.7.0 > > > <https://docs.anaconda.com/anaconda/reference/release-notes/#anaconda-5-3-0-sept-28-2018> The last version released with a python3.6 variant was version 5.2.0 > > Anaconda 5.2.0 (May 30, 2018) > ----------------------------- > > > python 3.6.4 -> 3.6.5 > > > <https://docs.anaconda.com/anaconda/reference/release-notes/#anaconda-5-2-0-may-30-2018> The links to this latest version are... * [Anaconda3-5.2.0-Linux-ppc64le.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-ppc64le.sh) * [Anaconda3-5.2.0-Linux-x86.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-x86.sh) * [Anaconda3-5.2.0-Linux-x86\_64.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-x86_64.sh) * [Anaconda3-5.2.0-MacOSX-x86\_64.pkg](https://repo.continuum.io/archive/Anaconda3-5.2.0-MacOSX-x86_64.pkg) * [Anaconda3-5.2.0-MacOSX-x86\_64.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-MacOSX-x86_64.sh) * [Anaconda3-5.2.0-Windows-x86.exe](https://repo.continuum.io/archive/Anaconda3-5.2.0-Windows-x86.exe) * [Anaconda3-5.2.0-Windows-x86\_64.exe](https://repo.continuum.io/archive/Anaconda3-5.2.0-Windows-x86_64.exe)
You can download the 3.7 version and then [use](https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html) ``` conda create -n mygreatenvironment python=3.6 <add other packages here> ``` and then: ``` conda activate mygreatenvironment ``` This environment will use Python 3.6.
54,801,513
I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Anaconda's [download](https://www.anaconda.com/distribution/#download-section) page, there are only two versions i.e for Python 3.7 and Python 2.7 but I need for Python 3.6. Any help would be great.
2019/02/21
[ "https://Stackoverflow.com/questions/54801513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033492/" ]
As suggested [here](https://stackoverflow.com/questions/52584907/how-to-downgrade-python-from-3-7-to-3-6), with an installation of the last anaconda you can create an environment just [like Cleb explained](https://stackoverflow.com/a/54801571/1534017) or downgrade python : ``` conda install python=3.6.0 ``` With this second solution, you may encounter some incompatibility issues with other packages. I tested it myself and did not encounter any issue but I guess it depends on the packages you installed. If you don't want to handle environments or face incompatibilities issues, you can download any Anaconda version here: <https://repo.continuum.io/archive/>. For example, Anaconda3-5.1.0-XXX or Anaconda3-5.2.0-XXX provides python 3.6 (the suffix XXX depends on your OS). To know which python is provided in an anaconda package, you can visit the [Release notes page](https://docs.anaconda.com/anaconda/reference/release-notes/). It provides the updates for the all anaconda versions. Find yours and look for the line > > python A.B.C -> X.Y.Z > > > where A.B.C is the previous version and X.Y.Z is the updated python version.
You can download anaconda from the archives. The path I followed was: Anaconda Documentation>Anaconda Distribution>Installation-(in page)System Requirements>[archive](https://docs.anaconda.com/anaconda/install/) I was looking for installation instructions on my CentOS machine when I stumbled upon the question.
54,801,513
I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Anaconda's [download](https://www.anaconda.com/distribution/#download-section) page, there are only two versions i.e for Python 3.7 and Python 2.7 but I need for Python 3.6. Any help would be great.
2019/02/21
[ "https://Stackoverflow.com/questions/54801513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033492/" ]
As suggested [here](https://stackoverflow.com/questions/52584907/how-to-downgrade-python-from-3-7-to-3-6), with an installation of the last anaconda you can create an environment just [like Cleb explained](https://stackoverflow.com/a/54801571/1534017) or downgrade python : ``` conda install python=3.6.0 ``` With this second solution, you may encounter some incompatibility issues with other packages. I tested it myself and did not encounter any issue but I guess it depends on the packages you installed. If you don't want to handle environments or face incompatibilities issues, you can download any Anaconda version here: <https://repo.continuum.io/archive/>. For example, Anaconda3-5.1.0-XXX or Anaconda3-5.2.0-XXX provides python 3.6 (the suffix XXX depends on your OS). To know which python is provided in an anaconda package, you can visit the [Release notes page](https://docs.anaconda.com/anaconda/reference/release-notes/). It provides the updates for the all anaconda versions. Find yours and look for the line > > python A.B.C -> X.Y.Z > > > where A.B.C is the previous version and X.Y.Z is the updated python version.
[This link](https://repo.continuum.io/archive/) has history version about Anaconda, you could download from this website. At version 5.3.0 python 3.6 support was dropped... > > Anaconda 5.3.0 (Sept 28, 2018) > ------------------------------ > > > ### User-facing changes > > > The Anaconda3 installers ship with python 3.7 instead of python 3.6 > > > python 3.6.5 -> 3.7.0 > > > <https://docs.anaconda.com/anaconda/reference/release-notes/#anaconda-5-3-0-sept-28-2018> The last version released with a python3.6 variant was version 5.2.0 > > Anaconda 5.2.0 (May 30, 2018) > ----------------------------- > > > python 3.6.4 -> 3.6.5 > > > <https://docs.anaconda.com/anaconda/reference/release-notes/#anaconda-5-2-0-may-30-2018> The links to this latest version are... * [Anaconda3-5.2.0-Linux-ppc64le.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-ppc64le.sh) * [Anaconda3-5.2.0-Linux-x86.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-x86.sh) * [Anaconda3-5.2.0-Linux-x86\_64.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-x86_64.sh) * [Anaconda3-5.2.0-MacOSX-x86\_64.pkg](https://repo.continuum.io/archive/Anaconda3-5.2.0-MacOSX-x86_64.pkg) * [Anaconda3-5.2.0-MacOSX-x86\_64.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-MacOSX-x86_64.sh) * [Anaconda3-5.2.0-Windows-x86.exe](https://repo.continuum.io/archive/Anaconda3-5.2.0-Windows-x86.exe) * [Anaconda3-5.2.0-Windows-x86\_64.exe](https://repo.continuum.io/archive/Anaconda3-5.2.0-Windows-x86_64.exe)
54,801,513
I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Anaconda's [download](https://www.anaconda.com/distribution/#download-section) page, there are only two versions i.e for Python 3.7 and Python 2.7 but I need for Python 3.6. Any help would be great.
2019/02/21
[ "https://Stackoverflow.com/questions/54801513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033492/" ]
[This link](https://repo.continuum.io/archive/) has history version about Anaconda, you could download from this website. At version 5.3.0 python 3.6 support was dropped... > > Anaconda 5.3.0 (Sept 28, 2018) > ------------------------------ > > > ### User-facing changes > > > The Anaconda3 installers ship with python 3.7 instead of python 3.6 > > > python 3.6.5 -> 3.7.0 > > > <https://docs.anaconda.com/anaconda/reference/release-notes/#anaconda-5-3-0-sept-28-2018> The last version released with a python3.6 variant was version 5.2.0 > > Anaconda 5.2.0 (May 30, 2018) > ----------------------------- > > > python 3.6.4 -> 3.6.5 > > > <https://docs.anaconda.com/anaconda/reference/release-notes/#anaconda-5-2-0-may-30-2018> The links to this latest version are... * [Anaconda3-5.2.0-Linux-ppc64le.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-ppc64le.sh) * [Anaconda3-5.2.0-Linux-x86.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-x86.sh) * [Anaconda3-5.2.0-Linux-x86\_64.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-x86_64.sh) * [Anaconda3-5.2.0-MacOSX-x86\_64.pkg](https://repo.continuum.io/archive/Anaconda3-5.2.0-MacOSX-x86_64.pkg) * [Anaconda3-5.2.0-MacOSX-x86\_64.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-MacOSX-x86_64.sh) * [Anaconda3-5.2.0-Windows-x86.exe](https://repo.continuum.io/archive/Anaconda3-5.2.0-Windows-x86.exe) * [Anaconda3-5.2.0-Windows-x86\_64.exe](https://repo.continuum.io/archive/Anaconda3-5.2.0-Windows-x86_64.exe)
You can download anaconda from the archives. The path I followed was: Anaconda Documentation>Anaconda Distribution>Installation-(in page)System Requirements>[archive](https://docs.anaconda.com/anaconda/install/) I was looking for installation instructions on my CentOS machine when I stumbled upon the question.
54,801,513
I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Anaconda's [download](https://www.anaconda.com/distribution/#download-section) page, there are only two versions i.e for Python 3.7 and Python 2.7 but I need for Python 3.6. Any help would be great.
2019/02/21
[ "https://Stackoverflow.com/questions/54801513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033492/" ]
As suggested [here](https://stackoverflow.com/questions/52584907/how-to-downgrade-python-from-3-7-to-3-6), with an installation of the last anaconda you can create an environment just [like Cleb explained](https://stackoverflow.com/a/54801571/1534017) or downgrade python : ``` conda install python=3.6.0 ``` With this second solution, you may encounter some incompatibility issues with other packages. I tested it myself and did not encounter any issue but I guess it depends on the packages you installed. If you don't want to handle environments or face incompatibilities issues, you can download any Anaconda version here: <https://repo.continuum.io/archive/>. For example, Anaconda3-5.1.0-XXX or Anaconda3-5.2.0-XXX provides python 3.6 (the suffix XXX depends on your OS). To know which python is provided in an anaconda package, you can visit the [Release notes page](https://docs.anaconda.com/anaconda/reference/release-notes/). It provides the updates for the all anaconda versions. Find yours and look for the line > > python A.B.C -> X.Y.Z > > > where A.B.C is the previous version and X.Y.Z is the updated python version.
Following [this answer](https://stackoverflow.com/questions/41535881/how-do-i-upgrade-to-python-3-6-with-conda), this solution is working for me on windows 10, From the anaconda prompt : 1. Create a custom environnement and specify the repository channel to find the version (in my case 3.6.5) ``` conda create --name py365 python=3.6.5 --channel conda-forge ``` 2. Activate the new environment ``` conda activate py365 ``` But the activation won't be permanent, you will need to activate each time you start the anaconda prompt 3. Create a shortcut to Anaconda prompt with your choosen environment In order to activate permanently your custom environment, you can create a anaconda prompt shortcut which new target. Go to ``` C:\Users\Your_Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit) ``` And Copy and rename the file `Anaconda Prompt (Anaconda3)` to `Anaconda 3.6.5`. Then right-click on the new file and click on "Properties". Then change the target : ``` %windir%\System32\cmd.exe "/K" C:\Users\Your_Name\Anaconda3\Scripts\activate.bat C:\Users\Your_Name\Anaconda3 ``` to ``` %windir%\System32\cmd.exe "/K" C:\Users\Your_Name\Anaconda3\Scripts\activate.bat C:\Users\Your_Name\Anaconda3\envs\py365 ``` (be aware to change "Your\_Name" by your "real" name ) Finally, if you go to your Windows Start menu, you will see your new shortcut "Anaconda 3.6.5" which launch the Anaconda Prompt with your choosen environment !
54,801,513
I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Anaconda's [download](https://www.anaconda.com/distribution/#download-section) page, there are only two versions i.e for Python 3.7 and Python 2.7 but I need for Python 3.6. Any help would be great.
2019/02/21
[ "https://Stackoverflow.com/questions/54801513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033492/" ]
[This link](https://repo.continuum.io/archive/) has history version about Anaconda, you could download from this website. At version 5.3.0 python 3.6 support was dropped... > > Anaconda 5.3.0 (Sept 28, 2018) > ------------------------------ > > > ### User-facing changes > > > The Anaconda3 installers ship with python 3.7 instead of python 3.6 > > > python 3.6.5 -> 3.7.0 > > > <https://docs.anaconda.com/anaconda/reference/release-notes/#anaconda-5-3-0-sept-28-2018> The last version released with a python3.6 variant was version 5.2.0 > > Anaconda 5.2.0 (May 30, 2018) > ----------------------------- > > > python 3.6.4 -> 3.6.5 > > > <https://docs.anaconda.com/anaconda/reference/release-notes/#anaconda-5-2-0-may-30-2018> The links to this latest version are... * [Anaconda3-5.2.0-Linux-ppc64le.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-ppc64le.sh) * [Anaconda3-5.2.0-Linux-x86.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-x86.sh) * [Anaconda3-5.2.0-Linux-x86\_64.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-Linux-x86_64.sh) * [Anaconda3-5.2.0-MacOSX-x86\_64.pkg](https://repo.continuum.io/archive/Anaconda3-5.2.0-MacOSX-x86_64.pkg) * [Anaconda3-5.2.0-MacOSX-x86\_64.sh](https://repo.continuum.io/archive/Anaconda3-5.2.0-MacOSX-x86_64.sh) * [Anaconda3-5.2.0-Windows-x86.exe](https://repo.continuum.io/archive/Anaconda3-5.2.0-Windows-x86.exe) * [Anaconda3-5.2.0-Windows-x86\_64.exe](https://repo.continuum.io/archive/Anaconda3-5.2.0-Windows-x86_64.exe)
Following [this answer](https://stackoverflow.com/questions/41535881/how-do-i-upgrade-to-python-3-6-with-conda), this solution is working for me on windows 10, From the anaconda prompt : 1. Create a custom environnement and specify the repository channel to find the version (in my case 3.6.5) ``` conda create --name py365 python=3.6.5 --channel conda-forge ``` 2. Activate the new environment ``` conda activate py365 ``` But the activation won't be permanent, you will need to activate each time you start the anaconda prompt 3. Create a shortcut to Anaconda prompt with your choosen environment In order to activate permanently your custom environment, you can create a anaconda prompt shortcut which new target. Go to ``` C:\Users\Your_Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit) ``` And Copy and rename the file `Anaconda Prompt (Anaconda3)` to `Anaconda 3.6.5`. Then right-click on the new file and click on "Properties". Then change the target : ``` %windir%\System32\cmd.exe "/K" C:\Users\Your_Name\Anaconda3\Scripts\activate.bat C:\Users\Your_Name\Anaconda3 ``` to ``` %windir%\System32\cmd.exe "/K" C:\Users\Your_Name\Anaconda3\Scripts\activate.bat C:\Users\Your_Name\Anaconda3\envs\py365 ``` (be aware to change "Your\_Name" by your "real" name ) Finally, if you go to your Windows Start menu, you will see your new shortcut "Anaconda 3.6.5" which launch the Anaconda Prompt with your choosen environment !
54,801,513
I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Anaconda's [download](https://www.anaconda.com/distribution/#download-section) page, there are only two versions i.e for Python 3.7 and Python 2.7 but I need for Python 3.6. Any help would be great.
2019/02/21
[ "https://Stackoverflow.com/questions/54801513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033492/" ]
Following [this answer](https://stackoverflow.com/questions/41535881/how-do-i-upgrade-to-python-3-6-with-conda), this solution is working for me on windows 10, From the anaconda prompt : 1. Create a custom environnement and specify the repository channel to find the version (in my case 3.6.5) ``` conda create --name py365 python=3.6.5 --channel conda-forge ``` 2. Activate the new environment ``` conda activate py365 ``` But the activation won't be permanent, you will need to activate each time you start the anaconda prompt 3. Create a shortcut to Anaconda prompt with your choosen environment In order to activate permanently your custom environment, you can create a anaconda prompt shortcut which new target. Go to ``` C:\Users\Your_Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit) ``` And Copy and rename the file `Anaconda Prompt (Anaconda3)` to `Anaconda 3.6.5`. Then right-click on the new file and click on "Properties". Then change the target : ``` %windir%\System32\cmd.exe "/K" C:\Users\Your_Name\Anaconda3\Scripts\activate.bat C:\Users\Your_Name\Anaconda3 ``` to ``` %windir%\System32\cmd.exe "/K" C:\Users\Your_Name\Anaconda3\Scripts\activate.bat C:\Users\Your_Name\Anaconda3\envs\py365 ``` (be aware to change "Your\_Name" by your "real" name ) Finally, if you go to your Windows Start menu, you will see your new shortcut "Anaconda 3.6.5" which launch the Anaconda Prompt with your choosen environment !
For installing python 3.6 on windows go to this [link](https://anaconda.org/ehmoussi/python)
54,801,513
I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Anaconda's [download](https://www.anaconda.com/distribution/#download-section) page, there are only two versions i.e for Python 3.7 and Python 2.7 but I need for Python 3.6. Any help would be great.
2019/02/21
[ "https://Stackoverflow.com/questions/54801513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033492/" ]
Following [this answer](https://stackoverflow.com/questions/41535881/how-do-i-upgrade-to-python-3-6-with-conda), this solution is working for me on windows 10, From the anaconda prompt : 1. Create a custom environnement and specify the repository channel to find the version (in my case 3.6.5) ``` conda create --name py365 python=3.6.5 --channel conda-forge ``` 2. Activate the new environment ``` conda activate py365 ``` But the activation won't be permanent, you will need to activate each time you start the anaconda prompt 3. Create a shortcut to Anaconda prompt with your choosen environment In order to activate permanently your custom environment, you can create a anaconda prompt shortcut which new target. Go to ``` C:\Users\Your_Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit) ``` And Copy and rename the file `Anaconda Prompt (Anaconda3)` to `Anaconda 3.6.5`. Then right-click on the new file and click on "Properties". Then change the target : ``` %windir%\System32\cmd.exe "/K" C:\Users\Your_Name\Anaconda3\Scripts\activate.bat C:\Users\Your_Name\Anaconda3 ``` to ``` %windir%\System32\cmd.exe "/K" C:\Users\Your_Name\Anaconda3\Scripts\activate.bat C:\Users\Your_Name\Anaconda3\envs\py365 ``` (be aware to change "Your\_Name" by your "real" name ) Finally, if you go to your Windows Start menu, you will see your new shortcut "Anaconda 3.6.5" which launch the Anaconda Prompt with your choosen environment !
You can download anaconda from the archives. The path I followed was: Anaconda Documentation>Anaconda Distribution>Installation-(in page)System Requirements>[archive](https://docs.anaconda.com/anaconda/install/) I was looking for installation instructions on my CentOS machine when I stumbled upon the question.
54,801,513
I was working on Tensorflow object detection project, for this I am using Anaconda 3 with python 3.7 but I am facing some issues while running object detection demo, I read couple of posts here on stackoverflow and found that it can be solved by using Anaconda with python 3.6 but this version is not available at Anaconda's [download](https://www.anaconda.com/distribution/#download-section) page, there are only two versions i.e for Python 3.7 and Python 2.7 but I need for Python 3.6. Any help would be great.
2019/02/21
[ "https://Stackoverflow.com/questions/54801513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5033492/" ]
You can download the 3.7 version and then [use](https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html) ``` conda create -n mygreatenvironment python=3.6 <add other packages here> ``` and then: ``` conda activate mygreatenvironment ``` This environment will use Python 3.6.
You can download anaconda from the archives. The path I followed was: Anaconda Documentation>Anaconda Distribution>Installation-(in page)System Requirements>[archive](https://docs.anaconda.com/anaconda/install/) I was looking for installation instructions on my CentOS machine when I stumbled upon the question.
50,013,072
I am trying to filter a python 3 string so that only utf8 characters of 3 bytes or less are kept (I am writing to a SQL db that is utf8\_general\_ci which can take only 3 bytes or less). Is there a straightforward way to do this in Python? Any help would be very appreciated.
2018/04/25
[ "https://Stackoverflow.com/questions/50013072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028588/" ]
You ask for an efficient solution. But you have hobbled performance from the outset by using a naive `vector<vector<int>>` and storing the data row-wise when you want to append column-wise. Rectangular matrices are better stored in a single vector with fancy indexing (e.g. `data.get(i, j)` instead of `data[i][j]`). If you store column-wise, appending a column is as simple as: ``` data.push_back(newCol); ```
You can just do like this: ``` void insert_col(vector<vector<int>>& data, vector<int>& newCol) { data.push_back(newCol); } ```
50,013,072
I am trying to filter a python 3 string so that only utf8 characters of 3 bytes or less are kept (I am writing to a SQL db that is utf8\_general\_ci which can take only 3 bytes or less). Is there a straightforward way to do this in Python? Any help would be very appreciated.
2018/04/25
[ "https://Stackoverflow.com/questions/50013072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028588/" ]
How about this ``` //For each vector<int> in the 2d vector, //push_back the corresponding element from the newCol vector for_each(data.begin(), data.end(), [&i, &newCol](vector<int>& v){v.push_back(newCol[i++]);}); ```
You can just do like this: ``` void insert_col(vector<vector<int>>& data, vector<int>& newCol) { data.push_back(newCol); } ```
50,013,072
I am trying to filter a python 3 string so that only utf8 characters of 3 bytes or less are kept (I am writing to a SQL db that is utf8\_general\_ci which can take only 3 bytes or less). Is there a straightforward way to do this in Python? Any help would be very appreciated.
2018/04/25
[ "https://Stackoverflow.com/questions/50013072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028588/" ]
You ask for an efficient solution. But you have hobbled performance from the outset by using a naive `vector<vector<int>>` and storing the data row-wise when you want to append column-wise. Rectangular matrices are better stored in a single vector with fancy indexing (e.g. `data.get(i, j)` instead of `data[i][j]`). If you store column-wise, appending a column is as simple as: ``` data.push_back(newCol); ```
How about this ``` //For each vector<int> in the 2d vector, //push_back the corresponding element from the newCol vector for_each(data.begin(), data.end(), [&i, &newCol](vector<int>& v){v.push_back(newCol[i++]);}); ```
51,153,543
I used the python example from <https://learn.microsoft.com/de-de/azure/iot-hub/quickstart-send-telemetry-python> to send telemetry data to the IoTHub. Now I try to forward only the messages from the device "test-device" into a blob storage via a custom endpoint and a route. With the query string "true" all messages from all devices are pushed to the storage. However, I don't get the query to select only the messages from the deviceId "test-device". I search in the documentation but didn't find any helpful example... Can anyone help me with the query? At least it would be also helpful to sample incoming messages inside the IoTHub to get an idea of the structure of IotHub messages (like it is done in the StreamAnalytics "sample data").
2018/07/03
[ "https://Stackoverflow.com/questions/51153543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10026391/" ]
`WeekDays` is just a type, types do no have any runtime presence so we can't access any information the type holds at runtime. Enums are represented as objects at runtime, this is why we can extract information from them. See more [here](https://stackoverflow.com/questions/51131898/what-is-the-difference-between-type-and-class-in-typescript/51132333#51132333) for a discussion on types vs values. Baring a custom compiler transformation (which means replacing the stock compiler with a custom version that emits extra information) the only thing we can do is construct a function to retrieve the values, which requires us to pass in an object literal that contains **exactly** the strings in the enum. While this requires us to restate the strings, the compiler will check that we don't add any extra ones and we don't have any missing, so it might be good enough: ``` export declare type WeekDays = 'su' | 'mo' | 'tu' | 'we' | 'th' | 'fr' | 'sa'; function getValues<T extends string>(values: { [P in T]: P }) : T[]{ return Object.values(values); } // Ok values are all stated, the values are correctly stated. getValues<WeekDays>({fr: 'fr',mo: 'mo',sa:'sa',su:'su',th:'th',tu:'tu',we:'we'}) // Error values don't match getValues<WeekDays>({fr: 'frrr',mo: 'mo',sa:'sa',su:'su',th:'th',tu:'tu',we:'we'}) // Error values missing getValues<WeekDays>({mo: 'mo',sa:'sa',su:'su',th:'th',tu:'tu',we:'we'}) // Error values extra values getValues<WeekDays>({funDay: 'funDay', fr: 'fr', mo: 'mo',sa:'sa',su:'su',th:'th',tu:'tu',we:'we'}) ```
All types in typescrpt are metadata only and are not available on run time. So the list of valid strings in your string literal type cannot be retrieved.
40,473,671
I have a NodeJS that host a WebSocket Server. The WebSocket redistributes message from Redis. The full line is, i have some python script that push some data in Redis and after that NodeJS is the WebSocket that reads the Redis newly input data to the connected clients. My problem is that the NodeJs is always taking up memory and after a while it just burst and stops. I don't know what is my problem, since my code is pretty simple. I don't need my WebSocket to receive message from the connected clients, since i only need to push them data, but alot of data. ``` var server = require('websocket').server, http = require('http'); var redis = require("redis"), client = redis.createClient(); var socket = new server({ httpServer: http.createServer().listen(443), keepalive: false }); client.subscribe("attack-map-production"); socket.on('request', function(request) { var connection = request.accept(null, request.origin); connection.on('message', function(message) { console.log(message); client.on("message", function(channel, message){ connection.send(message); }); }); connection.on('close', function(connection) { console.log('connection closed'); }); }); ``` I'm looking to make this work without eating all the memory on my server and possibly make this much more fast, but i think it's fast enough. Maybe NodeJS is not meant for this kind of work? Any help is appreciated. Thanks. **Update 2016-11-08** With the information provided below, i have "updated" my code. The problem is still there, i will continue to look around to find a answer... but i'm really not getting this. ``` var server = require('websocket').server, http = require('http'); var redis = require("redis"), client = redis.createClient(); var socket = new server({ httpServer: http.createServer().listen(443), keepalive: false }); client.subscribe("attack-map-production"); socket.on('request', function(request) { var connection = request.accept(null, request.origin); client.on("message", function(channel, message){ connection.send(message); }); connection.on('close', function(connection) { console.log('connection closed'); }); }); ``` **Update 2016-11-16** So here is my new code: ``` var io = require('socket.io').listen(443); var sub = require('redis').createClient(); io.sockets.on('connection', function (sockets) { sockets.emit('message',{Hello: 'World!'}); sub.subscribe('attack-map-production'); // Could be any patterni sockets.on('disconnect', function() { sub.unsubscribe('attack-map-production'); }); }); sub.on('message', function(channel, message) { io.sockets.json.send(message); }); ``` Even this code, makes nodejs go at 100% CPU and even more, and it starts to go really slow, until everything just stops. The complet flow of my data, is that a python script pushes data into Redis, and throught my subscribtion it pushes my data back to the browser by a webSocket and Socket.io. That simple, how can this be slow? I just don't get it.
2016/11/07
[ "https://Stackoverflow.com/questions/40473671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1861854/" ]
``` client = redis.createClient(); ``` take a look at this line , everytime you invoke the variable client , you create an instance of redis client inside node , and you never close it. so if you recieve 10000 socket 'request' , you will also have 10000 redis instances. You need to call the command client.quit() once the write or the read to redis is done ``` var server = require('websocket').server, http = require('http'); var redis = require("redis"), client = redis.createClient(); var socket = new server({ httpServer: http.createServer().listen(443), keepalive: false }); client.subscribe("attack-map-production"); socket.on('request', function(request) { var connection = request.accept(null, request.origin); client.on("message", function(channel, message){ connection.send(message); }); client.quit(); // MISSING LINE connection.on('close', function(connection) { console.log('connection closed'); }); }); ``` and i also noticed this piece of code ``` httpServer: http.createServer().listen(443) ``` the port 443 is for https ! so if you are using a secured connection you need to call the module https not http, like this ``` var socket = new server({ httpServer: https.createServer().listen(443), keepalive: false }); ``` hope it helps !
> > Maybe NodeJS is not meant for this kind of work? > > > If node is meant for something it's this. I/O stream and reading/writing is the main advantage of node asynchronism. On what kind of server are you running this ? In a too small EC2 instance you can hit some memory problem. Else it's a leak. That's kind of hard to trace. Code is small thought. I would remove any console.log just in case. ``` connection.on('message', function(message) { console.log(message); client.on("message", function(channel, message){ connection.send(message); }); }); ``` This part feel suspicious, two variables with the same name, an unused variable, it calls for trouble, and I don't really get why you have to listen for connection message in order to wait for redis message.
37,046,943
I use selenium webdriver, how can i check if the element should not be present in the page and I'm testing python. Can anyone suggest any solutions to this problem. Thanks a lot.
2016/05/05
[ "https://Stackoverflow.com/questions/37046943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5245640/" ]
yes try below its one liner and simple to use ``` if(driver.findElements(By.xpath("yourXpath/your locator stratgey")).size() >0){ // if size is greater then zero that means element // is present on the page }else if(!(driver.findElements(By.xpath("yourXpath/your locator stratgey")).size() >0)){ // if size is smaller then zero that means // element is not present on the page } ```
You can create a method IsElementPresent which will return whether element is present on page or not. You can call this method in your test case. ``` public boolean IsElementPresent(String locator, String locatorvalue) { try { if(locator.equalsIgnoreCase("id")) { driver.findElement(By.id(locatorvalue)); } return true; } catch (NoSuchElementException e) { return false; } } ```
37,046,943
I use selenium webdriver, how can i check if the element should not be present in the page and I'm testing python. Can anyone suggest any solutions to this problem. Thanks a lot.
2016/05/05
[ "https://Stackoverflow.com/questions/37046943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5245640/" ]
You could do this a number of ways. Lazy would be something like this. ``` # Import these at top of page import unittest try: assert '<div id="Waldo" class="waldo">Example</div>' not in driver.page_source except AssertionError, e: self.verificationErrors.append("Waldo incorrectly appeared in page source.") ``` Or you could import Expected conditions and asserting it returns presence\_of\_element\_located is not **T**rue. Notice true is caps sensitive and presence\_of\_element\_located either returns True or Not Null so assertFalse wouldn't be an easier way to phrase this. ``` # Import these at top of page import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC try: assert EC.presence_of_element_located( (By.XPATH, '//*[@id="Waldo"]') ) is not True except AssertionError, e: self.verificationErrors.append('presence_of_element_located returned True for Waldo') ``` Or like Raj said, you could use find\_element**s** and assert there are 0. ``` import unittest waldos = driver.find_elements_by_class_name('waldo') try: self.assertEqual(len(waldos), 0) except AssertionError, e: self.verificationErrors.append('Found ' + str(len(waldos)) + ' Waldi.') ``` You could also assert that a NoSuchElementException will occur. ``` # Import these at top of page import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException try: with self.assertRaises(NoSuchElementException) as cm: driver.find_element(By.CSS_SELECTOR, 'div.waldo') except AssertionError as e: raise e ```
yes try below its one liner and simple to use ``` if(driver.findElements(By.xpath("yourXpath/your locator stratgey")).size() >0){ // if size is greater then zero that means element // is present on the page }else if(!(driver.findElements(By.xpath("yourXpath/your locator stratgey")).size() >0)){ // if size is smaller then zero that means // element is not present on the page } ```
37,046,943
I use selenium webdriver, how can i check if the element should not be present in the page and I'm testing python. Can anyone suggest any solutions to this problem. Thanks a lot.
2016/05/05
[ "https://Stackoverflow.com/questions/37046943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5245640/" ]
yes try below its one liner and simple to use ``` if(driver.findElements(By.xpath("yourXpath/your locator stratgey")).size() >0){ // if size is greater then zero that means element // is present on the page }else if(!(driver.findElements(By.xpath("yourXpath/your locator stratgey")).size() >0)){ // if size is smaller then zero that means // element is not present on the page } ```
``` try: driver.find_elements_by_xpath('//*[@class="should_not_exist"]') should_exist = False except: should_exist = True if not should_exist: // Do something ```
37,046,943
I use selenium webdriver, how can i check if the element should not be present in the page and I'm testing python. Can anyone suggest any solutions to this problem. Thanks a lot.
2016/05/05
[ "https://Stackoverflow.com/questions/37046943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5245640/" ]
You could do this a number of ways. Lazy would be something like this. ``` # Import these at top of page import unittest try: assert '<div id="Waldo" class="waldo">Example</div>' not in driver.page_source except AssertionError, e: self.verificationErrors.append("Waldo incorrectly appeared in page source.") ``` Or you could import Expected conditions and asserting it returns presence\_of\_element\_located is not **T**rue. Notice true is caps sensitive and presence\_of\_element\_located either returns True or Not Null so assertFalse wouldn't be an easier way to phrase this. ``` # Import these at top of page import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC try: assert EC.presence_of_element_located( (By.XPATH, '//*[@id="Waldo"]') ) is not True except AssertionError, e: self.verificationErrors.append('presence_of_element_located returned True for Waldo') ``` Or like Raj said, you could use find\_element**s** and assert there are 0. ``` import unittest waldos = driver.find_elements_by_class_name('waldo') try: self.assertEqual(len(waldos), 0) except AssertionError, e: self.verificationErrors.append('Found ' + str(len(waldos)) + ' Waldi.') ``` You could also assert that a NoSuchElementException will occur. ``` # Import these at top of page import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException try: with self.assertRaises(NoSuchElementException) as cm: driver.find_element(By.CSS_SELECTOR, 'div.waldo') except AssertionError as e: raise e ```
You can create a method IsElementPresent which will return whether element is present on page or not. You can call this method in your test case. ``` public boolean IsElementPresent(String locator, String locatorvalue) { try { if(locator.equalsIgnoreCase("id")) { driver.findElement(By.id(locatorvalue)); } return true; } catch (NoSuchElementException e) { return false; } } ```
37,046,943
I use selenium webdriver, how can i check if the element should not be present in the page and I'm testing python. Can anyone suggest any solutions to this problem. Thanks a lot.
2016/05/05
[ "https://Stackoverflow.com/questions/37046943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5245640/" ]
``` try: driver.find_elements_by_xpath('//*[@class="should_not_exist"]') should_exist = False except: should_exist = True if not should_exist: // Do something ```
You can create a method IsElementPresent which will return whether element is present on page or not. You can call this method in your test case. ``` public boolean IsElementPresent(String locator, String locatorvalue) { try { if(locator.equalsIgnoreCase("id")) { driver.findElement(By.id(locatorvalue)); } return true; } catch (NoSuchElementException e) { return false; } } ```
37,046,943
I use selenium webdriver, how can i check if the element should not be present in the page and I'm testing python. Can anyone suggest any solutions to this problem. Thanks a lot.
2016/05/05
[ "https://Stackoverflow.com/questions/37046943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5245640/" ]
You could do this a number of ways. Lazy would be something like this. ``` # Import these at top of page import unittest try: assert '<div id="Waldo" class="waldo">Example</div>' not in driver.page_source except AssertionError, e: self.verificationErrors.append("Waldo incorrectly appeared in page source.") ``` Or you could import Expected conditions and asserting it returns presence\_of\_element\_located is not **T**rue. Notice true is caps sensitive and presence\_of\_element\_located either returns True or Not Null so assertFalse wouldn't be an easier way to phrase this. ``` # Import these at top of page import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC try: assert EC.presence_of_element_located( (By.XPATH, '//*[@id="Waldo"]') ) is not True except AssertionError, e: self.verificationErrors.append('presence_of_element_located returned True for Waldo') ``` Or like Raj said, you could use find\_element**s** and assert there are 0. ``` import unittest waldos = driver.find_elements_by_class_name('waldo') try: self.assertEqual(len(waldos), 0) except AssertionError, e: self.verificationErrors.append('Found ' + str(len(waldos)) + ' Waldi.') ``` You could also assert that a NoSuchElementException will occur. ``` # Import these at top of page import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException try: with self.assertRaises(NoSuchElementException) as cm: driver.find_element(By.CSS_SELECTOR, 'div.waldo') except AssertionError as e: raise e ```
``` try: driver.find_elements_by_xpath('//*[@class="should_not_exist"]') should_exist = False except: should_exist = True if not should_exist: // Do something ```
41,559,171
I wrote a little Python program and most of the people who are going to run it will be Windows users. I tried to use pyinstaller and py2exe on 2 different devices, one with Windows and the other with arch-linux. I reinstalled it more than once, using the pip3 install pyinstaller --no-cache I always get the same error: ``` sudo pyinstaller --windowed --onefile test.py 49 INFO: PyInstaller: 3.2 49 INFO: Python: 3.6.0 50 INFO: Platform: Linux-4.8.13-1-ARCH-x86_64-with-arch 51 INFO: wrote /home/XXXXX/test.spec 52 INFO: UPX is not available. 53 INFO: Extending PYTHONPATH with paths ['/home/XXXXX', '/home/XXXXX'] 54 INFO: checking Analysis 54 INFO: Building Analysis because out00-Analysis.toc is non existent 54 INFO: Initializing module dependency graph... 57 INFO: Initializing module graph hooks... 58 INFO: Analyzing base_library.zip ... Traceback (most recent call last): File "/usr/bin/pyinstaller", line 11, in <module> load_entry_point('PyInstaller==3.2', 'console_scripts', 'pyinstaller')() File "/usr/lib/python3.6/site-packages/PyInstaller/__main__.py", line 90, in run run_build(pyi_config, spec_file, **vars(args)) File "/usr/lib/python3.6/site-packages/PyInstaller/__main__.py", line 46, in run_build PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs) File "/usr/lib/python3.6/site-packages/PyInstaller/building/build_main.py", line 788, in main build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build')) File "/usr/lib/python3.6/site-packages/PyInstaller/building/build_main.py", line 734, in build exec(text, spec_namespace) File "<string>", line 16, in <module> File "/usr/lib/python3.6/site-packages/PyInstaller/building/build_main.py", line 212, in __init__ self.__postinit__() File "/usr/lib/python3.6/site-packages/PyInstaller/building/datastruct.py", line 178, in __postinit__ self.assemble() File "/usr/lib/python3.6/site-packages/PyInstaller/building/build_main.py", line 317, in assemble excludes=self.excludes, user_hook_dirs=self.hookspath) File "/usr/lib/python3.6/site-packages/PyInstaller/depend/analysis.py", line 560, in initialize_modgraph graph.import_hook(m) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 906, in import_hook q, tail = self._find_head_package(parent, name, level) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 990, in _find_head_package q = self._safe_import_module(head, qname, parent) File "/usr/lib/python3.6/site-packages/PyInstaller/depend/analysis.py", line 209, in _safe_import_module module_basename, module_name, parent_package) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 1211, in _safe_import_module module_name, file_handle, pathname, metadata) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 1295, in _load_module self._scan_code(m, co, co_ast) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 1460, in _scan_code self._scan_bytecode_stores(co, m) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 1505, in _scan_bytecode_stores name = co.co_names[oparg] IndexError: tuple index out of range ``` So, in that case, I just used a testscript containing: ``` #!/usr/bin/env python3.6 print("hello world") ``` to make sure there is no problem with the imports and so on.
2017/01/10
[ "https://Stackoverflow.com/questions/41559171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7396847/" ]
I run into the same problem with python 3.6 and pyinstaller, and have used for the first time `cx_Freeze`. It worked like a charm! Setup.py contents: ``` import cx_Freeze exe = [cx_Freeze.Executable("downloads_folder.py")] cx_Freeze.setup( name = "downloads", version = "1.0", options = {"build_exe": {"packages": ["errno", "os", "re", "stat", "subprocess","collections","pprint","shutil", "humanize","pycallgraph"], "include_files": []}}, executables = exe) ``` Start cmd in the directory where `setup.py` is, and run the following command: **python setup.py build**. The executable will be found in the build directory created by cx\_Freeze run.
Same here, i m also new and got the same problem as you. I was stuck about 6 hours and tried everything. Finally i also installed cx\_freeze and it worked > > pip install cx\_freeze > > >
41,559,171
I wrote a little Python program and most of the people who are going to run it will be Windows users. I tried to use pyinstaller and py2exe on 2 different devices, one with Windows and the other with arch-linux. I reinstalled it more than once, using the pip3 install pyinstaller --no-cache I always get the same error: ``` sudo pyinstaller --windowed --onefile test.py 49 INFO: PyInstaller: 3.2 49 INFO: Python: 3.6.0 50 INFO: Platform: Linux-4.8.13-1-ARCH-x86_64-with-arch 51 INFO: wrote /home/XXXXX/test.spec 52 INFO: UPX is not available. 53 INFO: Extending PYTHONPATH with paths ['/home/XXXXX', '/home/XXXXX'] 54 INFO: checking Analysis 54 INFO: Building Analysis because out00-Analysis.toc is non existent 54 INFO: Initializing module dependency graph... 57 INFO: Initializing module graph hooks... 58 INFO: Analyzing base_library.zip ... Traceback (most recent call last): File "/usr/bin/pyinstaller", line 11, in <module> load_entry_point('PyInstaller==3.2', 'console_scripts', 'pyinstaller')() File "/usr/lib/python3.6/site-packages/PyInstaller/__main__.py", line 90, in run run_build(pyi_config, spec_file, **vars(args)) File "/usr/lib/python3.6/site-packages/PyInstaller/__main__.py", line 46, in run_build PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs) File "/usr/lib/python3.6/site-packages/PyInstaller/building/build_main.py", line 788, in main build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build')) File "/usr/lib/python3.6/site-packages/PyInstaller/building/build_main.py", line 734, in build exec(text, spec_namespace) File "<string>", line 16, in <module> File "/usr/lib/python3.6/site-packages/PyInstaller/building/build_main.py", line 212, in __init__ self.__postinit__() File "/usr/lib/python3.6/site-packages/PyInstaller/building/datastruct.py", line 178, in __postinit__ self.assemble() File "/usr/lib/python3.6/site-packages/PyInstaller/building/build_main.py", line 317, in assemble excludes=self.excludes, user_hook_dirs=self.hookspath) File "/usr/lib/python3.6/site-packages/PyInstaller/depend/analysis.py", line 560, in initialize_modgraph graph.import_hook(m) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 906, in import_hook q, tail = self._find_head_package(parent, name, level) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 990, in _find_head_package q = self._safe_import_module(head, qname, parent) File "/usr/lib/python3.6/site-packages/PyInstaller/depend/analysis.py", line 209, in _safe_import_module module_basename, module_name, parent_package) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 1211, in _safe_import_module module_name, file_handle, pathname, metadata) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 1295, in _load_module self._scan_code(m, co, co_ast) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 1460, in _scan_code self._scan_bytecode_stores(co, m) File "/usr/lib/python3.6/site-packages/PyInstaller/lib/modulegraph/modulegraph.py", line 1505, in _scan_bytecode_stores name = co.co_names[oparg] IndexError: tuple index out of range ``` So, in that case, I just used a testscript containing: ``` #!/usr/bin/env python3.6 print("hello world") ``` to make sure there is no problem with the imports and so on.
2017/01/10
[ "https://Stackoverflow.com/questions/41559171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7396847/" ]
Pyinstaller doesn't support Python 3,6 yet. You could revert to Python 3.5, or try the cx\_Freeze solution mentioned ... not sure what it does though, I think it replaces it.
Same here, i m also new and got the same problem as you. I was stuck about 6 hours and tried everything. Finally i also installed cx\_freeze and it worked > > pip install cx\_freeze > > >
29,467,437
I hope it is not a duplicate question as a solution has been proposed [here](https://stackoverflow.com/questions/10718073/how-to-create-child-window-and-communicate-with-parent-in-tkinter/10718548#comment47050170_10718548), which I have a hard time making it work. (Alternatively I could post this in the same discussion) **Goal:** In the main window the user enter some data, if clicked, a new child window appears with parent data, eventually operates on them, then sends back the result to parent widgets. ![enter image description here](https://i.stack.imgur.com/KVCMG.png) **Code used:** ``` from Tkinter import * class trackApp(Frame): def __init__(self, master): Frame.__init__(self, master) self.mainVar1 = IntVar() self.mainVar2 = IntVar() self.mainVar1.set(100) self.mainVar2.set(100) self.master = master self.master.geometry('400x200+100+200') self.master.title('MAIN WINDOW') self.label1=Label(self.master,text='Variable1 : ').grid(row=1,column=1) self.mainEntry1=Entry(self.master,textvariable=self.mainVar1).grid(row=1,column=2) self.label2=Label(self.master,text='Variable2 : ').grid(row=2,column=1) self.mainEntry2=Entry(self.master,textvariable=self.mainVar2).grid(row=2,column=2) self.button1=Button(self.master,text='Child',command=self.dialogWindow).grid(row=7,column=2) def new_data(self, data): self.mainEntry1.delete(0,END) self.mainEntry1.insert(0,self.data['var1']) self.mainEntry2.delete(0,END) self.mainEntry2.insert(0,self.data['var2']) def dialogWindow(self): # Build a list from control variables used in the main window text entry boxes mainList = [self.mainVar1.get(),self.mainVar2.get()] top=Toplevel(self.master) childDialog=childWindow(top,mainList, self.master) class childWindow(Frame): # Pass data (list) to the child def __init__(self, master, list, app): self.list = list self.app = app self.master = master self.master.geometry('300x100+150+250') self.master.title('CHILD WINDOW') # Define control variabels to be used with child window text entry widgets self.childvar1 = IntVar() self.childvar2 = IntVar() # Fill child window text entry widgets with inf. from parent window self.childvar1.set(list[0]) self.childvar2.set(list[1]) # Text entry widgets self.label1=Label(self.master,text='Enter New value 1').grid(row=0,column=1) self.childEntry1=Entry(self.master,textvariable=self.childvar1).grid(row=0,column=2) self.label2=Label(self.master,text='Enter New value 2').grid(row=1,column=1) self.childEntry2=Entry(self.master,textvariable=self.childvar2).grid(row=1,column=2) self.button1=Button(self.master,text='OK',command=self.childDestroy).grid(row=3,column=1) def childDestroy(self): self.data = {} self.data['var1'] = self.childvar1.get() self.data['var2'] = self.childvar2.get() trackApp.app.new_data(self, self.data) # <<<<<<<<< How to call the parent new_data method self.master.destroy() def main(): root = Tk() app = trackApp(root) root.mainloop() if __name__ == "__main__": main() ``` **Question:** How to refer to the parent method (**new\_data**) from the child? **Error:** ``` /usr/bin/python2.7 /<path>/child-dialog.py Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__ return self.func(*args) File "/<path>/child-dialog.py", line 77, in childDestroy trackApp.app.new_data(self, self.data) # <<<<<<<<< How to call the parent new_data method AttributeError: class trackApp has no attribute 'app' ```
2015/04/06
[ "https://Stackoverflow.com/questions/29467437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1005123/" ]
The error message is telling you exactly what the problem is: it says that `trackApp` has no attribute `'app'`, and looking at the definition of that class I see no attribute `'app'`. For your child window to know it's parent, you need to give it a reference to the parent. So, when creating the window you pass the reference in, and within the child window you use the reference. It looks like you're attempting to do that, but you're passing in the wrong value, and then you're not using the value. You need to modify your code to look like this: ``` class trackApp(Frame): ... def dialogWindow(self): ... childDialog=childWindow(top,mainList, self) class childWindow(Frame): def childDestroy(self): ... self.app.new_data(self, self.data) ... ```
Thanks Bryan for the answer. Here are the changes I have made accordingly: Pass the parent (self) to the child window ``` def dialogWindow(self): childDialog=childWindow(top,mainList, self) ``` Call the parent method using parent instance (self) ``` def childDestroy(self) self.app.new_data(self.data) ``` and the following to update main window widgets: ``` def new_data(self, data): self.mainVar1.set(data['var1']) self.mainVar2.set(data['var2']) ``` Appreciate your help.
55,768,477
I'm experiencing issues using the official Postgres docker image, something that never happened on this machine. I'm using that through docker-compose but when running `docker-compose up`, the db container does not start, here's the error: ``` db_1 | 2019-04-19 22:20:27.180 UTC [1] FATAL: lock file "postmaster.pid" is empty db_1 | 2019-04-19 22:20:27.180 UTC [1] HINT: Either another server is starting, or the lock file is the remnant of a previous server startup crash. ``` I tried several times to remove the image so it then will be re-pulled, but hasn't solved the problem. I'm using Docker for Mac 2.0.0.3 (31259) here's the `docker-compose.yml`: ``` version: '2' services: web: build: . entrypoint: sh -c "python3 /var/www/my_project/manage.py migrate --noinput && python3 /var/www/my_project/manage.py runserver 0.0.0.0:8000" restart: on-failure ports: - "9001:8000" volumes: - .:/var/www/my_project depends_on: - db env_file: - ./.env environment: - DB_SERVER=db - DB_NAME=postgres - DB_USER=postgres db: ports: - "9432:5432" image: postgres volumes: - database:/var/lib/postgresql volumes: database: ``` Any help on this?
2019/04/19
[ "https://Stackoverflow.com/questions/55768477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/998967/" ]
The arrow function inside the `this.state.counter.filter()` returns the boolean value of the expression `c.id !== counterId`. When you don't put the brackets "{}" after declaring an arrow function, it means what comes after the arrow "=>" is considered the return value of it.
This function: ``` handleDelete = counterId => { const tempCounter = this.state.counters.filter(c => c.id !== counterId); // implicit return this.setState({ counters: tempCounter }); }; ``` OR ``` handleDelete = counterId => { const tempCounter = this.state.counters.filter(c => { return c.id !== counterId; // explicit return }); this.setState({ counters: tempCounter }); }; ``` More contrived example: ```js const people = [ { name: 'Bob', age: 20 }, { name: 'Jane', age: 30 }, { name: 'Mike', age: 40 }, { name: 'Smith', age: 50 }, ]; const under35implicit = people.filter(person => person.age < 35) // same as const under35explicit = people.filter(person => { return person.age < 35 }) console.log(under35implicit) console.log(under35explicit) ``` Does that make sense?
55,768,477
I'm experiencing issues using the official Postgres docker image, something that never happened on this machine. I'm using that through docker-compose but when running `docker-compose up`, the db container does not start, here's the error: ``` db_1 | 2019-04-19 22:20:27.180 UTC [1] FATAL: lock file "postmaster.pid" is empty db_1 | 2019-04-19 22:20:27.180 UTC [1] HINT: Either another server is starting, or the lock file is the remnant of a previous server startup crash. ``` I tried several times to remove the image so it then will be re-pulled, but hasn't solved the problem. I'm using Docker for Mac 2.0.0.3 (31259) here's the `docker-compose.yml`: ``` version: '2' services: web: build: . entrypoint: sh -c "python3 /var/www/my_project/manage.py migrate --noinput && python3 /var/www/my_project/manage.py runserver 0.0.0.0:8000" restart: on-failure ports: - "9001:8000" volumes: - .:/var/www/my_project depends_on: - db env_file: - ./.env environment: - DB_SERVER=db - DB_NAME=postgres - DB_USER=postgres db: ports: - "9432:5432" image: postgres volumes: - database:/var/lib/postgresql volumes: database: ``` Any help on this?
2019/04/19
[ "https://Stackoverflow.com/questions/55768477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/998967/" ]
The arrow function inside the `this.state.counter.filter()` returns the boolean value of the expression `c.id !== counterId`. When you don't put the brackets "{}" after declaring an arrow function, it means what comes after the arrow "=>" is considered the return value of it.
In an arrow function, if there is an expression after the arrow, it will be implicitly returned. If there are curly braces, then an explicit return statement is required to return a value. You could rewrite the first function like: ``` const tempCounter = this.state.counters.filter(c => { return c.id !== counterId }); ``` But it is more concise the first way. The second function could also be reversed to use an explicit return, using spreading: ``` const resetCounters = this.state.counters.map(c => ({ ...c, value: 0 })); ``` We need to wrap the object in parentheses, otherwise it will become a function body contained in curly braces.
55,768,477
I'm experiencing issues using the official Postgres docker image, something that never happened on this machine. I'm using that through docker-compose but when running `docker-compose up`, the db container does not start, here's the error: ``` db_1 | 2019-04-19 22:20:27.180 UTC [1] FATAL: lock file "postmaster.pid" is empty db_1 | 2019-04-19 22:20:27.180 UTC [1] HINT: Either another server is starting, or the lock file is the remnant of a previous server startup crash. ``` I tried several times to remove the image so it then will be re-pulled, but hasn't solved the problem. I'm using Docker for Mac 2.0.0.3 (31259) here's the `docker-compose.yml`: ``` version: '2' services: web: build: . entrypoint: sh -c "python3 /var/www/my_project/manage.py migrate --noinput && python3 /var/www/my_project/manage.py runserver 0.0.0.0:8000" restart: on-failure ports: - "9001:8000" volumes: - .:/var/www/my_project depends_on: - db env_file: - ./.env environment: - DB_SERVER=db - DB_NAME=postgres - DB_USER=postgres db: ports: - "9432:5432" image: postgres volumes: - database:/var/lib/postgresql volumes: database: ``` Any help on this?
2019/04/19
[ "https://Stackoverflow.com/questions/55768477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/998967/" ]
The arrow function inside the `this.state.counter.filter()` returns the boolean value of the expression `c.id !== counterId`. When you don't put the brackets "{}" after declaring an arrow function, it means what comes after the arrow "=>" is considered the return value of it.
Look closely! The returned value `c` is not the return value of your function `reset`, but rather the return value of your function `c => { c.value = 0; return c; }`, which you used within `this.state.counters.map` as parameter. This being clarified both functions `reset` and `handleDelete` don't return any values. They don't even have to, because they are most likely used as event handlers (button clicked, etc.). Therefore they trigger a state change by themselves with `this.setState`.
66,301,397
i am programming a chat room project by python.Below is my server.py and client.py .When client is trying to connect to server ,it returns"in line8, client.connect((ip,port)) ConnectionRefusedError: [Errno 111] Connection refused".I have no idea why client canʼt connect to server while telnet can do so without a error.If you have any idea,please let me know,thank you. server.py ``` import socket #ip =socket.gethostbyname(socket.gethostname()) ip="127.0.0.1" port=8000 server=socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((ip,port)) print("server ip address:"+ip) server.listen(1) conn,addr=server.accept() user=addr[0] print("[system]",user,"is online") while True: message=str(conn.recv(1024), encoding='utf-8') if(not "quit()" in message): print(user+' : '+message) else: print("[system]"+user+" quit") conn.close() break ``` client.py ``` import socket ip="127.0.0.1" port=8000 client=socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((ip,port)) while(1): message=input("input:") client.sendall(message.encode()) if(message=="quit()"): break client.close() ```
2021/02/21
[ "https://Stackoverflow.com/questions/66301397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14932648/" ]
**Approach 1 :** [Coroutines and Tasks](https://docs.python.org/3/library/asyncio-task.html) > > Coroutines declared with the async/await syntax is the preferred way > of writing asyncio applications. > > > A running example: ``` import asyncio async def f1(): print('Hello') await asyncio.sleep(1) async def f2(): print('World') await asyncio.sleep(1) asyncio.run(f1()) asyncio.run(f2()) ``` **Approach 2 :** [threading](https://docs.python.org/3/library/threading.html#module-threading) ``` from time import sleep def f1(): print('Hello ') sleep(1) def f2(): print('World') sleep(1) Thread(target=f1).start() Thread(target=f2).start() ``` Unfortunately, due to the [Global interpreter lock](https://en.wikipedia.org/wiki/Global_interpreter_lock) the functions will not be truly executed in parallel: > > A global interpreter lock (GIL) is a mechanism used in > computer-language interpreters to synchronize the execution of threads > so that only one native thread can execute at a time. An > interpreter that uses GIL always allows exactly one thread to execute > at a time, even if run on a multi-core processor. > > > **Approach 3:** [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) > > multiprocessing is a package that supports spawning processes using an > API similar to the threading module. The multiprocessing package > offers both local and remote concurrency, effectively side-stepping > the Global Interpreter Lock by using subprocesses instead of threads. > Due to this, the multiprocessing module allows the programmer to fully > leverage multiple processors on a given machine. > > > ``` from multiprocessing import Process from time import sleep def f1(): print('Hello ') sleep(1) def f2(): print('World') sleep(1) p1 = Process(target=f1) p1.start() p2 = Process(target=f2) p2.start() p1.join() p2.join() ```
You can use multiprocessing or threading, there are loads of videos about it on youtube if you want to look it up and try it out
63,167,228
I come from a C-like language background, so the code below looks pretty confusing to me: ``` #source: https://www.youtube.com/watch?v=4n7NPk5lwbI (timestamp 3:39) def rotation(t): """ Return list of rotations of input string t""" tt = t * 2 #why??, and is this concatenation? return [ tt[i:i+len(t)] for i in xrange(0, len(t)) ] #what is this for loop return/splice? ``` This should produce for a given input, say `t = "abc$"`: ``` [[abc$], [bc$a], [c$ab], [$abc]] ``` Or some permutation of the above output. Could someone explain what this code is doing? Including an example of input/output. I got a vague idea when typing this out, but it would help me to hear from someone that knows python.
2020/07/30
[ "https://Stackoverflow.com/questions/63167228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11040661/" ]
This isn't a normal `for` lop, rather it is a [list comprehension](https://www.youtube.com/watch?v=pShL9DCSIUw). In short, a list comprehension iterates over an iterable, and builds a new list from operations over each element. Python supports operator overloading, so the multiplication line is simply the implementation of multiplication on Python sequences, which is generally to repeat it: ``` >>> [1, 2] * 2 [1, 2, 1, 2] >>> "12" * 2 '1212' ``` Essentially, this code duplicates the sequence, then creates a sliding window over the new double-length sequence. Note that `collections.deque` has a method for rotation, so a good solution for this task is simply: ``` def rotation(t): current = collections.deque(t) yield list(current) for _ in range(len(current)): current.rotate(1) yield list(current) ``` (You could of course use `"".join()` for string results.)
``` def rotation(t): tt = t * 2 # 2 copies of the string t, yes this is concatenation # The list comprehension you questioned is basically equivalent to this result = [] for i in xrange(0, len(t)): result.append(tt[i:i+len(t)]) # the substring from i (inclusive) to i+len(t) (exclusive) return result ```
63,167,228
I come from a C-like language background, so the code below looks pretty confusing to me: ``` #source: https://www.youtube.com/watch?v=4n7NPk5lwbI (timestamp 3:39) def rotation(t): """ Return list of rotations of input string t""" tt = t * 2 #why??, and is this concatenation? return [ tt[i:i+len(t)] for i in xrange(0, len(t)) ] #what is this for loop return/splice? ``` This should produce for a given input, say `t = "abc$"`: ``` [[abc$], [bc$a], [c$ab], [$abc]] ``` Or some permutation of the above output. Could someone explain what this code is doing? Including an example of input/output. I got a vague idea when typing this out, but it would help me to hear from someone that knows python.
2020/07/30
[ "https://Stackoverflow.com/questions/63167228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11040661/" ]
``` def rotation(t): """ Return list of rotations of input string t""" tt = t * 2 #why??, and is this concatenation? return [ tt[i:i+len(t)] for i in xrange(0, len(t))] ``` `tt = t * 2` - why is this concatenation needed? So that you can easily choose substring using from index and to index. `abc$` would become `abc$abc$` `[ tt[i:i+len(t)] for i in xrange(0, len(t))]` - This is a list comprehension. It's like a one liner for loop. You are looping and also building a list of different rotations of the string i.e you are using sliding window to get different rotations And the final output is `['abc$', 'bc$a', 'c$ab', '$abc']`. It's not a nested list
``` def rotation(t): tt = t * 2 # 2 copies of the string t, yes this is concatenation # The list comprehension you questioned is basically equivalent to this result = [] for i in xrange(0, len(t)): result.append(tt[i:i+len(t)]) # the substring from i (inclusive) to i+len(t) (exclusive) return result ```
34,877,760
I'm getting into Python, and though of writing my own script which allows me to check arguments provided when a program is run. An example below of what I'm trying to achieve: `python file.py -v -h anotherfile.py` or `./file.py -v -h anotherfile.py` In these two cases, the `-v` and `-h` arguments, print out the module version, and a basic help file. I already have the code to differentiate between arguments and files, except I want to create a generalised module on the matter. The following code written in Java- ``` // Somewhere. public static HashMap<String, Runnable> args = new HashMap<String, Runnable>(); public void addArgument(String argument, Runnable command) { if (argument.length() > 0) { if (args.get(argument) == null) { args.put(argument, command); } else { System.err.println("Cannot add argument: " + argument + " to HashMap as the mapping already exists."); // Recover. } } } // Somewhere else. foo.addArgument("-v", () -> {System.out.println("version 1.0");}); foo.args.get("-v").run(); ``` -will run the Lambda Expressions *(atleast that's what I read they were when researching the topic)* successfully. I have no idea how Lambda Expressions work however, and have only basic knowledge of using them. **The point of this question, is how can I implement something like the Java example, in Python, storing any type of code inside of an array?** The thing is with the Java example though, if I have `int i = 0;` defined in the class which executes `addArgument` and uses `i` somehow or rather, the class containing `addArgument` knows to use `i` from the one that invoked it. I'm worried that this may not be the same case for Python... I want to be able to store them in dictionaries, or some other sort of key-based array, so I can store them in the following manner: ``` # Very rough example on the latter argument, showing what I'm after. addoption("-v", print("version 1.0")) ``` **EDIT: Example of what I want: (not working as is) (please ignore the ;'s)** ``` args = {}; def add(argument, command): args[argument] = lambda: command; # Same problem when removing 'lambda:' def run(): for arg in args: arg(); # Causing problems. def prnt(): print("test"); add("-v", prnt); run(); ```
2016/01/19
[ "https://Stackoverflow.com/questions/34877760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In Python, you can simply use the reference to a function as a value in a data structure. E.g., consider the following code: ``` def spam(): print('Ham!') eggs = [spam, spam, spam] for x in eggs: x() ``` This would call three instances of the function `spam`. The [lambda expressions](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions) you are referring to are simply another way to define functions, without explicitly having to bind them to a name. Consider the following: ``` eggs = [lambda : print('ham'), lambda : print('spam')] for x in eggs: x() ``` This gets much more powerful when you're using arguments, though: ``` fn = [lambda x: return x + 3, lambda x: return x * 2] for f in fn: print(f(4)) ``` Once you have a reference to a function, you can then pass *that* to another function. ``` def foo(x): return x + 2 bar = lambda x: return x * 2 def h(g, f, x): return g(f(x)) print(h(foo, bar, 37)) ``` In your scenario, however, you could simply pass `lambda : print("version 1.0")`.
Python has a function called [`eval()`](https://stackoverflow.com/questions/9383740/what-does-pythons-eval-do) that takes strings and tries to evaluate them as code. ``` >>> eval("2+3") 5 ``` Then you can store your code as multi-line strings using 3 quotation marks ``` x = """the quick brown fox jumps over the lazy dogs""" ``` If you want to store the functions themselves, no reason why they can't also be placed in a dictionary. Even without lambdas. ``` def f(): return 1 def g(x): return x + 1 def h(x): return 2*x F = [f,g,h] G = {"a": f, "b": g, "c": h} (F[0](), G["a"]()) ``` The value of the tuple is `(1,1)`. Otherwise I don't know what you are asking for.
34,877,760
I'm getting into Python, and though of writing my own script which allows me to check arguments provided when a program is run. An example below of what I'm trying to achieve: `python file.py -v -h anotherfile.py` or `./file.py -v -h anotherfile.py` In these two cases, the `-v` and `-h` arguments, print out the module version, and a basic help file. I already have the code to differentiate between arguments and files, except I want to create a generalised module on the matter. The following code written in Java- ``` // Somewhere. public static HashMap<String, Runnable> args = new HashMap<String, Runnable>(); public void addArgument(String argument, Runnable command) { if (argument.length() > 0) { if (args.get(argument) == null) { args.put(argument, command); } else { System.err.println("Cannot add argument: " + argument + " to HashMap as the mapping already exists."); // Recover. } } } // Somewhere else. foo.addArgument("-v", () -> {System.out.println("version 1.0");}); foo.args.get("-v").run(); ``` -will run the Lambda Expressions *(atleast that's what I read they were when researching the topic)* successfully. I have no idea how Lambda Expressions work however, and have only basic knowledge of using them. **The point of this question, is how can I implement something like the Java example, in Python, storing any type of code inside of an array?** The thing is with the Java example though, if I have `int i = 0;` defined in the class which executes `addArgument` and uses `i` somehow or rather, the class containing `addArgument` knows to use `i` from the one that invoked it. I'm worried that this may not be the same case for Python... I want to be able to store them in dictionaries, or some other sort of key-based array, so I can store them in the following manner: ``` # Very rough example on the latter argument, showing what I'm after. addoption("-v", print("version 1.0")) ``` **EDIT: Example of what I want: (not working as is) (please ignore the ;'s)** ``` args = {}; def add(argument, command): args[argument] = lambda: command; # Same problem when removing 'lambda:' def run(): for arg in args: arg(); # Causing problems. def prnt(): print("test"); add("-v", prnt); run(); ```
2016/01/19
[ "https://Stackoverflow.com/questions/34877760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
EDIT: to correct your most recent code, iterating over a dictionary yields its keys not its values, so you need: ``` args = {}; def add(argument, command): args[argument] = command; def run(): for arg in args: args[arg]() # <<<<<<<<<< def prnt(): print("test"); add("-v", prnt); run(); ``` For the example you give, a dictionary of functions, although possible, isn't really the natural way to go about things in Python. The standard library has a module, [`argparse`](https://docs.python.org/3/library/argparse.html) specifically for dealing with all things commmand-line argument related, and rather than using keys to a dictionary you can parse the command line arguments and refer to their stored constants. ``` import argparse def output_version(): print('Version 1.0!') parser = argparse.ArgumentParser(description="A program to do something.") parser.add_argument('-v', help='Output version number.', action='store_true') args = parser.parse_args() if args.v: output_version() ``` (In fact outputting a version string is also handled natively by `argparse`: see [here](https://docs.python.org/3/library/argparse.html#action)). To print out the contents of a text file, `myfile.txt` when the `-p` switch is given: ``` import argparse def print_file(filename): with open(filename) as fi: print(fi.read()) parser = argparse.ArgumentParser(description="A program to do something.") parser.add_argument('-p', help='Print a plain file.', action='store') args = parser.parse_args() if args.p: print_file(args.p) ``` Use with e.g. ``` $ prog.py -p the_filename.txt ```
In Python, you can simply use the reference to a function as a value in a data structure. E.g., consider the following code: ``` def spam(): print('Ham!') eggs = [spam, spam, spam] for x in eggs: x() ``` This would call three instances of the function `spam`. The [lambda expressions](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions) you are referring to are simply another way to define functions, without explicitly having to bind them to a name. Consider the following: ``` eggs = [lambda : print('ham'), lambda : print('spam')] for x in eggs: x() ``` This gets much more powerful when you're using arguments, though: ``` fn = [lambda x: return x + 3, lambda x: return x * 2] for f in fn: print(f(4)) ``` Once you have a reference to a function, you can then pass *that* to another function. ``` def foo(x): return x + 2 bar = lambda x: return x * 2 def h(g, f, x): return g(f(x)) print(h(foo, bar, 37)) ``` In your scenario, however, you could simply pass `lambda : print("version 1.0")`.
34,877,760
I'm getting into Python, and though of writing my own script which allows me to check arguments provided when a program is run. An example below of what I'm trying to achieve: `python file.py -v -h anotherfile.py` or `./file.py -v -h anotherfile.py` In these two cases, the `-v` and `-h` arguments, print out the module version, and a basic help file. I already have the code to differentiate between arguments and files, except I want to create a generalised module on the matter. The following code written in Java- ``` // Somewhere. public static HashMap<String, Runnable> args = new HashMap<String, Runnable>(); public void addArgument(String argument, Runnable command) { if (argument.length() > 0) { if (args.get(argument) == null) { args.put(argument, command); } else { System.err.println("Cannot add argument: " + argument + " to HashMap as the mapping already exists."); // Recover. } } } // Somewhere else. foo.addArgument("-v", () -> {System.out.println("version 1.0");}); foo.args.get("-v").run(); ``` -will run the Lambda Expressions *(atleast that's what I read they were when researching the topic)* successfully. I have no idea how Lambda Expressions work however, and have only basic knowledge of using them. **The point of this question, is how can I implement something like the Java example, in Python, storing any type of code inside of an array?** The thing is with the Java example though, if I have `int i = 0;` defined in the class which executes `addArgument` and uses `i` somehow or rather, the class containing `addArgument` knows to use `i` from the one that invoked it. I'm worried that this may not be the same case for Python... I want to be able to store them in dictionaries, or some other sort of key-based array, so I can store them in the following manner: ``` # Very rough example on the latter argument, showing what I'm after. addoption("-v", print("version 1.0")) ``` **EDIT: Example of what I want: (not working as is) (please ignore the ;'s)** ``` args = {}; def add(argument, command): args[argument] = lambda: command; # Same problem when removing 'lambda:' def run(): for arg in args: arg(); # Causing problems. def prnt(): print("test"); add("-v", prnt); run(); ```
2016/01/19
[ "https://Stackoverflow.com/questions/34877760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
EDIT: to correct your most recent code, iterating over a dictionary yields its keys not its values, so you need: ``` args = {}; def add(argument, command): args[argument] = command; def run(): for arg in args: args[arg]() # <<<<<<<<<< def prnt(): print("test"); add("-v", prnt); run(); ``` For the example you give, a dictionary of functions, although possible, isn't really the natural way to go about things in Python. The standard library has a module, [`argparse`](https://docs.python.org/3/library/argparse.html) specifically for dealing with all things commmand-line argument related, and rather than using keys to a dictionary you can parse the command line arguments and refer to their stored constants. ``` import argparse def output_version(): print('Version 1.0!') parser = argparse.ArgumentParser(description="A program to do something.") parser.add_argument('-v', help='Output version number.', action='store_true') args = parser.parse_args() if args.v: output_version() ``` (In fact outputting a version string is also handled natively by `argparse`: see [here](https://docs.python.org/3/library/argparse.html#action)). To print out the contents of a text file, `myfile.txt` when the `-p` switch is given: ``` import argparse def print_file(filename): with open(filename) as fi: print(fi.read()) parser = argparse.ArgumentParser(description="A program to do something.") parser.add_argument('-p', help='Print a plain file.', action='store') args = parser.parse_args() if args.p: print_file(args.p) ``` Use with e.g. ``` $ prog.py -p the_filename.txt ```
Python has a function called [`eval()`](https://stackoverflow.com/questions/9383740/what-does-pythons-eval-do) that takes strings and tries to evaluate them as code. ``` >>> eval("2+3") 5 ``` Then you can store your code as multi-line strings using 3 quotation marks ``` x = """the quick brown fox jumps over the lazy dogs""" ``` If you want to store the functions themselves, no reason why they can't also be placed in a dictionary. Even without lambdas. ``` def f(): return 1 def g(x): return x + 1 def h(x): return 2*x F = [f,g,h] G = {"a": f, "b": g, "c": h} (F[0](), G["a"]()) ``` The value of the tuple is `(1,1)`. Otherwise I don't know what you are asking for.
34,877,760
I'm getting into Python, and though of writing my own script which allows me to check arguments provided when a program is run. An example below of what I'm trying to achieve: `python file.py -v -h anotherfile.py` or `./file.py -v -h anotherfile.py` In these two cases, the `-v` and `-h` arguments, print out the module version, and a basic help file. I already have the code to differentiate between arguments and files, except I want to create a generalised module on the matter. The following code written in Java- ``` // Somewhere. public static HashMap<String, Runnable> args = new HashMap<String, Runnable>(); public void addArgument(String argument, Runnable command) { if (argument.length() > 0) { if (args.get(argument) == null) { args.put(argument, command); } else { System.err.println("Cannot add argument: " + argument + " to HashMap as the mapping already exists."); // Recover. } } } // Somewhere else. foo.addArgument("-v", () -> {System.out.println("version 1.0");}); foo.args.get("-v").run(); ``` -will run the Lambda Expressions *(atleast that's what I read they were when researching the topic)* successfully. I have no idea how Lambda Expressions work however, and have only basic knowledge of using them. **The point of this question, is how can I implement something like the Java example, in Python, storing any type of code inside of an array?** The thing is with the Java example though, if I have `int i = 0;` defined in the class which executes `addArgument` and uses `i` somehow or rather, the class containing `addArgument` knows to use `i` from the one that invoked it. I'm worried that this may not be the same case for Python... I want to be able to store them in dictionaries, or some other sort of key-based array, so I can store them in the following manner: ``` # Very rough example on the latter argument, showing what I'm after. addoption("-v", print("version 1.0")) ``` **EDIT: Example of what I want: (not working as is) (please ignore the ;'s)** ``` args = {}; def add(argument, command): args[argument] = lambda: command; # Same problem when removing 'lambda:' def run(): for arg in args: arg(); # Causing problems. def prnt(): print("test"); add("-v", prnt); run(); ```
2016/01/19
[ "https://Stackoverflow.com/questions/34877760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Since in Python functions are first-class objects, you may create dictionary of `{string: callable}` pairs. ``` def help(): print("Usage: xyz") d = { 'help': help, 'version': lambda: print("1.0"), # lambda is also callable } ``` After definition like that usage would be following: ``` my_function = d["help"] # retrieves function stored under key 'help' in dict my_function() # calls function # or obviously you may drop explainatory variable d['help']() ``` It'll work for your custom solution with problem defined like that. For standardized way of creating command line interfaces you may want to get familiar with [argparse module](https://docs.python.org/3/library/argparse.html).
Python has a function called [`eval()`](https://stackoverflow.com/questions/9383740/what-does-pythons-eval-do) that takes strings and tries to evaluate them as code. ``` >>> eval("2+3") 5 ``` Then you can store your code as multi-line strings using 3 quotation marks ``` x = """the quick brown fox jumps over the lazy dogs""" ``` If you want to store the functions themselves, no reason why they can't also be placed in a dictionary. Even without lambdas. ``` def f(): return 1 def g(x): return x + 1 def h(x): return 2*x F = [f,g,h] G = {"a": f, "b": g, "c": h} (F[0](), G["a"]()) ``` The value of the tuple is `(1,1)`. Otherwise I don't know what you are asking for.
34,877,760
I'm getting into Python, and though of writing my own script which allows me to check arguments provided when a program is run. An example below of what I'm trying to achieve: `python file.py -v -h anotherfile.py` or `./file.py -v -h anotherfile.py` In these two cases, the `-v` and `-h` arguments, print out the module version, and a basic help file. I already have the code to differentiate between arguments and files, except I want to create a generalised module on the matter. The following code written in Java- ``` // Somewhere. public static HashMap<String, Runnable> args = new HashMap<String, Runnable>(); public void addArgument(String argument, Runnable command) { if (argument.length() > 0) { if (args.get(argument) == null) { args.put(argument, command); } else { System.err.println("Cannot add argument: " + argument + " to HashMap as the mapping already exists."); // Recover. } } } // Somewhere else. foo.addArgument("-v", () -> {System.out.println("version 1.0");}); foo.args.get("-v").run(); ``` -will run the Lambda Expressions *(atleast that's what I read they were when researching the topic)* successfully. I have no idea how Lambda Expressions work however, and have only basic knowledge of using them. **The point of this question, is how can I implement something like the Java example, in Python, storing any type of code inside of an array?** The thing is with the Java example though, if I have `int i = 0;` defined in the class which executes `addArgument` and uses `i` somehow or rather, the class containing `addArgument` knows to use `i` from the one that invoked it. I'm worried that this may not be the same case for Python... I want to be able to store them in dictionaries, or some other sort of key-based array, so I can store them in the following manner: ``` # Very rough example on the latter argument, showing what I'm after. addoption("-v", print("version 1.0")) ``` **EDIT: Example of what I want: (not working as is) (please ignore the ;'s)** ``` args = {}; def add(argument, command): args[argument] = lambda: command; # Same problem when removing 'lambda:' def run(): for arg in args: arg(); # Causing problems. def prnt(): print("test"); add("-v", prnt); run(); ```
2016/01/19
[ "https://Stackoverflow.com/questions/34877760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
EDIT: to correct your most recent code, iterating over a dictionary yields its keys not its values, so you need: ``` args = {}; def add(argument, command): args[argument] = command; def run(): for arg in args: args[arg]() # <<<<<<<<<< def prnt(): print("test"); add("-v", prnt); run(); ``` For the example you give, a dictionary of functions, although possible, isn't really the natural way to go about things in Python. The standard library has a module, [`argparse`](https://docs.python.org/3/library/argparse.html) specifically for dealing with all things commmand-line argument related, and rather than using keys to a dictionary you can parse the command line arguments and refer to their stored constants. ``` import argparse def output_version(): print('Version 1.0!') parser = argparse.ArgumentParser(description="A program to do something.") parser.add_argument('-v', help='Output version number.', action='store_true') args = parser.parse_args() if args.v: output_version() ``` (In fact outputting a version string is also handled natively by `argparse`: see [here](https://docs.python.org/3/library/argparse.html#action)). To print out the contents of a text file, `myfile.txt` when the `-p` switch is given: ``` import argparse def print_file(filename): with open(filename) as fi: print(fi.read()) parser = argparse.ArgumentParser(description="A program to do something.") parser.add_argument('-p', help='Print a plain file.', action='store') args = parser.parse_args() if args.p: print_file(args.p) ``` Use with e.g. ``` $ prog.py -p the_filename.txt ```
Since in Python functions are first-class objects, you may create dictionary of `{string: callable}` pairs. ``` def help(): print("Usage: xyz") d = { 'help': help, 'version': lambda: print("1.0"), # lambda is also callable } ``` After definition like that usage would be following: ``` my_function = d["help"] # retrieves function stored under key 'help' in dict my_function() # calls function # or obviously you may drop explainatory variable d['help']() ``` It'll work for your custom solution with problem defined like that. For standardized way of creating command line interfaces you may want to get familiar with [argparse module](https://docs.python.org/3/library/argparse.html).
22,403,634
I'm trying to follow the documentation provided by Aldebaran [here](https://community.aldebaran-robotics.com/doc/1-14/dev/python/install_guide.html#python-install-guide) in order to get my NAO ready for Python programming. I correctly downloaded the NAOqi framework adapted to my OS (linux 64 bits) then I typed the command line `$ export PYTHONPATH=${PYTHONPATH}:/path/to/python-sdk` which, if I understand things right, should be typed in a terminal and not in a Python shell. Then I typed `import naoqi` in a Python shell and got the `ImportError: No module named naoqi` error, so I tried [troubleshooting](https://community.aldebaran-robotics.com/doc/1-14/dev/python/tips-and-tricks.html#python-sdk-troubleshooting) and typed ``` import sys print "\n".join(sys.path) ``` in the same Python shell and got the following output: ``` /home/***** /usr/bin /usr/lib/python2.7 /usr/lib/python2.7/plat-linux2 /usr/lib/python2.7/lib-tk /usr/lib/python2.7/lib-old /usr/lib/python2.7/lib-dynload /usr/local/lib/python2.7/dist-packages /usr/lib/python2.7/dist-packages /usr/lib/python2.7/dist-packages/PIL /usr/lib/python2.7/dist-packages/gst-0.10 /usr/lib/python2.7/dist-packages/gtk-2.0 /usr/lib/python2.7/dist-packages/ubuntu-sso-client /usr/lib/python2.7/dist-packages/ubuntuone-client /usr/lib/python2.7/dist-packages/ubuntuone-control-panel /usr/lib/python2.7/dist-packages/ubuntuone-couch /usr/lib/python2.7/dist-packages/ubuntuone-installer /usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol` ``` So I indeed don't have `/path/to/python-sdk` as I should, but not I'm blocked. What should I do to solve that? (I am new to Linux, Python, and NAO, so perhaps the answer is obvious, but I've been trying to configure NAO for almost a week, so I definitely need some help.)
2014/03/14
[ "https://Stackoverflow.com/questions/22403634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Regarding your second example, remove the fixed height of 60px. 60px isn't enough for the image and the header tag when they stack. That will fix the overlapping you see because the next block of text begins 60px below the top of the previous row (despite the fact that your h1 tag continues below the 60px height. ``` <div class="row" style="height: 60px;"> <div class="col-sm-2 text-center"><img src="{{asset('images/icons/heart.jpg')}}" style="height:48px; max-width: 100%; max-height: 100%;"></div> <div class="col-sm-10"><h1><strong>03</strong><br>Our Values</h1></div> </div> ``` <http://jsfiddle.net/QzTU9/9/>
Try To remove all those in-line style Boss.. The error will Automatically vanish... ``` > Here Is the fiddle : http://jsfiddle.net/chermanarun/QzTU9/10/ ```
29,221,836
Hello i want to install these dependencies in OpenShift for my App `yum -y install wget gcc zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel libffi-devel libxslt libxslt-devel libxml2 libxml2-devel openldap-devel libjpeg-turbo-devel openjpeg-devel libtiff-devel libyaml-devel python-virtualenv git libpng12 libXext xorg-x11-font-utils` But don't know how, is it through rhc? if so, how?
2015/03/23
[ "https://Stackoverflow.com/questions/29221836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3809894/" ]
There is no reason using anything else than `ABS()`. Generics for intrinsic procedures were already present in FORTRAN 77. You can use them for all intrinsic numeric types. If you want to see the table of available specific functions of the generic `ABS()`, see <https://gcc.gnu.org/onlinedocs/gfortran/ABS.html> , but they are mostly useful only to be passed as actual arguments. You can see that `CDABS()` is a non-standard extension and I do not recommend to use it.
`CABS` is defined by the standard to take an argument of type default complex. In your implementation this looks like `complex(kind=4)`. There is no standard function `CDABS`, although your implementation may perhaps offer one: read the appropriate documentation. Further, there is no standard specific function for the generic function `ABS` which takes a `double complex` argument. Again, your implementation may offer one called something other than `CDABS`. That said, the generic function `ABS` takes any integer, real, or complex argument. Use that.
29,221,836
Hello i want to install these dependencies in OpenShift for my App `yum -y install wget gcc zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel libffi-devel libxslt libxslt-devel libxml2 libxml2-devel openldap-devel libjpeg-turbo-devel openjpeg-devel libtiff-devel libyaml-devel python-virtualenv git libpng12 libXext xorg-x11-font-utils` But don't know how, is it through rhc? if so, how?
2015/03/23
[ "https://Stackoverflow.com/questions/29221836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3809894/" ]
There is no reason using anything else than `ABS()`. Generics for intrinsic procedures were already present in FORTRAN 77. You can use them for all intrinsic numeric types. If you want to see the table of available specific functions of the generic `ABS()`, see <https://gcc.gnu.org/onlinedocs/gfortran/ABS.html> , but they are mostly useful only to be passed as actual arguments. You can see that `CDABS()` is a non-standard extension and I do not recommend to use it.
COMPLEX\*8 and complex(KIND=8) are not the same. The first one, is 4 byte real and 4 byte imaginary. The complex(KIND=8) or COMPLEX(KIND=C\_DOUBLE) is actually a double precision real and double precision imaginary... So equivalent to COMPLEX\*16. As mentioned ABS() should be fine.
29,221,836
Hello i want to install these dependencies in OpenShift for my App `yum -y install wget gcc zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel libffi-devel libxslt libxslt-devel libxml2 libxml2-devel openldap-devel libjpeg-turbo-devel openjpeg-devel libtiff-devel libyaml-devel python-virtualenv git libpng12 libXext xorg-x11-font-utils` But don't know how, is it through rhc? if so, how?
2015/03/23
[ "https://Stackoverflow.com/questions/29221836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3809894/" ]
`CABS` is defined by the standard to take an argument of type default complex. In your implementation this looks like `complex(kind=4)`. There is no standard function `CDABS`, although your implementation may perhaps offer one: read the appropriate documentation. Further, there is no standard specific function for the generic function `ABS` which takes a `double complex` argument. Again, your implementation may offer one called something other than `CDABS`. That said, the generic function `ABS` takes any integer, real, or complex argument. Use that.
COMPLEX\*8 and complex(KIND=8) are not the same. The first one, is 4 byte real and 4 byte imaginary. The complex(KIND=8) or COMPLEX(KIND=C\_DOUBLE) is actually a double precision real and double precision imaginary... So equivalent to COMPLEX\*16. As mentioned ABS() should be fine.
19,596,750
I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out. ``` print("Hey") >Hey ``` Now I need to clear it, and write some new text. ``` print("How is your day?") ``` It would print. > > Hey > > > ``` >How is your day? ``` But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.
2013/10/25
[ "https://Stackoverflow.com/questions/19596750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2912324/" ]
``` import os os.system('cls') ``` Or `os.system('clear')` on unix (mac and linux). If you don't want the scroll up either, then you *can* do this: `os.system("printf '\033c'")` should get rid of scroll back too. Something that works on all systems: ``` import os os.system('cls' if os.name == 'nt' else "printf '\033c'") ```
I think this is what you want to do: > > take the cursor one line up and delete the line > > > this can be done like using the code below ``` import sys import time def delete_last_line(): "Use this function to delete the last line in the STDOUT" #cursor up one line sys.stdout.write('\x1b[1A') #delete last line sys.stdout.write('\x1b[2K') ########## FOR DEMO ################ if __name__ == "__main__": print("hello") print("this line will be delete after 2 seconds") time.sleep(2) delete_last_line() #################################### ```
19,596,750
I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out. ``` print("Hey") >Hey ``` Now I need to clear it, and write some new text. ``` print("How is your day?") ``` It would print. > > Hey > > > ``` >How is your day? ``` But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.
2013/10/25
[ "https://Stackoverflow.com/questions/19596750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2912324/" ]
``` import os os.system('cls') ``` Or `os.system('clear')` on unix (mac and linux). If you don't want the scroll up either, then you *can* do this: `os.system("printf '\033c'")` should get rid of scroll back too. Something that works on all systems: ``` import os os.system('cls' if os.name == 'nt' else "printf '\033c'") ```
Well I have a temporary way: ```py print("Hey", end="") for i in range(4): print('\b', end = '') print("How is your day?") ```
19,596,750
I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out. ``` print("Hey") >Hey ``` Now I need to clear it, and write some new text. ``` print("How is your day?") ``` It would print. > > Hey > > > ``` >How is your day? ``` But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.
2013/10/25
[ "https://Stackoverflow.com/questions/19596750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2912324/" ]
``` import os os.system('cls') ``` Or `os.system('clear')` on unix (mac and linux). If you don't want the scroll up either, then you *can* do this: `os.system("printf '\033c'")` should get rid of scroll back too. Something that works on all systems: ``` import os os.system('cls' if os.name == 'nt' else "printf '\033c'") ```
The escape character `\r` (carriage return), means "start printing from beginning of this line". But some of operating systems use it as 'newline'. Following would work in Linux: ``` import time import sys #first text print('Hey.', end="") #flush stdout sys.stdout.flush() #wait a second time.sleep(1) #write a carriage return and new text print('\rHow is your day?') ```
19,596,750
I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out. ``` print("Hey") >Hey ``` Now I need to clear it, and write some new text. ``` print("How is your day?") ``` It would print. > > Hey > > > ``` >How is your day? ``` But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.
2013/10/25
[ "https://Stackoverflow.com/questions/19596750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2912324/" ]
``` import os os.system('cls') ``` Or `os.system('clear')` on unix (mac and linux). If you don't want the scroll up either, then you *can* do this: `os.system("printf '\033c'")` should get rid of scroll back too. Something that works on all systems: ``` import os os.system('cls' if os.name == 'nt' else "printf '\033c'") ```
Small addition into `@Aniket Navlur` 's answer in order to delete multiple lines: ```py def delete_multiple_lines(n=1): """Delete the last line in the STDOUT.""" for _ in range(n): sys.stdout.write("\x1b[1A") # cursor up one line sys.stdout.write("\x1b[2K") # delete the last line ```
19,596,750
I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out. ``` print("Hey") >Hey ``` Now I need to clear it, and write some new text. ``` print("How is your day?") ``` It would print. > > Hey > > > ``` >How is your day? ``` But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.
2013/10/25
[ "https://Stackoverflow.com/questions/19596750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2912324/" ]
I think this is what you want to do: > > take the cursor one line up and delete the line > > > this can be done like using the code below ``` import sys import time def delete_last_line(): "Use this function to delete the last line in the STDOUT" #cursor up one line sys.stdout.write('\x1b[1A') #delete last line sys.stdout.write('\x1b[2K') ########## FOR DEMO ################ if __name__ == "__main__": print("hello") print("this line will be delete after 2 seconds") time.sleep(2) delete_last_line() #################################### ```
Well I have a temporary way: ```py print("Hey", end="") for i in range(4): print('\b', end = '') print("How is your day?") ```
19,596,750
I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out. ``` print("Hey") >Hey ``` Now I need to clear it, and write some new text. ``` print("How is your day?") ``` It would print. > > Hey > > > ``` >How is your day? ``` But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.
2013/10/25
[ "https://Stackoverflow.com/questions/19596750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2912324/" ]
I think this is what you want to do: > > take the cursor one line up and delete the line > > > this can be done like using the code below ``` import sys import time def delete_last_line(): "Use this function to delete the last line in the STDOUT" #cursor up one line sys.stdout.write('\x1b[1A') #delete last line sys.stdout.write('\x1b[2K') ########## FOR DEMO ################ if __name__ == "__main__": print("hello") print("this line will be delete after 2 seconds") time.sleep(2) delete_last_line() #################################### ```
The escape character `\r` (carriage return), means "start printing from beginning of this line". But some of operating systems use it as 'newline'. Following would work in Linux: ``` import time import sys #first text print('Hey.', end="") #flush stdout sys.stdout.flush() #wait a second time.sleep(1) #write a carriage return and new text print('\rHow is your day?') ```
19,596,750
I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out. ``` print("Hey") >Hey ``` Now I need to clear it, and write some new text. ``` print("How is your day?") ``` It would print. > > Hey > > > ``` >How is your day? ``` But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.
2013/10/25
[ "https://Stackoverflow.com/questions/19596750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2912324/" ]
I think this is what you want to do: > > take the cursor one line up and delete the line > > > this can be done like using the code below ``` import sys import time def delete_last_line(): "Use this function to delete the last line in the STDOUT" #cursor up one line sys.stdout.write('\x1b[1A') #delete last line sys.stdout.write('\x1b[2K') ########## FOR DEMO ################ if __name__ == "__main__": print("hello") print("this line will be delete after 2 seconds") time.sleep(2) delete_last_line() #################################### ```
Small addition into `@Aniket Navlur` 's answer in order to delete multiple lines: ```py def delete_multiple_lines(n=1): """Delete the last line in the STDOUT.""" for _ in range(n): sys.stdout.write("\x1b[1A") # cursor up one line sys.stdout.write("\x1b[2K") # delete the last line ```
19,596,750
I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out. ``` print("Hey") >Hey ``` Now I need to clear it, and write some new text. ``` print("How is your day?") ``` It would print. > > Hey > > > ``` >How is your day? ``` But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.
2013/10/25
[ "https://Stackoverflow.com/questions/19596750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2912324/" ]
Well I have a temporary way: ```py print("Hey", end="") for i in range(4): print('\b', end = '') print("How is your day?") ```
The escape character `\r` (carriage return), means "start printing from beginning of this line". But some of operating systems use it as 'newline'. Following would work in Linux: ``` import time import sys #first text print('Hey.', end="") #flush stdout sys.stdout.flush() #wait a second time.sleep(1) #write a carriage return and new text print('\rHow is your day?') ```
19,596,750
I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out. ``` print("Hey") >Hey ``` Now I need to clear it, and write some new text. ``` print("How is your day?") ``` It would print. > > Hey > > > ``` >How is your day? ``` But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.
2013/10/25
[ "https://Stackoverflow.com/questions/19596750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2912324/" ]
Small addition into `@Aniket Navlur` 's answer in order to delete multiple lines: ```py def delete_multiple_lines(n=1): """Delete the last line in the STDOUT.""" for _ in range(n): sys.stdout.write("\x1b[1A") # cursor up one line sys.stdout.write("\x1b[2K") # delete the last line ```
The escape character `\r` (carriage return), means "start printing from beginning of this line". But some of operating systems use it as 'newline'. Following would work in Linux: ``` import time import sys #first text print('Hey.', end="") #flush stdout sys.stdout.flush() #wait a second time.sleep(1) #write a carriage return and new text print('\rHow is your day?') ```
33,689,721
[Accuracy, precision, recall and f-score](https://en.wikipedia.org/wiki/Precision_and_recall) are measures of a system quality in machine-learning systems. It depends on a confusion matrix of True/False Positives/Negatives. Given a binary classification task, I have tried the following to get a function that returns accuracy, precision, recall and f-score: ``` gold = [1] + [0] * 9 predicted = [1] * 10 def evaluation(gold, predicted): true_pos = sum(1 for p,g in zip(predicted, gold) if p==1 and g==1) true_neg = sum(1 for p,g in zip(predicted, gold) if p==0 and g==0) false_pos = sum(1 for p,g in zip(predicted, gold) if p==1 and g==0) false_neg = sum(1 for p,g in zip(predicted, gold) if p==0 and g==1) try: recall = true_pos / float(true_pos + false_neg) except: recall = 0 try: precision = true_pos / float(true_pos + false_pos) except: precision = 0 try: fscore = 2*precision*recall / (precision + recall) except: fscore = 0 try: accuracy = (true_pos + true_neg) / float(len(gold)) except: accuracy = 0 return accuracy, precision, recall, fscore ``` But it seems like I have redundantly looped through the dataset 4 times to get the True/False Positives/Negatives. Also the multiple `try-excepts` to catch the `ZeroDivisionError` is a little redundant. **So what is the pythonic way to get the counts of the True/False Positives/Negatives without multiple loops through the dataset?** **How do I pythonically catch the `ZeroDivisionError` without the multiple try-excepts?** --- I could also do the following to count the True/False Positives/Negatives in one loop but **is there an alternative way without the multiple `if`?**: ``` for p,g in zip(predicted, gold): if p==1 and g==1: true_pos+=1 if p==0 and g==0: true_neg+=1 if p==1 and g==0: false_pos+=1 if p==0 and g==1: false_neg+=1 ```
2015/11/13
[ "https://Stackoverflow.com/questions/33689721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
> > what is the pythonic way to get the counts of the True/False > Positives/Negatives without multiple loops through the dataset? > > > I would use a [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter), roughly what you're doing with all of the `if`s (you should be using `elif`s, as your conditions are mutually exclusive) at the end: ``` counts = Counter(zip(predicted, gold)) ``` Then e.g. `true_pos = counts[1, 1]`. > > How do I pythonically catch the ZeroDivisionError without the multiple > try-excepts? > > > For a start, you should (almost) never use a bare `except:`. If you're catching `ZeroDivisionError`s, then write `except ZeroDivisionError`. You could also consider a [*"look before you leap"*](https://docs.python.org/2/glossary.html#term-lbyl) approach, checking whether the denominator is `0` before trying the division, e.g. ``` accuracy = (true_pos + true_neg) / float(len(gold)) if gold else 0 ```
Depending on your needs, there are several libraries that will calculate precision, recall, F-score, etc. One that I have used is `scikit-learn`. Assuming that you have aligned `list`s of actual and predicted values, then it is as simple as... ``` from sklearn.metrics import precision_recall_fscore_support as pr bPrecis, bRecall, bFscore, bSupport = pr(gold, predicted, average='binary') ``` One of the advantages of using this library is that different flavors of metrics (such as micro-averaging, macro-averaging, weighted, binary, etc.) come free out of the box.
33,689,721
[Accuracy, precision, recall and f-score](https://en.wikipedia.org/wiki/Precision_and_recall) are measures of a system quality in machine-learning systems. It depends on a confusion matrix of True/False Positives/Negatives. Given a binary classification task, I have tried the following to get a function that returns accuracy, precision, recall and f-score: ``` gold = [1] + [0] * 9 predicted = [1] * 10 def evaluation(gold, predicted): true_pos = sum(1 for p,g in zip(predicted, gold) if p==1 and g==1) true_neg = sum(1 for p,g in zip(predicted, gold) if p==0 and g==0) false_pos = sum(1 for p,g in zip(predicted, gold) if p==1 and g==0) false_neg = sum(1 for p,g in zip(predicted, gold) if p==0 and g==1) try: recall = true_pos / float(true_pos + false_neg) except: recall = 0 try: precision = true_pos / float(true_pos + false_pos) except: precision = 0 try: fscore = 2*precision*recall / (precision + recall) except: fscore = 0 try: accuracy = (true_pos + true_neg) / float(len(gold)) except: accuracy = 0 return accuracy, precision, recall, fscore ``` But it seems like I have redundantly looped through the dataset 4 times to get the True/False Positives/Negatives. Also the multiple `try-excepts` to catch the `ZeroDivisionError` is a little redundant. **So what is the pythonic way to get the counts of the True/False Positives/Negatives without multiple loops through the dataset?** **How do I pythonically catch the `ZeroDivisionError` without the multiple try-excepts?** --- I could also do the following to count the True/False Positives/Negatives in one loop but **is there an alternative way without the multiple `if`?**: ``` for p,g in zip(predicted, gold): if p==1 and g==1: true_pos+=1 if p==0 and g==0: true_neg+=1 if p==1 and g==0: false_pos+=1 if p==0 and g==1: false_neg+=1 ```
2015/11/13
[ "https://Stackoverflow.com/questions/33689721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
> > what is the pythonic way to get the counts of the True/False > Positives/Negatives without multiple loops through the dataset? > > > I would use a [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter), roughly what you're doing with all of the `if`s (you should be using `elif`s, as your conditions are mutually exclusive) at the end: ``` counts = Counter(zip(predicted, gold)) ``` Then e.g. `true_pos = counts[1, 1]`. > > How do I pythonically catch the ZeroDivisionError without the multiple > try-excepts? > > > For a start, you should (almost) never use a bare `except:`. If you're catching `ZeroDivisionError`s, then write `except ZeroDivisionError`. You could also consider a [*"look before you leap"*](https://docs.python.org/2/glossary.html#term-lbyl) approach, checking whether the denominator is `0` before trying the division, e.g. ``` accuracy = (true_pos + true_neg) / float(len(gold)) if gold else 0 ```
This is a pretty natural use case for the [bitarray](https://pypi.python.org/pypi/bitarray/0.8.1) package. ``` import bitarray as bt tp = (bt.bitarray(p) & bt.bitarray(g)).count() tn = (~bt.bitarray(p) & ~bt.bitarray(g)).count() fp = (bt.bitarray(p) & ~bt.bitarray(g)).count() fn = (~bt.bitarray(p) & bt.bitarray(g)).count() ``` There's some type conversion overhead, but after that, the bitwise operations are much faster. For 100 instances, timeit on my PC gives 0.036 for your method and 0.017 using bitarray at 1000 passes. For 1000 instances, it goes to 0.291 and 0.093. For 10000, 3.177 and 0.863. You get the idea. It scales pretty well, using no loops, and doesn't have to store a large intermediate representation building a temporary list of tuples in `zip`.
33,689,721
[Accuracy, precision, recall and f-score](https://en.wikipedia.org/wiki/Precision_and_recall) are measures of a system quality in machine-learning systems. It depends on a confusion matrix of True/False Positives/Negatives. Given a binary classification task, I have tried the following to get a function that returns accuracy, precision, recall and f-score: ``` gold = [1] + [0] * 9 predicted = [1] * 10 def evaluation(gold, predicted): true_pos = sum(1 for p,g in zip(predicted, gold) if p==1 and g==1) true_neg = sum(1 for p,g in zip(predicted, gold) if p==0 and g==0) false_pos = sum(1 for p,g in zip(predicted, gold) if p==1 and g==0) false_neg = sum(1 for p,g in zip(predicted, gold) if p==0 and g==1) try: recall = true_pos / float(true_pos + false_neg) except: recall = 0 try: precision = true_pos / float(true_pos + false_pos) except: precision = 0 try: fscore = 2*precision*recall / (precision + recall) except: fscore = 0 try: accuracy = (true_pos + true_neg) / float(len(gold)) except: accuracy = 0 return accuracy, precision, recall, fscore ``` But it seems like I have redundantly looped through the dataset 4 times to get the True/False Positives/Negatives. Also the multiple `try-excepts` to catch the `ZeroDivisionError` is a little redundant. **So what is the pythonic way to get the counts of the True/False Positives/Negatives without multiple loops through the dataset?** **How do I pythonically catch the `ZeroDivisionError` without the multiple try-excepts?** --- I could also do the following to count the True/False Positives/Negatives in one loop but **is there an alternative way without the multiple `if`?**: ``` for p,g in zip(predicted, gold): if p==1 and g==1: true_pos+=1 if p==0 and g==0: true_neg+=1 if p==1 and g==0: false_pos+=1 if p==0 and g==1: false_neg+=1 ```
2015/11/13
[ "https://Stackoverflow.com/questions/33689721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
This is a pretty natural use case for the [bitarray](https://pypi.python.org/pypi/bitarray/0.8.1) package. ``` import bitarray as bt tp = (bt.bitarray(p) & bt.bitarray(g)).count() tn = (~bt.bitarray(p) & ~bt.bitarray(g)).count() fp = (bt.bitarray(p) & ~bt.bitarray(g)).count() fn = (~bt.bitarray(p) & bt.bitarray(g)).count() ``` There's some type conversion overhead, but after that, the bitwise operations are much faster. For 100 instances, timeit on my PC gives 0.036 for your method and 0.017 using bitarray at 1000 passes. For 1000 instances, it goes to 0.291 and 0.093. For 10000, 3.177 and 0.863. You get the idea. It scales pretty well, using no loops, and doesn't have to store a large intermediate representation building a temporary list of tuples in `zip`.
Depending on your needs, there are several libraries that will calculate precision, recall, F-score, etc. One that I have used is `scikit-learn`. Assuming that you have aligned `list`s of actual and predicted values, then it is as simple as... ``` from sklearn.metrics import precision_recall_fscore_support as pr bPrecis, bRecall, bFscore, bSupport = pr(gold, predicted, average='binary') ``` One of the advantages of using this library is that different flavors of metrics (such as micro-averaging, macro-averaging, weighted, binary, etc.) come free out of the box.
37,602,126
I am trying to get Fab up and running locally. Why is Fab installing to `/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5`? The system Python version is 2.7.10, confirmed below: ``` Toms-MBP:~ tom$ which python /usr/local/bin/python Toms-MBP:~ tom$ python --version Python 2.7.10 Toms-MBP:~ tom$ head -1 `which fab` #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 Toms-MBP:~ tom$ fab Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/bin/fab", line 9, in <module> load_entry_point('Fabric==1.11.1', 'console_scripts', 'fab')() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/__init__.py", line 558, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2682, in load_entry_point return ep.load() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2355, in load return self.resolve() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2361, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/fabric/main.py", line 13, in <module> from operator import isMappingType ImportError: cannot import name 'isMappingType' ```
2016/06/02
[ "https://Stackoverflow.com/questions/37602126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416103/" ]
you need this: ``` pip install fabric3 ```
Its look like you aren't using a virtualenv configured previously, so I think that the system just uses the normal path to `python` which means to `/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5` . This error is usual when we try use `Fabric` with `python3.x` because `Fabric` has not been update to this version of `python` which is really sad.
59,542,995
I am trying to write a character through serial to Arduino which runs a code to control a IR-led for remote-control purpose. Running code in Arduino-terminal works, the led does its job. The Arduino-code works. Running line by line in shell works, no problem. But when i run "python remote.py" it does not work. I tried an extra piece of code to make sure its the same version of python being run by both shell and interpreter at the command prompt. ``` import sys sys.stdout.write("Hello from Python %s\n" % (sys.version,)) ``` And it results in "Python 3.7.3" which is the version of shell when i start that. This is the entire Python code: ``` import serial ser = serial.Serial('COM7', 9600) ser.write('a'.encode()) ser.close() ``` I realise it is not very "Pythonic" or even entirely correct, but to simplify and to try and have as little code as possible i cut out everything that did not had to be in. Since the code runs in shell, its some how correct? The Arduino code is here: <https://pastebin.com/7T2yFzrL> I use Python 3.7.3 under Windows 10 with Notepad++ I found this thread: [Arduino Python3 script](https://stackoverflow.com/questions/24682354/arduino-python3-script), but i do not understand how my code can work in shell and not in script? It could be the codepoint (What that means I dont understand) but in that case how do i correct it? No errors are shown either. I hope someone can steer me in the right direction. /Best regards Magnus Tried an addition to my code after suggestion from T. Feix new code like this: ``` #! python3 import serial try: ser = serial.Serial('COM7', 9600) ser.write('a'.encode()) ser.close() except input() as ex: print(ex) ``` unfortunately it does not return anything, no error no nothing? My code on the Arduino expects an char and the Python seems to send a Byte, is that perhaps the error and if so how do i change either type? Have now changed the expected datatype on the Arduino to Byte, the code still works in terminal but no luck as i run the Python script.
2019/12/31
[ "https://Stackoverflow.com/questions/59542995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12631437/" ]
The problem is solved, i found an answer i did not find before. [pySerial write() works fine in Python interpreter, but not Python script](https://stackoverflow.com/questions/28192190/pyserial-write-works-fine-in-python-interpreter-but-not-python-script?rq=1) It was the fast execution of the script, and a little delay of 2 seconds did the difference. I thank you all who have had suggestions to a solution and intend to wrap this up. Happy new year to you all!
I have tired your program with a simple loop-back. It is working as expected: ``` import serial try: ser = serial.Serial("/dev/ttyUSB0") print("Bytes Written: %d" % (ser.write("b".encode()))) ser.flush() print(ser.read()) ser.close() except Exception as e: print(e) ``` Output: ``` Bytes Written: 1 b'b' ``` I have called `flush` to make sure data has been written to the physical port. See this [link](https://pyserial.readthedocs.io/en/latest/pyserial_api.html) for more information. > > Flush of file like objects. In this case, wait until all data is written. > > > **Looks like there could be some issue with your wires or the arduino code.**
2,935,836
I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable the following behavior: 1. "`foo.py`" is launched from the command line, and it will stay running for a long time-- days or weeks until the machine is rebooted or the parent process kills it. 2. every few minutes the same script is launched again, but with different command-line parameters 3. when launched, the script should see if any other instances are running. 4. if other instances are running, then instance #2 should send its command-line parameters to instance #1, and then instance #2 should exit. 5. instance #1, if it receives command-line parameters from another script, should spin up a new thread and (using the command-line parameters sent in the step above) start performing the work that instance #2 was going to perform. So I'm looking for two things: how can a python program know another instance of itself is running, and then how can one python command-line program communicate with another? Making this more complicated, the same script needs to run on both Windows and Linux, so ideally the solution would use only the Python standard library and not any OS-specific calls. Although if I need to have a Windows codepath and an \*nix codepath (and a big `if` statement in my code to choose one or the other), that's OK if a "same code" solution isn't possible. I realize I could probably work out a file-based approach (e.g. instance #1 watches a directory for changes and each instance drops a file into that directory when it wants to do work) but I'm a little concerned about cleaning up those files after a non-graceful machine shutdown. I'd ideally be able to use an in-memory solution. But again I'm flexible, if a persistent-file-based approach is the only way to do it, I'm open to that option. More details: I'm trying to do this because our servers are using a monitoring tool which supports running python scripts to collect monitoring data (e.g. results of a database query or web service call) which the monitoring tool then indexes for later use. Some of these scripts are very expensive to start up but cheap to run after startup (e.g. making a DB connection vs. running a query). So we've chosen to keep them running in an infinite loop until the parent process kills them. This works great, but on larger servers 100 instances of the same script may be running, even if they're only gathering data every 20 minutes each. This wreaks havoc with RAM, DB connection limits, etc. We want to switch from 100 processes with 1 thread to one process with 100 threads, each executing the work that, previously, one script was doing. But changing how the scripts are invoked by the monitoring tool is not possible. We need to keep invocation the same (launch a process with different command-line parameters) but but change the scripts to recognize that another one is active, and have the "new" script send its work instructions (from the command line params) over to the "old" script. BTW, this is not something I want to do on a one-script basis. Instead, I want to package this behavior into a library which many script authors can leverage-- my goal is to enable script authors to write simple, single-threaded scripts which are unaware of multi-instance issues, and to handle the multi-threading and single-instancing under the covers.
2010/05/29
[ "https://Stackoverflow.com/questions/2935836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126352/" ]
The general approach is to have the script, on startup, set up a communication channel in a way that's guaranteed to be exclusive (other attempts to set up the same channel fail in a predictable way) so that further instances of the script can detect the first one's running *and* talk to it. Your requirements for cross-platform functionality strongly point towards using a socket as the communication channel in question: you can designate a "well known port" that's reserved for your script, say 12345, and open a socket on that port listening to localhost only (127.0.0.1). If the attempt to open that socket fails, because the port in question is "taken", then you can connect to that port number instead, and that will let you communicate with the existing script. If you're not familiar with socket programming, there's a good `HOWTO` doc [here](http://www.amk.ca/python/howto/sockets/). You can also look at the relevant chapter in [Python in a Nutshell](http://books.google.com/books?id=vpTAq4dnmuAC&pg=PA521&lpg=PA521&dq=python+socket+nutshell&source=bl&ots=AORax1F8wx&sig=qtSZR6r9vy9BWTW06PEIyvG_yUs&hl=en&ei=SkcBTKL3LKT4Mpbb4Ts&sa=X&oi=book_result&ct=result&resnum=5&ved=0CDEQ6AEwBA#v=onepage&q&f=false) (I'm biased about that one, of course;-).
Perhaps try using sockets for communication?
2,935,836
I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable the following behavior: 1. "`foo.py`" is launched from the command line, and it will stay running for a long time-- days or weeks until the machine is rebooted or the parent process kills it. 2. every few minutes the same script is launched again, but with different command-line parameters 3. when launched, the script should see if any other instances are running. 4. if other instances are running, then instance #2 should send its command-line parameters to instance #1, and then instance #2 should exit. 5. instance #1, if it receives command-line parameters from another script, should spin up a new thread and (using the command-line parameters sent in the step above) start performing the work that instance #2 was going to perform. So I'm looking for two things: how can a python program know another instance of itself is running, and then how can one python command-line program communicate with another? Making this more complicated, the same script needs to run on both Windows and Linux, so ideally the solution would use only the Python standard library and not any OS-specific calls. Although if I need to have a Windows codepath and an \*nix codepath (and a big `if` statement in my code to choose one or the other), that's OK if a "same code" solution isn't possible. I realize I could probably work out a file-based approach (e.g. instance #1 watches a directory for changes and each instance drops a file into that directory when it wants to do work) but I'm a little concerned about cleaning up those files after a non-graceful machine shutdown. I'd ideally be able to use an in-memory solution. But again I'm flexible, if a persistent-file-based approach is the only way to do it, I'm open to that option. More details: I'm trying to do this because our servers are using a monitoring tool which supports running python scripts to collect monitoring data (e.g. results of a database query or web service call) which the monitoring tool then indexes for later use. Some of these scripts are very expensive to start up but cheap to run after startup (e.g. making a DB connection vs. running a query). So we've chosen to keep them running in an infinite loop until the parent process kills them. This works great, but on larger servers 100 instances of the same script may be running, even if they're only gathering data every 20 minutes each. This wreaks havoc with RAM, DB connection limits, etc. We want to switch from 100 processes with 1 thread to one process with 100 threads, each executing the work that, previously, one script was doing. But changing how the scripts are invoked by the monitoring tool is not possible. We need to keep invocation the same (launch a process with different command-line parameters) but but change the scripts to recognize that another one is active, and have the "new" script send its work instructions (from the command line params) over to the "old" script. BTW, this is not something I want to do on a one-script basis. Instead, I want to package this behavior into a library which many script authors can leverage-- my goal is to enable script authors to write simple, single-threaded scripts which are unaware of multi-instance issues, and to handle the multi-threading and single-instancing under the covers.
2010/05/29
[ "https://Stackoverflow.com/questions/2935836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126352/" ]
Perhaps try using sockets for communication?
Sounds like your best bet is sticking with a pid file but have it not only contain the process Id - have it also include the port number that the prior instance is listening on. So when starting up check for the pid file and if present see if a process with that Id is running - if so send your data to it and quit otherwise overwrite the pid file with the current process's info.
2,935,836
I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable the following behavior: 1. "`foo.py`" is launched from the command line, and it will stay running for a long time-- days or weeks until the machine is rebooted or the parent process kills it. 2. every few minutes the same script is launched again, but with different command-line parameters 3. when launched, the script should see if any other instances are running. 4. if other instances are running, then instance #2 should send its command-line parameters to instance #1, and then instance #2 should exit. 5. instance #1, if it receives command-line parameters from another script, should spin up a new thread and (using the command-line parameters sent in the step above) start performing the work that instance #2 was going to perform. So I'm looking for two things: how can a python program know another instance of itself is running, and then how can one python command-line program communicate with another? Making this more complicated, the same script needs to run on both Windows and Linux, so ideally the solution would use only the Python standard library and not any OS-specific calls. Although if I need to have a Windows codepath and an \*nix codepath (and a big `if` statement in my code to choose one or the other), that's OK if a "same code" solution isn't possible. I realize I could probably work out a file-based approach (e.g. instance #1 watches a directory for changes and each instance drops a file into that directory when it wants to do work) but I'm a little concerned about cleaning up those files after a non-graceful machine shutdown. I'd ideally be able to use an in-memory solution. But again I'm flexible, if a persistent-file-based approach is the only way to do it, I'm open to that option. More details: I'm trying to do this because our servers are using a monitoring tool which supports running python scripts to collect monitoring data (e.g. results of a database query or web service call) which the monitoring tool then indexes for later use. Some of these scripts are very expensive to start up but cheap to run after startup (e.g. making a DB connection vs. running a query). So we've chosen to keep them running in an infinite loop until the parent process kills them. This works great, but on larger servers 100 instances of the same script may be running, even if they're only gathering data every 20 minutes each. This wreaks havoc with RAM, DB connection limits, etc. We want to switch from 100 processes with 1 thread to one process with 100 threads, each executing the work that, previously, one script was doing. But changing how the scripts are invoked by the monitoring tool is not possible. We need to keep invocation the same (launch a process with different command-line parameters) but but change the scripts to recognize that another one is active, and have the "new" script send its work instructions (from the command line params) over to the "old" script. BTW, this is not something I want to do on a one-script basis. Instead, I want to package this behavior into a library which many script authors can leverage-- my goal is to enable script authors to write simple, single-threaded scripts which are unaware of multi-instance issues, and to handle the multi-threading and single-instancing under the covers.
2010/05/29
[ "https://Stackoverflow.com/questions/2935836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126352/" ]
The Alex Martelli approach of setting up a communications channel is the appropriate one. I would use a multiprocessing.connection.Listener to create a listener, in your choice. Documentation at: <http://docs.python.org/library/multiprocessing.html#multiprocessing-listeners-clients> Rather than using AF\_INET (sockets) you may elect to use AF\_UNIX for Linux and AF\_PIPE for Windows. Hopefully a small "if" wouldn't hurt. **Edit**: I guess an example wouldn't hurt. It is a basic one, though. ``` #!/usr/bin/env python from multiprocessing.connection import Listener, Client import socket from array import array from sys import argv def myloop(address): try: listener = Listener(*address) conn = listener.accept() serve(conn) except socket.error, e: conn = Client(*address) conn.send('this is a client') conn.send('close') def serve(conn): while True: msg = conn.recv() if msg.upper() == 'CLOSE': break print msg conn.close() if __name__ == '__main__': address = ('/tmp/testipc', 'AF_UNIX') myloop(address) ``` This works on OS X, so it needs testing with both Linux and (after substituting the right address) Windows. A lot of caveats exists from a security point, the main one being that conn.recv unpickles its data, so you are almost always better of with recv\_bytes.
Perhaps try using sockets for communication?
2,935,836
I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable the following behavior: 1. "`foo.py`" is launched from the command line, and it will stay running for a long time-- days or weeks until the machine is rebooted or the parent process kills it. 2. every few minutes the same script is launched again, but with different command-line parameters 3. when launched, the script should see if any other instances are running. 4. if other instances are running, then instance #2 should send its command-line parameters to instance #1, and then instance #2 should exit. 5. instance #1, if it receives command-line parameters from another script, should spin up a new thread and (using the command-line parameters sent in the step above) start performing the work that instance #2 was going to perform. So I'm looking for two things: how can a python program know another instance of itself is running, and then how can one python command-line program communicate with another? Making this more complicated, the same script needs to run on both Windows and Linux, so ideally the solution would use only the Python standard library and not any OS-specific calls. Although if I need to have a Windows codepath and an \*nix codepath (and a big `if` statement in my code to choose one or the other), that's OK if a "same code" solution isn't possible. I realize I could probably work out a file-based approach (e.g. instance #1 watches a directory for changes and each instance drops a file into that directory when it wants to do work) but I'm a little concerned about cleaning up those files after a non-graceful machine shutdown. I'd ideally be able to use an in-memory solution. But again I'm flexible, if a persistent-file-based approach is the only way to do it, I'm open to that option. More details: I'm trying to do this because our servers are using a monitoring tool which supports running python scripts to collect monitoring data (e.g. results of a database query or web service call) which the monitoring tool then indexes for later use. Some of these scripts are very expensive to start up but cheap to run after startup (e.g. making a DB connection vs. running a query). So we've chosen to keep them running in an infinite loop until the parent process kills them. This works great, but on larger servers 100 instances of the same script may be running, even if they're only gathering data every 20 minutes each. This wreaks havoc with RAM, DB connection limits, etc. We want to switch from 100 processes with 1 thread to one process with 100 threads, each executing the work that, previously, one script was doing. But changing how the scripts are invoked by the monitoring tool is not possible. We need to keep invocation the same (launch a process with different command-line parameters) but but change the scripts to recognize that another one is active, and have the "new" script send its work instructions (from the command line params) over to the "old" script. BTW, this is not something I want to do on a one-script basis. Instead, I want to package this behavior into a library which many script authors can leverage-- my goal is to enable script authors to write simple, single-threaded scripts which are unaware of multi-instance issues, and to handle the multi-threading and single-instancing under the covers.
2010/05/29
[ "https://Stackoverflow.com/questions/2935836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126352/" ]
The general approach is to have the script, on startup, set up a communication channel in a way that's guaranteed to be exclusive (other attempts to set up the same channel fail in a predictable way) so that further instances of the script can detect the first one's running *and* talk to it. Your requirements for cross-platform functionality strongly point towards using a socket as the communication channel in question: you can designate a "well known port" that's reserved for your script, say 12345, and open a socket on that port listening to localhost only (127.0.0.1). If the attempt to open that socket fails, because the port in question is "taken", then you can connect to that port number instead, and that will let you communicate with the existing script. If you're not familiar with socket programming, there's a good `HOWTO` doc [here](http://www.amk.ca/python/howto/sockets/). You can also look at the relevant chapter in [Python in a Nutshell](http://books.google.com/books?id=vpTAq4dnmuAC&pg=PA521&lpg=PA521&dq=python+socket+nutshell&source=bl&ots=AORax1F8wx&sig=qtSZR6r9vy9BWTW06PEIyvG_yUs&hl=en&ei=SkcBTKL3LKT4Mpbb4Ts&sa=X&oi=book_result&ct=result&resnum=5&ved=0CDEQ6AEwBA#v=onepage&q&f=false) (I'm biased about that one, of course;-).
Sounds like your best bet is sticking with a pid file but have it not only contain the process Id - have it also include the port number that the prior instance is listening on. So when starting up check for the pid file and if present see if a process with that Id is running - if so send your data to it and quit otherwise overwrite the pid file with the current process's info.
2,935,836
I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable the following behavior: 1. "`foo.py`" is launched from the command line, and it will stay running for a long time-- days or weeks until the machine is rebooted or the parent process kills it. 2. every few minutes the same script is launched again, but with different command-line parameters 3. when launched, the script should see if any other instances are running. 4. if other instances are running, then instance #2 should send its command-line parameters to instance #1, and then instance #2 should exit. 5. instance #1, if it receives command-line parameters from another script, should spin up a new thread and (using the command-line parameters sent in the step above) start performing the work that instance #2 was going to perform. So I'm looking for two things: how can a python program know another instance of itself is running, and then how can one python command-line program communicate with another? Making this more complicated, the same script needs to run on both Windows and Linux, so ideally the solution would use only the Python standard library and not any OS-specific calls. Although if I need to have a Windows codepath and an \*nix codepath (and a big `if` statement in my code to choose one or the other), that's OK if a "same code" solution isn't possible. I realize I could probably work out a file-based approach (e.g. instance #1 watches a directory for changes and each instance drops a file into that directory when it wants to do work) but I'm a little concerned about cleaning up those files after a non-graceful machine shutdown. I'd ideally be able to use an in-memory solution. But again I'm flexible, if a persistent-file-based approach is the only way to do it, I'm open to that option. More details: I'm trying to do this because our servers are using a monitoring tool which supports running python scripts to collect monitoring data (e.g. results of a database query or web service call) which the monitoring tool then indexes for later use. Some of these scripts are very expensive to start up but cheap to run after startup (e.g. making a DB connection vs. running a query). So we've chosen to keep them running in an infinite loop until the parent process kills them. This works great, but on larger servers 100 instances of the same script may be running, even if they're only gathering data every 20 minutes each. This wreaks havoc with RAM, DB connection limits, etc. We want to switch from 100 processes with 1 thread to one process with 100 threads, each executing the work that, previously, one script was doing. But changing how the scripts are invoked by the monitoring tool is not possible. We need to keep invocation the same (launch a process with different command-line parameters) but but change the scripts to recognize that another one is active, and have the "new" script send its work instructions (from the command line params) over to the "old" script. BTW, this is not something I want to do on a one-script basis. Instead, I want to package this behavior into a library which many script authors can leverage-- my goal is to enable script authors to write simple, single-threaded scripts which are unaware of multi-instance issues, and to handle the multi-threading and single-instancing under the covers.
2010/05/29
[ "https://Stackoverflow.com/questions/2935836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126352/" ]
The Alex Martelli approach of setting up a communications channel is the appropriate one. I would use a multiprocessing.connection.Listener to create a listener, in your choice. Documentation at: <http://docs.python.org/library/multiprocessing.html#multiprocessing-listeners-clients> Rather than using AF\_INET (sockets) you may elect to use AF\_UNIX for Linux and AF\_PIPE for Windows. Hopefully a small "if" wouldn't hurt. **Edit**: I guess an example wouldn't hurt. It is a basic one, though. ``` #!/usr/bin/env python from multiprocessing.connection import Listener, Client import socket from array import array from sys import argv def myloop(address): try: listener = Listener(*address) conn = listener.accept() serve(conn) except socket.error, e: conn = Client(*address) conn.send('this is a client') conn.send('close') def serve(conn): while True: msg = conn.recv() if msg.upper() == 'CLOSE': break print msg conn.close() if __name__ == '__main__': address = ('/tmp/testipc', 'AF_UNIX') myloop(address) ``` This works on OS X, so it needs testing with both Linux and (after substituting the right address) Windows. A lot of caveats exists from a security point, the main one being that conn.recv unpickles its data, so you are almost always better of with recv\_bytes.
The general approach is to have the script, on startup, set up a communication channel in a way that's guaranteed to be exclusive (other attempts to set up the same channel fail in a predictable way) so that further instances of the script can detect the first one's running *and* talk to it. Your requirements for cross-platform functionality strongly point towards using a socket as the communication channel in question: you can designate a "well known port" that's reserved for your script, say 12345, and open a socket on that port listening to localhost only (127.0.0.1). If the attempt to open that socket fails, because the port in question is "taken", then you can connect to that port number instead, and that will let you communicate with the existing script. If you're not familiar with socket programming, there's a good `HOWTO` doc [here](http://www.amk.ca/python/howto/sockets/). You can also look at the relevant chapter in [Python in a Nutshell](http://books.google.com/books?id=vpTAq4dnmuAC&pg=PA521&lpg=PA521&dq=python+socket+nutshell&source=bl&ots=AORax1F8wx&sig=qtSZR6r9vy9BWTW06PEIyvG_yUs&hl=en&ei=SkcBTKL3LKT4Mpbb4Ts&sa=X&oi=book_result&ct=result&resnum=5&ved=0CDEQ6AEwBA#v=onepage&q&f=false) (I'm biased about that one, of course;-).
2,935,836
I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable the following behavior: 1. "`foo.py`" is launched from the command line, and it will stay running for a long time-- days or weeks until the machine is rebooted or the parent process kills it. 2. every few minutes the same script is launched again, but with different command-line parameters 3. when launched, the script should see if any other instances are running. 4. if other instances are running, then instance #2 should send its command-line parameters to instance #1, and then instance #2 should exit. 5. instance #1, if it receives command-line parameters from another script, should spin up a new thread and (using the command-line parameters sent in the step above) start performing the work that instance #2 was going to perform. So I'm looking for two things: how can a python program know another instance of itself is running, and then how can one python command-line program communicate with another? Making this more complicated, the same script needs to run on both Windows and Linux, so ideally the solution would use only the Python standard library and not any OS-specific calls. Although if I need to have a Windows codepath and an \*nix codepath (and a big `if` statement in my code to choose one or the other), that's OK if a "same code" solution isn't possible. I realize I could probably work out a file-based approach (e.g. instance #1 watches a directory for changes and each instance drops a file into that directory when it wants to do work) but I'm a little concerned about cleaning up those files after a non-graceful machine shutdown. I'd ideally be able to use an in-memory solution. But again I'm flexible, if a persistent-file-based approach is the only way to do it, I'm open to that option. More details: I'm trying to do this because our servers are using a monitoring tool which supports running python scripts to collect monitoring data (e.g. results of a database query or web service call) which the monitoring tool then indexes for later use. Some of these scripts are very expensive to start up but cheap to run after startup (e.g. making a DB connection vs. running a query). So we've chosen to keep them running in an infinite loop until the parent process kills them. This works great, but on larger servers 100 instances of the same script may be running, even if they're only gathering data every 20 minutes each. This wreaks havoc with RAM, DB connection limits, etc. We want to switch from 100 processes with 1 thread to one process with 100 threads, each executing the work that, previously, one script was doing. But changing how the scripts are invoked by the monitoring tool is not possible. We need to keep invocation the same (launch a process with different command-line parameters) but but change the scripts to recognize that another one is active, and have the "new" script send its work instructions (from the command line params) over to the "old" script. BTW, this is not something I want to do on a one-script basis. Instead, I want to package this behavior into a library which many script authors can leverage-- my goal is to enable script authors to write simple, single-threaded scripts which are unaware of multi-instance issues, and to handle the multi-threading and single-instancing under the covers.
2010/05/29
[ "https://Stackoverflow.com/questions/2935836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126352/" ]
The Alex Martelli approach of setting up a communications channel is the appropriate one. I would use a multiprocessing.connection.Listener to create a listener, in your choice. Documentation at: <http://docs.python.org/library/multiprocessing.html#multiprocessing-listeners-clients> Rather than using AF\_INET (sockets) you may elect to use AF\_UNIX for Linux and AF\_PIPE for Windows. Hopefully a small "if" wouldn't hurt. **Edit**: I guess an example wouldn't hurt. It is a basic one, though. ``` #!/usr/bin/env python from multiprocessing.connection import Listener, Client import socket from array import array from sys import argv def myloop(address): try: listener = Listener(*address) conn = listener.accept() serve(conn) except socket.error, e: conn = Client(*address) conn.send('this is a client') conn.send('close') def serve(conn): while True: msg = conn.recv() if msg.upper() == 'CLOSE': break print msg conn.close() if __name__ == '__main__': address = ('/tmp/testipc', 'AF_UNIX') myloop(address) ``` This works on OS X, so it needs testing with both Linux and (after substituting the right address) Windows. A lot of caveats exists from a security point, the main one being that conn.recv unpickles its data, so you are almost always better of with recv\_bytes.
Sounds like your best bet is sticking with a pid file but have it not only contain the process Id - have it also include the port number that the prior instance is listening on. So when starting up check for the pid file and if present see if a process with that Id is running - if so send your data to it and quit otherwise overwrite the pid file with the current process's info.
26,378,538
I am using Ubuntu 14.04 with Python version 2.7.6. I recently installed Python version 3.4.2 side-by-side with the system Python using `pyenv`. Now I would like to test out some debuggers for Python 3, and I downloaded `trepan-0.2.8-py3.3.egg` from the [python3-trepan project page](https://code.google.com/p/python3-trepan/). Then I ran `pyenv global 3.4.2` and `easy_install trepan-0.2.8-py3.3.egg`, which gave me the following error: ``` Traceback (most recent call last): File "/home/hakon/.pyenv/versions/3.4.2/bin/easy_install", line 11, in <module> sys.exit(main()) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 1909, in main with_ei_usage(lambda: File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 1896, in with_ei_usage return f() File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 1913, in <lambda> distclass=DistributionWithoutHelpCommands, **kw File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/distutils/core.py", line 148, in setup dist.run_commands() File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/distutils/dist.py", line 955, in run_commands self.run_command(cmd) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 358, in run self.easy_install(spec, not self.no_deps) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 574, in easy_install return self.install_item(None, spec, tmpdir, deps, True) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 625, in install_item self.process_distribution(spec, dist, deps) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 671, in process_distribution [requirement], self.local_index, self.easy_install File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/pkg_resources.py", line 564, in resolve dist = best[req.key] = env.best_match(req, self, installer) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/pkg_resources.py", line 802, in best_match return self.obtain(req, installer) # try and download/install File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/pkg_resources.py", line 814, in obtain return installer(requirement) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 593, in easy_install return self.install_item(spec, dist.location, tmpdir, deps) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 623, in install_item dists = self.install_eggs(spec, download, tmpdir) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 809, in install_eggs return self.build_and_install(setup_script, setup_base) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 1015, in build_and_install self.run_setup(setup_script, setup_base, args) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 1000, in run_setup run_setup(setup_script, args) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/sandbox.py", line 50, in run_setup lambda: execfile( File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/sandbox.py", line 100, in run return func() File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/sandbox.py", line 52, in <lambda> {'__file__':setup_script, '__name__':'__main__'} File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/compat.py", line 78, in execfile exec(compile(source, fn, 'exec'), globs, locs) File "setup.py", line 12, in <module> ImportError: No module named '__pkginfo__' ``` **Update:** The problem seems not to be related to installing Python 3 using `pyenv`: I tried the following: * disabled `pyenv` * `sudo apt-get install python3 python` * `sudo apt-get install python3-setuptools` * `sudo easy_install-3.4 trepan-0.2.8-py3.3.egg` This gave me the same error: ``` Traceback (most recent call last): File "/usr/bin/easy_install-3.4", line 9, in <module> load_entry_point('setuptools==3.3', 'console_scripts', 'easy_install-3.4')() File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 1963, in main with_ei_usage(lambda: File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 1950, in with_ei_usage return f() File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 1967, in <lambda> distclass=DistributionWithoutHelpCommands, **kw File "/usr/lib/python3.4/distutils/core.py", line 148, in setup dist.run_commands() File "/usr/lib/python3.4/distutils/dist.py", line 955, in run_commands self.run_command(cmd) File "/usr/lib/python3.4/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 381, in run self.easy_install(spec, not self.no_deps) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 597, in easy_install return self.install_item(None, spec, tmpdir, deps, True) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 648, in install_item self.process_distribution(spec, dist, deps) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 694, in process_distribution [requirement], self.local_index, self.easy_install File "/usr/lib/python3/dist-packages/pkg_resources.py", line 620, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "/usr/lib/python3/dist-packages/pkg_resources.py", line 858, in best_match return self.obtain(req, installer) # try and download/install File "/usr/lib/python3/dist-packages/pkg_resources.py", line 870, in obtain return installer(requirement) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 616, in easy_install return self.install_item(spec, dist.location, tmpdir, deps) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 646, in install_item dists = self.install_eggs(spec, download, tmpdir) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 834, in install_eggs return self.build_and_install(setup_script, setup_base) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 1040, in build_and_install self.run_setup(setup_script, setup_base, args) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 1025, in run_setup run_setup(setup_script, args) File "/usr/lib/python3/dist-packages/setuptools/sandbox.py", line 50, in run_setup lambda: execfile( File "/usr/lib/python3/dist-packages/setuptools/sandbox.py", line 100, in run return func() File "/usr/lib/python3/dist-packages/setuptools/sandbox.py", line 52, in <lambda> {'__file__':setup_script, '__name__':'__main__'} File "/usr/lib/python3/dist-packages/setuptools/compat.py", line 78, in execfile exec(compile(source, fn, 'exec'), globs, locs) File "setup.py", line 12, in <module> ImportError: No module named '__pkginfo__' ```
2014/10/15
[ "https://Stackoverflow.com/questions/26378538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2173773/" ]
I haven't tested it, but the maintainer @rocky recommends this to install: ``` pip3 install trepan3k ``` **OLD**: Install using this command: ``` pip3 install -e git+https://github.com/rocky/python3-trepan/#egg=trepan ``` I think the current tarball/eggs are broken
You might take a look at <https://askubuntu.com/questions/95037/what-is-the-best-way-to-install-python-packages> or <https://askubuntu.com/questions/350437/installing-python-modules-on-ubuntu> or [Installing python modules on Ubuntu](https://stackoverflow.com/questions/19034959/installing-python-modules-on-ubuntu) This just might solve the problem. Hope it helps.
26,378,538
I am using Ubuntu 14.04 with Python version 2.7.6. I recently installed Python version 3.4.2 side-by-side with the system Python using `pyenv`. Now I would like to test out some debuggers for Python 3, and I downloaded `trepan-0.2.8-py3.3.egg` from the [python3-trepan project page](https://code.google.com/p/python3-trepan/). Then I ran `pyenv global 3.4.2` and `easy_install trepan-0.2.8-py3.3.egg`, which gave me the following error: ``` Traceback (most recent call last): File "/home/hakon/.pyenv/versions/3.4.2/bin/easy_install", line 11, in <module> sys.exit(main()) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 1909, in main with_ei_usage(lambda: File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 1896, in with_ei_usage return f() File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 1913, in <lambda> distclass=DistributionWithoutHelpCommands, **kw File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/distutils/core.py", line 148, in setup dist.run_commands() File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/distutils/dist.py", line 955, in run_commands self.run_command(cmd) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 358, in run self.easy_install(spec, not self.no_deps) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 574, in easy_install return self.install_item(None, spec, tmpdir, deps, True) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 625, in install_item self.process_distribution(spec, dist, deps) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 671, in process_distribution [requirement], self.local_index, self.easy_install File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/pkg_resources.py", line 564, in resolve dist = best[req.key] = env.best_match(req, self, installer) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/pkg_resources.py", line 802, in best_match return self.obtain(req, installer) # try and download/install File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/pkg_resources.py", line 814, in obtain return installer(requirement) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 593, in easy_install return self.install_item(spec, dist.location, tmpdir, deps) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 623, in install_item dists = self.install_eggs(spec, download, tmpdir) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 809, in install_eggs return self.build_and_install(setup_script, setup_base) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 1015, in build_and_install self.run_setup(setup_script, setup_base, args) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 1000, in run_setup run_setup(setup_script, args) File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/sandbox.py", line 50, in run_setup lambda: execfile( File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/sandbox.py", line 100, in run return func() File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/sandbox.py", line 52, in <lambda> {'__file__':setup_script, '__name__':'__main__'} File "/home/hakon/.pyenv/versions/3.4.2/lib/python3.4/site-packages/setuptools/compat.py", line 78, in execfile exec(compile(source, fn, 'exec'), globs, locs) File "setup.py", line 12, in <module> ImportError: No module named '__pkginfo__' ``` **Update:** The problem seems not to be related to installing Python 3 using `pyenv`: I tried the following: * disabled `pyenv` * `sudo apt-get install python3 python` * `sudo apt-get install python3-setuptools` * `sudo easy_install-3.4 trepan-0.2.8-py3.3.egg` This gave me the same error: ``` Traceback (most recent call last): File "/usr/bin/easy_install-3.4", line 9, in <module> load_entry_point('setuptools==3.3', 'console_scripts', 'easy_install-3.4')() File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 1963, in main with_ei_usage(lambda: File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 1950, in with_ei_usage return f() File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 1967, in <lambda> distclass=DistributionWithoutHelpCommands, **kw File "/usr/lib/python3.4/distutils/core.py", line 148, in setup dist.run_commands() File "/usr/lib/python3.4/distutils/dist.py", line 955, in run_commands self.run_command(cmd) File "/usr/lib/python3.4/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 381, in run self.easy_install(spec, not self.no_deps) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 597, in easy_install return self.install_item(None, spec, tmpdir, deps, True) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 648, in install_item self.process_distribution(spec, dist, deps) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 694, in process_distribution [requirement], self.local_index, self.easy_install File "/usr/lib/python3/dist-packages/pkg_resources.py", line 620, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "/usr/lib/python3/dist-packages/pkg_resources.py", line 858, in best_match return self.obtain(req, installer) # try and download/install File "/usr/lib/python3/dist-packages/pkg_resources.py", line 870, in obtain return installer(requirement) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 616, in easy_install return self.install_item(spec, dist.location, tmpdir, deps) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 646, in install_item dists = self.install_eggs(spec, download, tmpdir) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 834, in install_eggs return self.build_and_install(setup_script, setup_base) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 1040, in build_and_install self.run_setup(setup_script, setup_base, args) File "/usr/lib/python3/dist-packages/setuptools/command/easy_install.py", line 1025, in run_setup run_setup(setup_script, args) File "/usr/lib/python3/dist-packages/setuptools/sandbox.py", line 50, in run_setup lambda: execfile( File "/usr/lib/python3/dist-packages/setuptools/sandbox.py", line 100, in run return func() File "/usr/lib/python3/dist-packages/setuptools/sandbox.py", line 52, in <lambda> {'__file__':setup_script, '__name__':'__main__'} File "/usr/lib/python3/dist-packages/setuptools/compat.py", line 78, in execfile exec(compile(source, fn, 'exec'), globs, locs) File "setup.py", line 12, in <module> ImportError: No module named '__pkginfo__' ```
2014/10/15
[ "https://Stackoverflow.com/questions/26378538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2173773/" ]
Starting with trepan 0.4.2 (at this writing we are at 0.4.7), the pip problems were addressed. However... You are using pyenv but note that on Ubuntu 14.04 without that, you may need to use *pip3* instead of *pip*. Outside of pyenv I think defaults *pip* to Python2's *pip*. See also [this link](http://this%20link). And alas, there is another weirdness. When a wheel is not available (as was the case before version 0.4.7), pip uses the source tarball to install from rather than an egg. However the source code for Python 2 versus Python 3 is necessarily different and it would be too difficult to try to combine these into one source. So, I have started to put wheel format file on pypi.org and I hope this too will address problems like this in the future.
You might take a look at <https://askubuntu.com/questions/95037/what-is-the-best-way-to-install-python-packages> or <https://askubuntu.com/questions/350437/installing-python-modules-on-ubuntu> or [Installing python modules on Ubuntu](https://stackoverflow.com/questions/19034959/installing-python-modules-on-ubuntu) This just might solve the problem. Hope it helps.
68,634,422
I'm having trouble understanding how the recursive merge sort algorithm works, I understand how it theoretically works : if there's more than one element in an array find its middle and divide the array into 2 smaller sub-arrays and so on until you have 2 arrays of 1 element that are by definition already sorted (base case) then you can merge them using a merging algorithm, then you go up the tree and so on. I've tried to implement it in python with some print statements to follow step by step and it works but I don't really understand why it works the way it does. I'll describe you my wrong logic: the algorithm in pseudo code with l being the low index and h the high index : ``` merge_sort(l,h){ if(l < h){ mid = (l+h)//2 merge_sort(l,mid) merge_sort(mid+1,h) merge(l,mid,h) } } ``` so for a an arr = [9,3,7,5] * We call merge\_sort(0,3) which is the full array, l=0 , h =3, mid = 1 [9,3,7,5] * l < h so it calls merge\_sort(0,1), l=0,h=1 , mid=0 [9,3] * l < h so it calls merge\_sort(0,0) l=0 h=0 mid =0 [9] **from here l == h so we don't fulfill the condition l < h and thus merge\_sort doesn't call itself again, for me the algorithm ends here** ( which is obviously wrong ) BUT here it goes upand calls merge\_sort(1,1) [3] (right side of the array) then merge is executed. After that it goes up again and tackles the right side of the initial array merge\_sort(2,3) [7,5] and continues. ( [7] then [5] then merging ) Can someone please explain me why the algorithms continues to call himself after l == n ? I've read some explanations and watch some videos and some even argues merge(l,mid) sort the full first half [9,3] and merge(mid+1,h) sort the second full half [7,5] which is apparently not how it's working, I'm really confused.
2021/08/03
[ "https://Stackoverflow.com/questions/68634422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13229018/" ]
It doesn't call itself again, it returns back to it's previous step in recursion, once it finishes the current one. Here is an example from GeeksForGeeks of a merge sort algorithm, with each step labeled numerically in a sequential order: ![merge sort algorithm, with each step labeled numerically in a sequential order](https://i.stack.imgur.com/EbD53.png)
You can understand a recursive algorithm by *trusting* it. Have a look at the annotation below (`!` starts a comment): ``` merge_sort(l,h) { if (l < h) { mid = (l+h)//2 merge_sort(l,mid) ! If merge_sort does its job, the array is now sorted from l to mid merge_sort(mid+1,h) ! If merge_sort does its job, the array is now sorted from mid+1 to h merge(l,mid,h) ! If merge does its job, the array is now sorted from l to h } else { ! If l==h, the array is already sorted from l to h } ``` Now you can see that if we call the function with some values of `l` and `h`, it will return a sorted array, by calling itself on parts of the array, each time returning them sorted. The whole construction works because the size of the subarrays goes decreasing across the levels of calls, and always reaches 1, causing an immediate return to the calling level.
5,517,582
I am about to get a bunch of python scripts from an untrusted source. I'd like to be sure that no part of the code can hurt my system, meaning: `(1) the code is not allowed to import ANY MODULE` `(2) the code is not allowed to read or write any data, connect to the network etc` (the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value) before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system. I thought of using the following approach: `check that the word 'import' is not used (so we are guaranteed that no modules are imported)` yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using `open`). Then here comes the question: (1) where can I get a 'global' list of python methods (like `open`)? (2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword `open` would lead to an exception)? I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs. **EDIT:** suppose that I make sure that no `import` is in the file, and that no possible hurtful methods (such as `open`, `eval`, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
2011/04/01
[ "https://Stackoverflow.com/questions/5517582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
An approach that should work better than string matching us to use [module ast](http://docs.python.org/library/ast.html), parse the python code, do your whitelist filtering on the tree (e.g. allow only basic operations), then compile and run the tree. See [this nice example](http://www.dalkescientific.com/writings/diary/archive/2010/02/22/instrumenting_the_ast.html) by Andrew Dalke on manipulating ASTs.
Without a sandboxed environment, it is impossible to prevent a Python file from doing harm to your system aside from *not running it*. It is easy to create a Cryptominer, delete/encrypt/overwrite files, run shell commands, and do general harm to your system. If you are on Linux, you should be able to use docker to sandbox your code. For more information, see this GitHub issue: <https://github.com/raxod502/python-in-a-box/issues/2>. I did come across [this](https://github.com/donno2048/restricted-functions) on GitHub, so something like it could be used, but that has a lot of limits. Another approach would be to create another Python file which parses the original one, removes the bad code, and runs the file. However, that would still be hit-and-miss.
5,517,582
I am about to get a bunch of python scripts from an untrusted source. I'd like to be sure that no part of the code can hurt my system, meaning: `(1) the code is not allowed to import ANY MODULE` `(2) the code is not allowed to read or write any data, connect to the network etc` (the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value) before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system. I thought of using the following approach: `check that the word 'import' is not used (so we are guaranteed that no modules are imported)` yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using `open`). Then here comes the question: (1) where can I get a 'global' list of python methods (like `open`)? (2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword `open` would lead to an exception)? I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs. **EDIT:** suppose that I make sure that no `import` is in the file, and that no possible hurtful methods (such as `open`, `eval`, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
2011/04/01
[ "https://Stackoverflow.com/questions/5517582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
You can still obfuscate `import` without using `eval`: ``` s = '__imp' s += 'ort__' f = globals()['__builtins__'].__dict__[s] ** BOOM ** ```
built in functions/keywords: * eval * exec * `__import__` * open * file * input * execfile * print can be dangerous if you have one of those dumb shells that execute code on seeing certain output * stdin * `__builtins__` * globals() and locals() must be blocked otherwise they can be used to bypass your rules There's probably tons of others that I didn't think about. Unfortunately, crap like this is possible... `object().__reduce__()[0].__globals__["__builtins__"]["eval"]("open('/tmp/l0l0l0l0l0l0l','w').write('pwnd')")` So it turns out keywords, import restrictions, and in-scope by default symbols alone are not enough to cover, you need to verify the entire graph...
5,517,582
I am about to get a bunch of python scripts from an untrusted source. I'd like to be sure that no part of the code can hurt my system, meaning: `(1) the code is not allowed to import ANY MODULE` `(2) the code is not allowed to read or write any data, connect to the network etc` (the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value) before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system. I thought of using the following approach: `check that the word 'import' is not used (so we are guaranteed that no modules are imported)` yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using `open`). Then here comes the question: (1) where can I get a 'global' list of python methods (like `open`)? (2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword `open` would lead to an exception)? I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs. **EDIT:** suppose that I make sure that no `import` is in the file, and that no possible hurtful methods (such as `open`, `eval`, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
2011/04/01
[ "https://Stackoverflow.com/questions/5517582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
This point hasn't been made yet, and should be: > > **You are not going to be able to secure arbitrary Python code.** > > > A VM is the way to go unless you want security issues up the wazoo.
An approach that should work better than string matching us to use [module ast](http://docs.python.org/library/ast.html), parse the python code, do your whitelist filtering on the tree (e.g. allow only basic operations), then compile and run the tree. See [this nice example](http://www.dalkescientific.com/writings/diary/archive/2010/02/22/instrumenting_the_ast.html) by Andrew Dalke on manipulating ASTs.
5,517,582
I am about to get a bunch of python scripts from an untrusted source. I'd like to be sure that no part of the code can hurt my system, meaning: `(1) the code is not allowed to import ANY MODULE` `(2) the code is not allowed to read or write any data, connect to the network etc` (the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value) before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system. I thought of using the following approach: `check that the word 'import' is not used (so we are guaranteed that no modules are imported)` yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using `open`). Then here comes the question: (1) where can I get a 'global' list of python methods (like `open`)? (2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword `open` would lead to an exception)? I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs. **EDIT:** suppose that I make sure that no `import` is in the file, and that no possible hurtful methods (such as `open`, `eval`, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
2011/04/01
[ "https://Stackoverflow.com/questions/5517582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
built in functions/keywords: * eval * exec * `__import__` * open * file * input * execfile * print can be dangerous if you have one of those dumb shells that execute code on seeing certain output * stdin * `__builtins__` * globals() and locals() must be blocked otherwise they can be used to bypass your rules There's probably tons of others that I didn't think about. Unfortunately, crap like this is possible... `object().__reduce__()[0].__globals__["__builtins__"]["eval"]("open('/tmp/l0l0l0l0l0l0l','w').write('pwnd')")` So it turns out keywords, import restrictions, and in-scope by default symbols alone are not enough to cover, you need to verify the entire graph...
Without a sandboxed environment, it is impossible to prevent a Python file from doing harm to your system aside from *not running it*. It is easy to create a Cryptominer, delete/encrypt/overwrite files, run shell commands, and do general harm to your system. If you are on Linux, you should be able to use docker to sandbox your code. For more information, see this GitHub issue: <https://github.com/raxod502/python-in-a-box/issues/2>. I did come across [this](https://github.com/donno2048/restricted-functions) on GitHub, so something like it could be used, but that has a lot of limits. Another approach would be to create another Python file which parses the original one, removes the bad code, and runs the file. However, that would still be hit-and-miss.
5,517,582
I am about to get a bunch of python scripts from an untrusted source. I'd like to be sure that no part of the code can hurt my system, meaning: `(1) the code is not allowed to import ANY MODULE` `(2) the code is not allowed to read or write any data, connect to the network etc` (the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value) before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system. I thought of using the following approach: `check that the word 'import' is not used (so we are guaranteed that no modules are imported)` yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using `open`). Then here comes the question: (1) where can I get a 'global' list of python methods (like `open`)? (2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword `open` would lead to an exception)? I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs. **EDIT:** suppose that I make sure that no `import` is in the file, and that no possible hurtful methods (such as `open`, `eval`, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
2011/04/01
[ "https://Stackoverflow.com/questions/5517582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
[Built-in functions](http://docs.python.org/library/functions.html#built-in-functions). [Keywords](http://docs.python.org/reference/lexical_analysis.html#keywords). Note that you'll need to do things like look for both "file" and "open", as both can open files. Also, as others have noted, this isn't 100% certain to stop someone determined to insert malacious code.
Use a Virtual Machine instead of running it on a system that you are concerned about.
5,517,582
I am about to get a bunch of python scripts from an untrusted source. I'd like to be sure that no part of the code can hurt my system, meaning: `(1) the code is not allowed to import ANY MODULE` `(2) the code is not allowed to read or write any data, connect to the network etc` (the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value) before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system. I thought of using the following approach: `check that the word 'import' is not used (so we are guaranteed that no modules are imported)` yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using `open`). Then here comes the question: (1) where can I get a 'global' list of python methods (like `open`)? (2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword `open` would lead to an exception)? I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs. **EDIT:** suppose that I make sure that no `import` is in the file, and that no possible hurtful methods (such as `open`, `eval`, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
2011/04/01
[ "https://Stackoverflow.com/questions/5517582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
This point hasn't been made yet, and should be: > > **You are not going to be able to secure arbitrary Python code.** > > > A VM is the way to go unless you want security issues up the wazoo.
[Built-in functions](http://docs.python.org/library/functions.html#built-in-functions). [Keywords](http://docs.python.org/reference/lexical_analysis.html#keywords). Note that you'll need to do things like look for both "file" and "open", as both can open files. Also, as others have noted, this isn't 100% certain to stop someone determined to insert malacious code.
5,517,582
I am about to get a bunch of python scripts from an untrusted source. I'd like to be sure that no part of the code can hurt my system, meaning: `(1) the code is not allowed to import ANY MODULE` `(2) the code is not allowed to read or write any data, connect to the network etc` (the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value) before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system. I thought of using the following approach: `check that the word 'import' is not used (so we are guaranteed that no modules are imported)` yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using `open`). Then here comes the question: (1) where can I get a 'global' list of python methods (like `open`)? (2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword `open` would lead to an exception)? I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs. **EDIT:** suppose that I make sure that no `import` is in the file, and that no possible hurtful methods (such as `open`, `eval`, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
2011/04/01
[ "https://Stackoverflow.com/questions/5517582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
You can still obfuscate `import` without using `eval`: ``` s = '__imp' s += 'ort__' f = globals()['__builtins__'].__dict__[s] ** BOOM ** ```
An approach that should work better than string matching us to use [module ast](http://docs.python.org/library/ast.html), parse the python code, do your whitelist filtering on the tree (e.g. allow only basic operations), then compile and run the tree. See [this nice example](http://www.dalkescientific.com/writings/diary/archive/2010/02/22/instrumenting_the_ast.html) by Andrew Dalke on manipulating ASTs.
5,517,582
I am about to get a bunch of python scripts from an untrusted source. I'd like to be sure that no part of the code can hurt my system, meaning: `(1) the code is not allowed to import ANY MODULE` `(2) the code is not allowed to read or write any data, connect to the network etc` (the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value) before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system. I thought of using the following approach: `check that the word 'import' is not used (so we are guaranteed that no modules are imported)` yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using `open`). Then here comes the question: (1) where can I get a 'global' list of python methods (like `open`)? (2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword `open` would lead to an exception)? I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs. **EDIT:** suppose that I make sure that no `import` is in the file, and that no possible hurtful methods (such as `open`, `eval`, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
2011/04/01
[ "https://Stackoverflow.com/questions/5517582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
[Built-in functions](http://docs.python.org/library/functions.html#built-in-functions). [Keywords](http://docs.python.org/reference/lexical_analysis.html#keywords). Note that you'll need to do things like look for both "file" and "open", as both can open files. Also, as others have noted, this isn't 100% certain to stop someone determined to insert malacious code.
Without a sandboxed environment, it is impossible to prevent a Python file from doing harm to your system aside from *not running it*. It is easy to create a Cryptominer, delete/encrypt/overwrite files, run shell commands, and do general harm to your system. If you are on Linux, you should be able to use docker to sandbox your code. For more information, see this GitHub issue: <https://github.com/raxod502/python-in-a-box/issues/2>. I did come across [this](https://github.com/donno2048/restricted-functions) on GitHub, so something like it could be used, but that has a lot of limits. Another approach would be to create another Python file which parses the original one, removes the bad code, and runs the file. However, that would still be hit-and-miss.
5,517,582
I am about to get a bunch of python scripts from an untrusted source. I'd like to be sure that no part of the code can hurt my system, meaning: `(1) the code is not allowed to import ANY MODULE` `(2) the code is not allowed to read or write any data, connect to the network etc` (the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value) before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system. I thought of using the following approach: `check that the word 'import' is not used (so we are guaranteed that no modules are imported)` yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using `open`). Then here comes the question: (1) where can I get a 'global' list of python methods (like `open`)? (2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword `open` would lead to an exception)? I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs. **EDIT:** suppose that I make sure that no `import` is in the file, and that no possible hurtful methods (such as `open`, `eval`, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
2011/04/01
[ "https://Stackoverflow.com/questions/5517582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
This point hasn't been made yet, and should be: > > **You are not going to be able to secure arbitrary Python code.** > > > A VM is the way to go unless you want security issues up the wazoo.
You can still obfuscate `import` without using `eval`: ``` s = '__imp' s += 'ort__' f = globals()['__builtins__'].__dict__[s] ** BOOM ** ```
5,517,582
I am about to get a bunch of python scripts from an untrusted source. I'd like to be sure that no part of the code can hurt my system, meaning: `(1) the code is not allowed to import ANY MODULE` `(2) the code is not allowed to read or write any data, connect to the network etc` (the purpose of each script is to loop through a list, compute some data from input given to it and return the computed value) before I execute such code, I'd like to have a script 'examine' it and make sure that there's nothing dangerous there that could hurt my system. I thought of using the following approach: `check that the word 'import' is not used (so we are guaranteed that no modules are imported)` yet, it would still be possible for the user (if desired) to write code to read/write files etc (say, using `open`). Then here comes the question: (1) where can I get a 'global' list of python methods (like `open`)? (2) Is there some code that I could add to each script that is sent to me (at the top) that would make some 'global' methods invalid for that script (for example, any use of the keyword `open` would lead to an exception)? I know that there are some solutions of python sandboxing. but please try to answer this question as I feel this is the more relevant approach for my needs. **EDIT:** suppose that I make sure that no `import` is in the file, and that no possible hurtful methods (such as `open`, `eval`, etc) are in it. can I conclude that the file is SAFE? (can you think of any other 'dangerous' ways that built-in methods can be run?)
2011/04/01
[ "https://Stackoverflow.com/questions/5517582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
An approach that should work better than string matching us to use [module ast](http://docs.python.org/library/ast.html), parse the python code, do your whitelist filtering on the tree (e.g. allow only basic operations), then compile and run the tree. See [this nice example](http://www.dalkescientific.com/writings/diary/archive/2010/02/22/instrumenting_the_ast.html) by Andrew Dalke on manipulating ASTs.
Use a Virtual Machine instead of running it on a system that you are concerned about.
13,622,973
Let's say I have a list of the opened files (actually, of the file numbers): ``` import resource import fcntl def get_open_fds(): fds = [] soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) for fd in range(3, soft): try: flags = fcntl.fcntl(fd, fcntl.F_GETFD) except IOError: continue fds.append(fd) return fds ``` Now I would like to get the names of those files. How can I do this? EDIT ---- Just to clarify, for those downvoting this: fd is an integer. It is **NOT** a filedescriptor. Sorry for confusing you with the name, but the code is self-explanatory. EDIT2 ----- I am getting flamed about this, I think because of my choice of `fd` to mean file number. I just checked the [documentation](http://docs.python.org/2/library/fcntl.html): > > All functions in this module take a file descriptor fd as their first > argument. This can be an integer file descriptor, such as returned by > sys.stdin.fileno(), or a file object, such as sys.stdin itself, which > provides a fileno() which returns a genuine file descriptor. > > > So `fd` is indeed an integer. It can also be a file object but, in the general case, `fd` has not `.name`.
2012/11/29
[ "https://Stackoverflow.com/questions/13622973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647991/" ]
As per [this answer](https://stackoverflow.com/a/1189582/989121): ``` for fd in get_open_fds(): print fd, os.readlink('/proc/self/fd/%d' % fd) ```
I was in the same boat. What I ended up doing is writing my own `open` that keeps track of all the files opened. Then in the initial Python file the first thing that happens is the built-in `open` gets replaced by mine, and then later I can query it for the currently open files. This is what it looks like: ``` class Open(object): builtin_open = open _cache = {} @classmethod def __call__(cls, name, *args): file = cls.builtin_open(name, *args) cls._cache[name] = file return file @classmethod def active(cls, name): cls.open_files() try: return cls._cache[name] except KeyError: raise ValueError('%s has been closed' % name) @classmethod def open_files(cls): closed = [] for name, file in cls._cache.items(): if file.closed: closed.append(name) for name in closed: cls._cache.pop(name) return cls._cache.items() import __builtin__ __builtin__.open = Open() ``` then later... ``` daemon.files_preserve = [open.active('/dev/urandom')] ```
14,502,250
This happens when I run python manage.py syncdb. It also happens when I run python manage.py syncdb --mysite.settings. Not sure where to go from here: django isn't recognizing my settings file and I don't know why or how to rectify it. ``` python ../manage.py syncdb Traceback (most recent call last): File "../manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/home/ryan/Programming/OpenCV-2.4.2/msheroku/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line utility.execute() File "/home/ryan/Programming/OpenCV-2.4.2/msheroku/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ryan/Programming/OpenCV-2.4.2/msheroku/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv self.execute(*args, **options.__dict__) File "/home/ryan/Programming/OpenCV-2.4.2/msheroku/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute output = self.handle(*args, **options) File "/home/ryan/Programming/OpenCV-2.4.2/msheroku/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 371, in handle return self.handle_noargs(**options) File "/home/ryan/Programming/OpenCV-2.4.2/msheroku/venv/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 57, in handle_noargs cursor = connection.cursor() File "/home/ryan/Programming/OpenCV-2.4.2/msheroku/venv/local/lib/python2.7/site-packages/django/db/backends/dummy/base.py", line 15, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. ``` From settings.py ``` DATABASES = { 'default': { 'ENGINE': 'postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'xxx', # Or path to database file if using sqlite3. 'USER': 'xxx', # Not used with sqlite3. 'PASSWORD': 'xxx', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } ``` I'm pretty confident that it's not finding the right settings file to begin with.
2013/01/24
[ "https://Stackoverflow.com/questions/14502250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1378184/" ]
Hi I am assuming you are testing your app using heroku and your trying to connect to your local database ? if so be sure to remove this line of code : ``` # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES['default'] = dj_database_url.config() # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ``` Add it in when you are gonna connect to a database on a anther server.
A correct one would look something like this. ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } ``` Edit: changed host to localhost to reflect comments & manage.py Based on how your running your syncdb ``` python manage.py syncdb --mysite.settings ``` Make sure your manage.py file has the correct DJANGO\_SETTINGS\_MODULE specified ``` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") ``` You should then be able to run syncdb without --mysite.settings ``` python manage.py syncdb ```
30,770,658
I am trying to put footer at the bottom with a horizontal line just above the footer. But I am not even able to get footer at the bottom. Tried many posts and blogs but I am missing out on something. I am using the base of some blog to create the signup page. [Fiddle](http://jsfiddle.net/750h2crz/) ### html ``` <div id="header"> </div> <div id="main"> <div id="container"> <form action="index.html" method="post"> <p id="form_title" style='color:#808080'>Create an Account</p> <fieldset> <legend style="color:#585858">Get started with Your Profile</legend> <label for="name" style='color:#808080;font-size:14px'>CUSTOM NAME</label> <input type="text" id="name" name="user_name" style="color:#404040"> <label for="type" style='color:#808080;font-size:14px'>TYPE</label> <select id="sel-type" name="type"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> <label for="type" style='color:#808080;font-size:14px'>REGION</label> <select id="sel-region" name="region"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> </fieldset> <button type="submit">Create Profile</button> </form> </div> </div> <div id="footer"> <a href="About">About</a> <a href="info.com">Instructions</a> <a href="tt.com">Encountered an issue?</a> </div> ``` ### css ``` *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } body { font-family: 'Lato'; background-color: #E8E8E8; } #header { width:100%; background-color: #27272D; height: 50px ; border:1px solid; position:relative; } #main{ border:1px solid; width:100%; height:100%; } #container{ margin-top: 100px; border:1px; } form { max-width: 300px; margin: 10px auto; padding: 10px 20px; border-radius: 3px; background-color: white; border:1px; } #form_title { margin: 10px 0 30px 15px; font-size:20px; } input[type="text"], select { background: rgba(255,255,255,0.1); border: none; font-size: 16px; height: auto; margin: 0; outline: 0; padding: 15px; width: 100%; background-color: #e8eeef; color: #8a97a0; box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset; margin-bottom: 20px; } input[type="text"]{ border-radius: 6px; -moz-border-radius: 6px; -khtml-border-radius: 6px; -webkit-border-radius: 6px; height:44px; font-size: 14px; } select { padding: 6px; height: 44px; border-radius: 2px; } button { color: #FFF; background-color: #13ABAF; font-size: 14px; text-align: center; font-style: normal; border-radius: 5px; width: 96%; height:44px; border: 1px solid; border-width: 1px 1px 3px; margin-bottom: 10px; margin-left: 10px; } fieldset { border: none; } legend { font-size: 17px; margin-bottom: 24px; } label { display: block; margin-bottom: 8px; } label.light { font-weight: 300; display: inline; } #horizontal-line{ display: block; margin-top:100px; margin-bottom: 60px; width:96%; margin-left: auto; margin-right: auto; border-style: inset; border-width: 1px; border-color: #F0F0F0; } #footer { position : absolute; bottom : 0; height:60px; margin-top : 40px; text-align: center ; font-size: 10px ; font-family: 'Lato' ; } @media screen and (min-width: 480px) { form { max-width: 480px; } } ```
2015/06/11
[ "https://Stackoverflow.com/questions/30770658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3089927/" ]
For your css, try ``` #footer { position: relative; ... } ``` Also for the horizontal line just use ``` <hr> ``` html tag above footer (sorry about that, my editing looks awkward because stackoverflow prints out a horizontal line whenever I use that tag) Also its more simple and if you want minimal changes to css. <http://jsfiddle.net/750h2crz/7/>
put this in your css, and use a border instead of a horizontal line. ``` footer { position: absolute; bottom: 0; height: 60px; border-top-width: 5px; border-top-style: solid; border-top-color: #FFF; } ```
30,770,658
I am trying to put footer at the bottom with a horizontal line just above the footer. But I am not even able to get footer at the bottom. Tried many posts and blogs but I am missing out on something. I am using the base of some blog to create the signup page. [Fiddle](http://jsfiddle.net/750h2crz/) ### html ``` <div id="header"> </div> <div id="main"> <div id="container"> <form action="index.html" method="post"> <p id="form_title" style='color:#808080'>Create an Account</p> <fieldset> <legend style="color:#585858">Get started with Your Profile</legend> <label for="name" style='color:#808080;font-size:14px'>CUSTOM NAME</label> <input type="text" id="name" name="user_name" style="color:#404040"> <label for="type" style='color:#808080;font-size:14px'>TYPE</label> <select id="sel-type" name="type"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> <label for="type" style='color:#808080;font-size:14px'>REGION</label> <select id="sel-region" name="region"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> </fieldset> <button type="submit">Create Profile</button> </form> </div> </div> <div id="footer"> <a href="About">About</a> <a href="info.com">Instructions</a> <a href="tt.com">Encountered an issue?</a> </div> ``` ### css ``` *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } body { font-family: 'Lato'; background-color: #E8E8E8; } #header { width:100%; background-color: #27272D; height: 50px ; border:1px solid; position:relative; } #main{ border:1px solid; width:100%; height:100%; } #container{ margin-top: 100px; border:1px; } form { max-width: 300px; margin: 10px auto; padding: 10px 20px; border-radius: 3px; background-color: white; border:1px; } #form_title { margin: 10px 0 30px 15px; font-size:20px; } input[type="text"], select { background: rgba(255,255,255,0.1); border: none; font-size: 16px; height: auto; margin: 0; outline: 0; padding: 15px; width: 100%; background-color: #e8eeef; color: #8a97a0; box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset; margin-bottom: 20px; } input[type="text"]{ border-radius: 6px; -moz-border-radius: 6px; -khtml-border-radius: 6px; -webkit-border-radius: 6px; height:44px; font-size: 14px; } select { padding: 6px; height: 44px; border-radius: 2px; } button { color: #FFF; background-color: #13ABAF; font-size: 14px; text-align: center; font-style: normal; border-radius: 5px; width: 96%; height:44px; border: 1px solid; border-width: 1px 1px 3px; margin-bottom: 10px; margin-left: 10px; } fieldset { border: none; } legend { font-size: 17px; margin-bottom: 24px; } label { display: block; margin-bottom: 8px; } label.light { font-weight: 300; display: inline; } #horizontal-line{ display: block; margin-top:100px; margin-bottom: 60px; width:96%; margin-left: auto; margin-right: auto; border-style: inset; border-width: 1px; border-color: #F0F0F0; } #footer { position : absolute; bottom : 0; height:60px; margin-top : 40px; text-align: center ; font-size: 10px ; font-family: 'Lato' ; } @media screen and (min-width: 480px) { form { max-width: 480px; } } ```
2015/06/11
[ "https://Stackoverflow.com/questions/30770658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3089927/" ]
Remove the `position: absolute` in your style: ``` #footer { position: absolute; /* ... */ } ``` FIDDLE: <https://jsfiddle.net/lmgonzalves/750h2crz/2/>
put this in your css, and use a border instead of a horizontal line. ``` footer { position: absolute; bottom: 0; height: 60px; border-top-width: 5px; border-top-style: solid; border-top-color: #FFF; } ```
30,770,658
I am trying to put footer at the bottom with a horizontal line just above the footer. But I am not even able to get footer at the bottom. Tried many posts and blogs but I am missing out on something. I am using the base of some blog to create the signup page. [Fiddle](http://jsfiddle.net/750h2crz/) ### html ``` <div id="header"> </div> <div id="main"> <div id="container"> <form action="index.html" method="post"> <p id="form_title" style='color:#808080'>Create an Account</p> <fieldset> <legend style="color:#585858">Get started with Your Profile</legend> <label for="name" style='color:#808080;font-size:14px'>CUSTOM NAME</label> <input type="text" id="name" name="user_name" style="color:#404040"> <label for="type" style='color:#808080;font-size:14px'>TYPE</label> <select id="sel-type" name="type"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> <label for="type" style='color:#808080;font-size:14px'>REGION</label> <select id="sel-region" name="region"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> </fieldset> <button type="submit">Create Profile</button> </form> </div> </div> <div id="footer"> <a href="About">About</a> <a href="info.com">Instructions</a> <a href="tt.com">Encountered an issue?</a> </div> ``` ### css ``` *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } body { font-family: 'Lato'; background-color: #E8E8E8; } #header { width:100%; background-color: #27272D; height: 50px ; border:1px solid; position:relative; } #main{ border:1px solid; width:100%; height:100%; } #container{ margin-top: 100px; border:1px; } form { max-width: 300px; margin: 10px auto; padding: 10px 20px; border-radius: 3px; background-color: white; border:1px; } #form_title { margin: 10px 0 30px 15px; font-size:20px; } input[type="text"], select { background: rgba(255,255,255,0.1); border: none; font-size: 16px; height: auto; margin: 0; outline: 0; padding: 15px; width: 100%; background-color: #e8eeef; color: #8a97a0; box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset; margin-bottom: 20px; } input[type="text"]{ border-radius: 6px; -moz-border-radius: 6px; -khtml-border-radius: 6px; -webkit-border-radius: 6px; height:44px; font-size: 14px; } select { padding: 6px; height: 44px; border-radius: 2px; } button { color: #FFF; background-color: #13ABAF; font-size: 14px; text-align: center; font-style: normal; border-radius: 5px; width: 96%; height:44px; border: 1px solid; border-width: 1px 1px 3px; margin-bottom: 10px; margin-left: 10px; } fieldset { border: none; } legend { font-size: 17px; margin-bottom: 24px; } label { display: block; margin-bottom: 8px; } label.light { font-weight: 300; display: inline; } #horizontal-line{ display: block; margin-top:100px; margin-bottom: 60px; width:96%; margin-left: auto; margin-right: auto; border-style: inset; border-width: 1px; border-color: #F0F0F0; } #footer { position : absolute; bottom : 0; height:60px; margin-top : 40px; text-align: center ; font-size: 10px ; font-family: 'Lato' ; } @media screen and (min-width: 480px) { form { max-width: 480px; } } ```
2015/06/11
[ "https://Stackoverflow.com/questions/30770658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3089927/" ]
put this in your css, and use a border instead of a horizontal line. ``` footer { position: absolute; bottom: 0; height: 60px; border-top-width: 5px; border-top-style: solid; border-top-color: #FFF; } ```
updated your css with ``` #footer { position:fixed; width:100%; /* fill the whole width of the screen */ border-top:1px solid #aaa; /* you can change to whatever color you want */ padding-top:10px; /* add some spacing between line and links/text */ background:#fff; /* this is important otherwise your background will be transparent, change the color based on your needs */ /* ... your other properties */ } ``` Also updated you body styling with some padding at the bottom to offset the footer ``` body { /* ... your other properties */ padding-bottom:65px; } ```
30,770,658
I am trying to put footer at the bottom with a horizontal line just above the footer. But I am not even able to get footer at the bottom. Tried many posts and blogs but I am missing out on something. I am using the base of some blog to create the signup page. [Fiddle](http://jsfiddle.net/750h2crz/) ### html ``` <div id="header"> </div> <div id="main"> <div id="container"> <form action="index.html" method="post"> <p id="form_title" style='color:#808080'>Create an Account</p> <fieldset> <legend style="color:#585858">Get started with Your Profile</legend> <label for="name" style='color:#808080;font-size:14px'>CUSTOM NAME</label> <input type="text" id="name" name="user_name" style="color:#404040"> <label for="type" style='color:#808080;font-size:14px'>TYPE</label> <select id="sel-type" name="type"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> <label for="type" style='color:#808080;font-size:14px'>REGION</label> <select id="sel-region" name="region"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> </fieldset> <button type="submit">Create Profile</button> </form> </div> </div> <div id="footer"> <a href="About">About</a> <a href="info.com">Instructions</a> <a href="tt.com">Encountered an issue?</a> </div> ``` ### css ``` *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } body { font-family: 'Lato'; background-color: #E8E8E8; } #header { width:100%; background-color: #27272D; height: 50px ; border:1px solid; position:relative; } #main{ border:1px solid; width:100%; height:100%; } #container{ margin-top: 100px; border:1px; } form { max-width: 300px; margin: 10px auto; padding: 10px 20px; border-radius: 3px; background-color: white; border:1px; } #form_title { margin: 10px 0 30px 15px; font-size:20px; } input[type="text"], select { background: rgba(255,255,255,0.1); border: none; font-size: 16px; height: auto; margin: 0; outline: 0; padding: 15px; width: 100%; background-color: #e8eeef; color: #8a97a0; box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset; margin-bottom: 20px; } input[type="text"]{ border-radius: 6px; -moz-border-radius: 6px; -khtml-border-radius: 6px; -webkit-border-radius: 6px; height:44px; font-size: 14px; } select { padding: 6px; height: 44px; border-radius: 2px; } button { color: #FFF; background-color: #13ABAF; font-size: 14px; text-align: center; font-style: normal; border-radius: 5px; width: 96%; height:44px; border: 1px solid; border-width: 1px 1px 3px; margin-bottom: 10px; margin-left: 10px; } fieldset { border: none; } legend { font-size: 17px; margin-bottom: 24px; } label { display: block; margin-bottom: 8px; } label.light { font-weight: 300; display: inline; } #horizontal-line{ display: block; margin-top:100px; margin-bottom: 60px; width:96%; margin-left: auto; margin-right: auto; border-style: inset; border-width: 1px; border-color: #F0F0F0; } #footer { position : absolute; bottom : 0; height:60px; margin-top : 40px; text-align: center ; font-size: 10px ; font-family: 'Lato' ; } @media screen and (min-width: 480px) { form { max-width: 480px; } } ```
2015/06/11
[ "https://Stackoverflow.com/questions/30770658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3089927/" ]
I would simply use separate tag for footer sec and use Horizontal Rule tag ``` <div id="footer"> <hr> <footer> <a href="About">About</a> <a href="info.com">Instructions</a> <a href="tt.com">Encountered an issue?</a> <footer> </div> ``` Thx
put this in your css, and use a border instead of a horizontal line. ``` footer { position: absolute; bottom: 0; height: 60px; border-top-width: 5px; border-top-style: solid; border-top-color: #FFF; } ```
30,770,658
I am trying to put footer at the bottom with a horizontal line just above the footer. But I am not even able to get footer at the bottom. Tried many posts and blogs but I am missing out on something. I am using the base of some blog to create the signup page. [Fiddle](http://jsfiddle.net/750h2crz/) ### html ``` <div id="header"> </div> <div id="main"> <div id="container"> <form action="index.html" method="post"> <p id="form_title" style='color:#808080'>Create an Account</p> <fieldset> <legend style="color:#585858">Get started with Your Profile</legend> <label for="name" style='color:#808080;font-size:14px'>CUSTOM NAME</label> <input type="text" id="name" name="user_name" style="color:#404040"> <label for="type" style='color:#808080;font-size:14px'>TYPE</label> <select id="sel-type" name="type"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> <label for="type" style='color:#808080;font-size:14px'>REGION</label> <select id="sel-region" name="region"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> </fieldset> <button type="submit">Create Profile</button> </form> </div> </div> <div id="footer"> <a href="About">About</a> <a href="info.com">Instructions</a> <a href="tt.com">Encountered an issue?</a> </div> ``` ### css ``` *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } body { font-family: 'Lato'; background-color: #E8E8E8; } #header { width:100%; background-color: #27272D; height: 50px ; border:1px solid; position:relative; } #main{ border:1px solid; width:100%; height:100%; } #container{ margin-top: 100px; border:1px; } form { max-width: 300px; margin: 10px auto; padding: 10px 20px; border-radius: 3px; background-color: white; border:1px; } #form_title { margin: 10px 0 30px 15px; font-size:20px; } input[type="text"], select { background: rgba(255,255,255,0.1); border: none; font-size: 16px; height: auto; margin: 0; outline: 0; padding: 15px; width: 100%; background-color: #e8eeef; color: #8a97a0; box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset; margin-bottom: 20px; } input[type="text"]{ border-radius: 6px; -moz-border-radius: 6px; -khtml-border-radius: 6px; -webkit-border-radius: 6px; height:44px; font-size: 14px; } select { padding: 6px; height: 44px; border-radius: 2px; } button { color: #FFF; background-color: #13ABAF; font-size: 14px; text-align: center; font-style: normal; border-radius: 5px; width: 96%; height:44px; border: 1px solid; border-width: 1px 1px 3px; margin-bottom: 10px; margin-left: 10px; } fieldset { border: none; } legend { font-size: 17px; margin-bottom: 24px; } label { display: block; margin-bottom: 8px; } label.light { font-weight: 300; display: inline; } #horizontal-line{ display: block; margin-top:100px; margin-bottom: 60px; width:96%; margin-left: auto; margin-right: auto; border-style: inset; border-width: 1px; border-color: #F0F0F0; } #footer { position : absolute; bottom : 0; height:60px; margin-top : 40px; text-align: center ; font-size: 10px ; font-family: 'Lato' ; } @media screen and (min-width: 480px) { form { max-width: 480px; } } ```
2015/06/11
[ "https://Stackoverflow.com/questions/30770658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3089927/" ]
For your css, try ``` #footer { position: relative; ... } ``` Also for the horizontal line just use ``` <hr> ``` html tag above footer (sorry about that, my editing looks awkward because stackoverflow prints out a horizontal line whenever I use that tag) Also its more simple and if you want minimal changes to css. <http://jsfiddle.net/750h2crz/7/>
updated your css with ``` #footer { position:fixed; width:100%; /* fill the whole width of the screen */ border-top:1px solid #aaa; /* you can change to whatever color you want */ padding-top:10px; /* add some spacing between line and links/text */ background:#fff; /* this is important otherwise your background will be transparent, change the color based on your needs */ /* ... your other properties */ } ``` Also updated you body styling with some padding at the bottom to offset the footer ``` body { /* ... your other properties */ padding-bottom:65px; } ```
30,770,658
I am trying to put footer at the bottom with a horizontal line just above the footer. But I am not even able to get footer at the bottom. Tried many posts and blogs but I am missing out on something. I am using the base of some blog to create the signup page. [Fiddle](http://jsfiddle.net/750h2crz/) ### html ``` <div id="header"> </div> <div id="main"> <div id="container"> <form action="index.html" method="post"> <p id="form_title" style='color:#808080'>Create an Account</p> <fieldset> <legend style="color:#585858">Get started with Your Profile</legend> <label for="name" style='color:#808080;font-size:14px'>CUSTOM NAME</label> <input type="text" id="name" name="user_name" style="color:#404040"> <label for="type" style='color:#808080;font-size:14px'>TYPE</label> <select id="sel-type" name="type"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> <label for="type" style='color:#808080;font-size:14px'>REGION</label> <select id="sel-region" name="region"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> </fieldset> <button type="submit">Create Profile</button> </form> </div> </div> <div id="footer"> <a href="About">About</a> <a href="info.com">Instructions</a> <a href="tt.com">Encountered an issue?</a> </div> ``` ### css ``` *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } body { font-family: 'Lato'; background-color: #E8E8E8; } #header { width:100%; background-color: #27272D; height: 50px ; border:1px solid; position:relative; } #main{ border:1px solid; width:100%; height:100%; } #container{ margin-top: 100px; border:1px; } form { max-width: 300px; margin: 10px auto; padding: 10px 20px; border-radius: 3px; background-color: white; border:1px; } #form_title { margin: 10px 0 30px 15px; font-size:20px; } input[type="text"], select { background: rgba(255,255,255,0.1); border: none; font-size: 16px; height: auto; margin: 0; outline: 0; padding: 15px; width: 100%; background-color: #e8eeef; color: #8a97a0; box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset; margin-bottom: 20px; } input[type="text"]{ border-radius: 6px; -moz-border-radius: 6px; -khtml-border-radius: 6px; -webkit-border-radius: 6px; height:44px; font-size: 14px; } select { padding: 6px; height: 44px; border-radius: 2px; } button { color: #FFF; background-color: #13ABAF; font-size: 14px; text-align: center; font-style: normal; border-radius: 5px; width: 96%; height:44px; border: 1px solid; border-width: 1px 1px 3px; margin-bottom: 10px; margin-left: 10px; } fieldset { border: none; } legend { font-size: 17px; margin-bottom: 24px; } label { display: block; margin-bottom: 8px; } label.light { font-weight: 300; display: inline; } #horizontal-line{ display: block; margin-top:100px; margin-bottom: 60px; width:96%; margin-left: auto; margin-right: auto; border-style: inset; border-width: 1px; border-color: #F0F0F0; } #footer { position : absolute; bottom : 0; height:60px; margin-top : 40px; text-align: center ; font-size: 10px ; font-family: 'Lato' ; } @media screen and (min-width: 480px) { form { max-width: 480px; } } ```
2015/06/11
[ "https://Stackoverflow.com/questions/30770658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3089927/" ]
Remove the `position: absolute` in your style: ``` #footer { position: absolute; /* ... */ } ``` FIDDLE: <https://jsfiddle.net/lmgonzalves/750h2crz/2/>
updated your css with ``` #footer { position:fixed; width:100%; /* fill the whole width of the screen */ border-top:1px solid #aaa; /* you can change to whatever color you want */ padding-top:10px; /* add some spacing between line and links/text */ background:#fff; /* this is important otherwise your background will be transparent, change the color based on your needs */ /* ... your other properties */ } ``` Also updated you body styling with some padding at the bottom to offset the footer ``` body { /* ... your other properties */ padding-bottom:65px; } ```
30,770,658
I am trying to put footer at the bottom with a horizontal line just above the footer. But I am not even able to get footer at the bottom. Tried many posts and blogs but I am missing out on something. I am using the base of some blog to create the signup page. [Fiddle](http://jsfiddle.net/750h2crz/) ### html ``` <div id="header"> </div> <div id="main"> <div id="container"> <form action="index.html" method="post"> <p id="form_title" style='color:#808080'>Create an Account</p> <fieldset> <legend style="color:#585858">Get started with Your Profile</legend> <label for="name" style='color:#808080;font-size:14px'>CUSTOM NAME</label> <input type="text" id="name" name="user_name" style="color:#404040"> <label for="type" style='color:#808080;font-size:14px'>TYPE</label> <select id="sel-type" name="type"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> <label for="type" style='color:#808080;font-size:14px'>REGION</label> <select id="sel-region" name="region"> <option value="frontend_developer">Front-End Developer</option> <option value="php_developor">PHP Developer</option> <option value="python_developer">Python Developer</option> <option value="rails_developer"> Rails Developer</option> <option value="web_designer">Web Designer</option> <option value="WordPress_developer">WordPress Developer</option> </select> </fieldset> <button type="submit">Create Profile</button> </form> </div> </div> <div id="footer"> <a href="About">About</a> <a href="info.com">Instructions</a> <a href="tt.com">Encountered an issue?</a> </div> ``` ### css ``` *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } body { font-family: 'Lato'; background-color: #E8E8E8; } #header { width:100%; background-color: #27272D; height: 50px ; border:1px solid; position:relative; } #main{ border:1px solid; width:100%; height:100%; } #container{ margin-top: 100px; border:1px; } form { max-width: 300px; margin: 10px auto; padding: 10px 20px; border-radius: 3px; background-color: white; border:1px; } #form_title { margin: 10px 0 30px 15px; font-size:20px; } input[type="text"], select { background: rgba(255,255,255,0.1); border: none; font-size: 16px; height: auto; margin: 0; outline: 0; padding: 15px; width: 100%; background-color: #e8eeef; color: #8a97a0; box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset; margin-bottom: 20px; } input[type="text"]{ border-radius: 6px; -moz-border-radius: 6px; -khtml-border-radius: 6px; -webkit-border-radius: 6px; height:44px; font-size: 14px; } select { padding: 6px; height: 44px; border-radius: 2px; } button { color: #FFF; background-color: #13ABAF; font-size: 14px; text-align: center; font-style: normal; border-radius: 5px; width: 96%; height:44px; border: 1px solid; border-width: 1px 1px 3px; margin-bottom: 10px; margin-left: 10px; } fieldset { border: none; } legend { font-size: 17px; margin-bottom: 24px; } label { display: block; margin-bottom: 8px; } label.light { font-weight: 300; display: inline; } #horizontal-line{ display: block; margin-top:100px; margin-bottom: 60px; width:96%; margin-left: auto; margin-right: auto; border-style: inset; border-width: 1px; border-color: #F0F0F0; } #footer { position : absolute; bottom : 0; height:60px; margin-top : 40px; text-align: center ; font-size: 10px ; font-family: 'Lato' ; } @media screen and (min-width: 480px) { form { max-width: 480px; } } ```
2015/06/11
[ "https://Stackoverflow.com/questions/30770658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3089927/" ]
I would simply use separate tag for footer sec and use Horizontal Rule tag ``` <div id="footer"> <hr> <footer> <a href="About">About</a> <a href="info.com">Instructions</a> <a href="tt.com">Encountered an issue?</a> <footer> </div> ``` Thx
updated your css with ``` #footer { position:fixed; width:100%; /* fill the whole width of the screen */ border-top:1px solid #aaa; /* you can change to whatever color you want */ padding-top:10px; /* add some spacing between line and links/text */ background:#fff; /* this is important otherwise your background will be transparent, change the color based on your needs */ /* ... your other properties */ } ``` Also updated you body styling with some padding at the bottom to offset the footer ``` body { /* ... your other properties */ padding-bottom:65px; } ```
59,894,720
I am using keras and trying to plot the logs using tensorboard. Bellow you can find out the error I am getting and also the list of packages versions I am using. I can not understand it is giving me the error of 'Sequential' object has no attribute '\_get\_distribution\_strategy'. Package: Keras 2.3.1 Keras-Applications 1.0.8 Keras-Preprocessing 1.1.0 tensorboard 2.1.0 tensorflow 2.1.0 tensorflow-estimator 2.1.0 **MODEL:** ``` model = Sequential() model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_shape=(X.shape[1],))) model.add(GlobalAveragePooling1D()) #model.add(Dense(10, activation='sigmoid')) model.add(Dense(len(CATEGORIES), activation='softmax')) model.summary() #opt = 'adam' # Here we can choose a certain optimizer for our model opt = 'rmsprop' model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy']) # Here we choose the loss function, input our optimizer choice, and set our metrics. # Create a TensorBoard instance with the path to the logs directory tensorboard = TensorBoard(log_dir='logs/{}'.format(time()), histogram_freq = 1, embeddings_freq = 1, embeddings_data = X) history = model.fit(X, Y, epochs=epochs, batch_size=batch_size, validation_split=0.1, callbacks=[tensorboard]) ``` **ERROR:** ``` C:\Users\Bruno\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\callbacks\tensorboard_v2.py:102: UserWarning: The TensorBoard callback does not support embeddings display when using TensorFlow 2.0. Embeddings-related arguments are ignored. warnings.warn('The TensorBoard callback does not support ' C:\Users\Bruno\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\framework\indexed_slices.py:433: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory. "Converting sparse IndexedSlices to a dense Tensor of unknown shape. " Train on 1123 samples, validate on 125 samples Traceback (most recent call last): File ".\NN_Training.py", line 128, in <module> history = model.fit(X, Y, epochs=epochs, batch_size=batch_size, validation_split=0.1, callbacks=[tensorboard]) # Feed in the train set for X and y and run the model!!! File "C:\Users\Bruno\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\engine\training.py", line 1239, in fit validation_freq=validation_freq) File "C:\Users\Bruno\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\engine\training_arrays.py", line 119, in fit_loop callbacks.set_model(callback_model) File "C:\Users\Bruno\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\callbacks\callbacks.py", line 68, in set_model callback.set_model(model) File "C:\Users\Bruno\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\callbacks\tensorboard_v2.py", line 116, in set_model super(TensorBoard, self).set_model(model) File "C:\Users\Bruno\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow_core\python\keras\callbacks.py", line 1532, in set_model self.log_dir, self.model._get_distribution_strategy()) # pylint: disable=protected-access AttributeError: 'Sequential' object has no attribute '_get_distribution_strategy'``` ```
2020/01/24
[ "https://Stackoverflow.com/questions/59894720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12491188/" ]
You are mixing imports between `keras` and `tf.keras`, they are not the same library and doing this is not supported. You should make all imports from one of the libraries, either `keras` or `tf.keras`.
It seems that your python environment is mixing imports from `keras` and `tensorflow.keras`. Try to use **Sequential** module like this: ``` model = tensorflow.keras.Sequential() ``` Or change your imports to something like ``` import tensorflow layers = tensorflow.keras.layers BatchNormalization = tensorflow.keras.layers.BatchNormalization Conv2D = tensorflow.keras.layers.Conv2D Flatten = tensorflow.keras.layers.Flatten TensorBoard = tensorflow.keras.callbacks.TensorBoard ModelCheckpoint = tensorflow.keras.callbacks.ModelCheckpoint ``` ...etc
25,234,921
I want to match a space or the start of a string, using string "abc" for a demo: ``` "abc_some_words" match for "abc" at the start of the string "some_words abc_some_words" match for there is a space before "abc" "Aabc" don't match for there is a "A" before "abc" ``` so I write regex as "[ \A]abc" for "\A Matches only at the start of the string". As shown below, regex "[ \A]abc" matches " abc", but doesn't match "abc" in python. ``` >>> re.search(r"[ \A]abc", "babc") >>> re.search(r"[ \A]abc", "abc") >>> re.search(r"[ \A]abc", " abc") <_sre.SRE_Match object at 0xb6fccdb0> ```
2014/08/11
[ "https://Stackoverflow.com/questions/25234921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1235372/" ]
Unfortunately, `\A` does not represent a character or set of characters. Therefore, it (and the similar `\Z`) cannot be used within a character class (`[]`). If you put it in a character class then it will silently be treated as a capital A. To match either a space or the start of the string, you may use an alternation instead: `(?:\A| )abc` (where I used a non-capturing group `(?:)`).
If you want to match the beginning of the string you can use anchor `^`. So, if you want to have a space at the beginning or abc you can use this regex: ``` ^\s?abc ``` **[Working demo](http://regex101.com/r/oR2kC4/1)**
25,234,921
I want to match a space or the start of a string, using string "abc" for a demo: ``` "abc_some_words" match for "abc" at the start of the string "some_words abc_some_words" match for there is a space before "abc" "Aabc" don't match for there is a "A" before "abc" ``` so I write regex as "[ \A]abc" for "\A Matches only at the start of the string". As shown below, regex "[ \A]abc" matches " abc", but doesn't match "abc" in python. ``` >>> re.search(r"[ \A]abc", "babc") >>> re.search(r"[ \A]abc", "abc") >>> re.search(r"[ \A]abc", " abc") <_sre.SRE_Match object at 0xb6fccdb0> ```
2014/08/11
[ "https://Stackoverflow.com/questions/25234921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1235372/" ]
Unfortunately, `\A` does not represent a character or set of characters. Therefore, it (and the similar `\Z`) cannot be used within a character class (`[]`). If you put it in a character class then it will silently be treated as a capital A. To match either a space or the start of the string, you may use an alternation instead: `(?:\A| )abc` (where I used a non-capturing group `(?:)`).
`\A` -- start of string is the mirror image of `\Z` -- end of string. The meaning of `^` and `$` can be modified by the `re.M` flag. They can either mean the start of the string for `^` or the start of each line; `$` can be either the end of string or the end of each line -- depending on the `re.M` flag. However, `\A` is unambiguously the start of the string and `\Z` is unambiguously the the end of the string. Suppose you have the string: ``` txt='''\ 1 ABC 2 ABC 3 ABC 4 ABC''' ``` To match the ABC at the start of each line you may do: ``` >>> re.findall(r'^\d\sABC', txt, re.M) ['1 ABC', '2 ABC', '3 ABC', '4 ABC'] ``` But if you only want the first and the last line, you may do: ``` >>> re.findall(r'\A\d\sABC|\d\sABC\Z', txt, re.M) ['1 ABC', '4 ABC'] ```
58,827,730
If I have two rows in excel file: say like a,b,c,d... and another row with values 100,121,98,09,100,45,... with same number of columns in both rows; How do we make a dictionary in python, by reading from the xlsx file.... with keys as a,b,c,...with corresponding values in the other row of same column. ```py #to get the two rows l1=[] l2=[] for x in [row1_num,row2_num]: cells=xl_sheet.row_slice(rowx=x,start_colx=20,end_colx=xl_sheet.ncols) for idx,cellobj in enumerate(cells): #based on the idx...should have a dictionary with values in row1 as keys #and row2 as values if(cell_obj.value is not None): if x==row1_num: l1.append(cell_obj.value) elif x==row2_num: l2.append(cell_obj.value) dictionary=dict(zip(l1,l2)) ``` Is this a good approach? also the list1 l1 is becoming empty when coming out of the for loop?
2019/11/12
[ "https://Stackoverflow.com/questions/58827730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11932196/" ]
Here's an example with just a bit of a spin on the example from the [w3schools zip () tutorial](https://www.w3schools.com/python/ref_func_zip.asp). ``` row1 = ("a", "b", "c") row2 = (1, 2, 3) x = zip(row1, row2) print(dict(x)) ``` This will output: `{'a': 1, 'b': 2, 'c': 3}` I believe you can incorporate your additional `xl_sheet` logic easily enough. Happy coding!
You have a nice start there. The hard part for me when solving this problem for myself was figuring out how to chunk the rows into pairs. Here are two solutions to this problem. The first one might be a little easier conceptually to see what is going on. And then I discovered a very slick way to chunk things using [`itertools.zip_longest`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest). See [How to chunk a list in Python 3?](https://stackoverflow.com/q/5850536/1913726) ``` import urllib.request import xlrd import itertools as it # Fake data stored on my Minio server. url = "https://minio.apps.selfip.com/mymedia/xlxs/fake_xl.xlxs" filepath, response = urllib.request.urlretrieve(url, "/tmp/test.xlxs") wb = xlrd.open_workbook(filepath) ws = wb.sheet_by_index(0) odd_rows, even_rows = it.tee(ws.get_rows()) # Get 2 iterables using itertools.tee row_pairs = ( # generator expression to "chunk the rows into groups of 2" [[cell.value for cell in row] for row in rows] # 2D list of values for rows in zip( it.islice(odd_rows, 0, ws.nrows, 2), # Use itertools.islice, odd it.islice(even_rows, 1, ws.nrows, 2), # even ) ) # zip is useful for "zipping" key value pairs together. print([dict(zip(*row_pair)) for row_pair in row_pairs]) # Another way to chunk the rows into pairs is like this: print([ dict(zip(*[[cell.value for cell in pair] for pair in pairs])) for pairs in it.zip_longest(*it.repeat(iter(ws.get_rows()), 2)) ]) ``` Ouput for both: [{'2a5de626': 'algorithm', '86ce99a2': 'implementation', 'e6b481ba': 'adapter', 'bc85c996': 'capability', '4edfb828': 'array', '05d79ce2': 'definition', 'b9b5ae33': 'knowledgebase', 'f0da7366': 'complexity', '39a48259': 'methodology', '1ee95d9e': 'strategy'}, {'01bc389d': 'neural-net', 'd5d16b0c': 'monitoring', 'd9fb3a8d': 'installation', '8c7a049f': 'moratorium', 'f3d9aa0e': 'help-desk', 'd0e8d371': 'paradigm', '9e33f679': 'complexity', '6354affc': 'core', '606c4eb6': 'groupware', '97741196': 'strategy'}, {'76ae32df': 'algorithm', '942654da': 'task-force', '462fa31b': 'ability', '584df007': 'adapter', 'f6293960': 'attitude', 'afd8fa00': 'knowledgebase', '4c5f2c49': 'alliance', '6d76c690': 'collaboration', '3018a22b': 'solution', '034f1bb2': 'access'}]
38,340,914
I have a very long text file (2GB) and I removed duplicates using: ``` sort -u filename > outfile1 ``` and ``` >>> data = open('filename', 'r').readlines() >>> u = list(set(data)) >>> open('outfile2', 'w').writelines(u) ``` However the two files outfile2 and outfile1 have a different number of entries: ``` wc -l outfile? 185866729 filename 109608242 outfile1 109611085 outfile2 ``` How is this possible? UPDATE. Following up on the request to see the data, I have found that python will remove as duplicates entries like: ``` låsningernes læsningernes løsningernes ``` Effectively the second character is ignored in `sort -u`, and only the first entry is kept. Python instead does a good job of distinguishing the three records.
2016/07/13
[ "https://Stackoverflow.com/questions/38340914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1040266/" ]
Without seeing the actual output (or at least the 'extra' lines, we can only guess. But it will come down to how much preprocessing is done by `sort`, which is finding more duplicates than `set()`. Possible causes might be * Trailing spaces on some lines. They might be removed by `sort` but not by `set`. * Different handling of unicode characters. Perhaps sort maps some of them onto a smaller set of equivalents, producing more duplicates.
if you combine them and create them into a list you could do this: ``` non_duplicates= [a for i,a in enumerate(l) if i == l.index(a)] ``` this also keeps the order of the items it contains
11,361,881
When running the install.sh the following error occurs ``` install.sh: line 48: ./INSTALLDIR/lib/python/bin/python: Permission denied ```
2012/07/06
[ "https://Stackoverflow.com/questions/11361881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506689/" ]
since the error got as far as line 48 the permission on install.sh is ok. What is not OK is the permission on the python executable. ``` chmod +x ./INSTALLDIR/lib/python/bin/python ```
Just make sure you have python installed an it's even better if you have v2+ like the one Komodo IDE installer has integrated and to see what version of python you have installed just open your terminal/console and type "python" (without the quotation marks) and the output should be something like this: ``` Python 2.7.3 (default, Sep 26 2012, 21:53:58) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. ``` And if you have python installed then open install.sh and search for a line similar to this: ``` $dname/INSTALLDIR/lib/python/bin/python -E $dname/support/_install.py "$@" ``` (I have Komodo IDE 8.0 so the code might differ) All you have to do is replace the path that points to the integrated python from the Komodo IDE installer "(Komodo IDE folder)/INSTALLDIR/lib/python/bin/python" with your local installed python which is "python" so in conclusion replace: ``` $dname/INSTALLDIR/lib/python/bin/python ``` With: ``` python ``` Result: ``` python -E $dname/support/_install.py "$@" ``` This technique worked for me however I was using Linux Mint 14 Nadia which by default comes with a preinstalled Python version 2.7.3 (like many other linux distributions out there) and my version of Komodo IDE was 8.0 EDIT: The technique above seems to give an error about some missing python module named "activestate" which is a file named "activestate.py" located in the incorporated python from Komodo IDE installer however the second method I've used worked just fine. First step is to open your terminal/console and obtain root privileges after that open your file manager/explorer mine was "nemo" so I typed "nemo" in the terminal/console (without the quotation marks) that opened a new window of nemo with Elevated Privileges aka. Root Privileges so the I've browsed to where I saved the archived Komodo IDE installer I've downloaded from the official site and opened with the default archive manager installed on my system (by default the archive manager also opened with root privileges inherited from nemo file manager) so in the file manager/explorer I've browsed to "/opt/" and extracted the contents of that archive in a folder then closed the archive manager now open a terminal/console window and obtain root privileges then cd into the folder where "install.sh" is located ex. "cd /opt/komodo-ide-8.0.0-linux-x86/" now type in the terminal/console ``` sh ./install.sh ``` Or ``` bash ./install.sh ``` And the rest of the installation should proceed as normal and require you the path where to install Komodo in my case I typed "/opt/komodo/" and the installation worked just fine.
68,104,882
I am creating a program in python using web browser. There is an internet issue. When the internet is slow, the program gets the error (`xpath is not found`) and stops. I am also using the `sleep` function How can I create a `while` loop of xpath? or any other methods please explain. I have done this... ``` browser.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/div[1]/div/span').click() time.sleep(3) ``` **i want to do** when internet gets slow. The program will wait for xpath then click.
2021/06/23
[ "https://Stackoverflow.com/questions/68104882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16107547/" ]
Try this, with RelativeLayout ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:textSize="13sp" android:textColor="@color/black" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="James Lingard" /> <TextView android:textSize="13sp" android:textColor="@color/black" android:gravity="start" android:layout_alignParentEnd="true" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="22" /> ``` or I recomanded(is most adaptable) (P.S. Sorry for my english) ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:textSize="13sp" android:textColor="@color/black" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_weight="4" android:layout_width="0dp" android:layout_height="wrap_content" android:text="James Lingard" /> <TextView android:textSize="13sp" android:textColor="@color/black" android:layout_alignParentEnd="true" android:layout_marginTop="10dp" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:text="22" /> ```
Yes, you're right the problem is : `android:layout_marginStart="410dp"`. I can suppose that on some devices the device screen width less than `410dp`. As I can see you're using `RelativeLayout`, just add the attribute: `android:layout_alignParentEnd="true"` inside your 2nd `TextView`. And, of course, remove this line: `android:layout_marginStart="410dp"`
68,104,882
I am creating a program in python using web browser. There is an internet issue. When the internet is slow, the program gets the error (`xpath is not found`) and stops. I am also using the `sleep` function How can I create a `while` loop of xpath? or any other methods please explain. I have done this... ``` browser.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/div[1]/div/span').click() time.sleep(3) ``` **i want to do** when internet gets slow. The program will wait for xpath then click.
2021/06/23
[ "https://Stackoverflow.com/questions/68104882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16107547/" ]
Yes, you're right the problem is : `android:layout_marginStart="410dp"`. I can suppose that on some devices the device screen width less than `410dp`. As I can see you're using `RelativeLayout`, just add the attribute: `android:layout_alignParentEnd="true"` inside your 2nd `TextView`. And, of course, remove this line: `android:layout_marginStart="410dp"`
You can do it using `ConstraintLayout` ```xml <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:text="James Lingard" android:textColor="@color/black" android:textSize="13sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:text="22" android:textColor="@color/black" android:textSize="13sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> ``` Results [![Display two text](https://i.stack.imgur.com/s5k0H.png)](https://i.stack.imgur.com/s5k0H.png)
68,104,882
I am creating a program in python using web browser. There is an internet issue. When the internet is slow, the program gets the error (`xpath is not found`) and stops. I am also using the `sleep` function How can I create a `while` loop of xpath? or any other methods please explain. I have done this... ``` browser.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/div[1]/div/span').click() time.sleep(3) ``` **i want to do** when internet gets slow. The program will wait for xpath then click.
2021/06/23
[ "https://Stackoverflow.com/questions/68104882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16107547/" ]
Try this, with RelativeLayout ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:textSize="13sp" android:textColor="@color/black" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="James Lingard" /> <TextView android:textSize="13sp" android:textColor="@color/black" android:gravity="start" android:layout_alignParentEnd="true" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="22" /> ``` or I recomanded(is most adaptable) (P.S. Sorry for my english) ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:textSize="13sp" android:textColor="@color/black" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_weight="4" android:layout_width="0dp" android:layout_height="wrap_content" android:text="James Lingard" /> <TextView android:textSize="13sp" android:textColor="@color/black" android:layout_alignParentEnd="true" android:layout_marginTop="10dp" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:text="22" /> ```
You can do it using `ConstraintLayout` ```xml <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:text="James Lingard" android:textColor="@color/black" android:textSize="13sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:text="22" android:textColor="@color/black" android:textSize="13sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> ``` Results [![Display two text](https://i.stack.imgur.com/s5k0H.png)](https://i.stack.imgur.com/s5k0H.png)
23,270,915
I've been following instructions from [this article](http://www.benhavilland.com/blog/deploying-mezzanine-on-heroku/) to deploy mezzanine on heroku I want to run static files from heroku so followed the instructions in the link as mentioned but I'm getting this error when I do "Heroku open" ``` Opening mezzanine-be... failed ! Heroku client internal error. ! Search for help at: https://help.heroku.com ! Or report a bug at: https://github.com/heroku/heroku/issues/new Error: Unable to find a browser command. If this is unexpected, Please rerun with environment variab le LAUNCHY_DEBUG=true or the '-d' commandline option and file a bug at https://github.com/copiousfreetime/laun chy/issues/new (Launchy::CommandNotFoundError) Backtrace: /usr/local/heroku/vendor/gems/launchy-2.4.2/lib/launchy/applications/browser.rb:63:in `browse r_cmdline' /usr/local/heroku/vendor/gems/launchy-2.4.2/lib/launchy/applications/browser.rb:67:in `cmd_an d_args' /usr/local/heroku/vendor/gems/launchy-2.4.2/lib/launchy/applications/browser.rb:78:in `open' /usr/local/heroku/vendor/gems/launchy-2.4.2/lib/launchy.rb:29:in `open' /usr/local/heroku/lib/heroku/helpers.rb:328:in `block in launchy' /usr/local/heroku/lib/heroku/helpers.rb:227:in `action' /usr/local/heroku/lib/heroku/helpers.rb:326:in `launchy' /usr/local/heroku/lib/heroku/command/apps.rb:338:in `open' /usr/local/heroku/lib/heroku/command.rb:218:in `run' /usr/local/heroku/lib/heroku/cli.rb:28:in `start' /usr/local/heroku/bin/heroku:25:in `<main>' Command: heroku open Version: heroku-toolbelt/3.4.1 (i686-linux) ruby/1.9.3 ``` I got this log when I did "heroku logs" ``` 2014-04-22T22:14:23.416063+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/mezzanine/utils/c onf.py:59: UserWarning: TIME_ZONE setting is not set, using closest match: Etc/UTC 2014-04-22T22:14:23.472992+00:00 app[web.1]: Type 'manage.py help' for usage. 2014-04-22T22:14:23.416081+00:00 app[web.1]: warn("TIME_ZONE setting is not set, using closest match: %s" % tz) 2014-04-22T22:14:23.472983+00:00 app[web.1]: Unknown command: 'run_gunicorn' 2014-04-22T22:14:25.275890+00:00 heroku[web.1]: Process exited with status 1 2014-04-22T22:14:25.282406+00:00 heroku[web.1]: State changed from starting to crashed 2014-04-23T04:09:18.972452+00:00 heroku[web.1]: State changed from crashed to starting 2014-04-23T04:09:25.363685+00:00 heroku[web.1]: Starting process with command `python manage.py run_gunicorn - b 0.0.0.0:55680 -w 1` 2014-04-23T04:09:26.682220+00:00 app[web.1]: warn("TIME_ZONE setting is not set, using closest match: %s" % tz) 2014-04-23T04:09:26.682206+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/mezzanine/utils/c onf.py:59: UserWarning: TIME_ZONE setting is not set, using closest match: Etc/UTC 2014-04-23T04:09:26.695461+00:00 app[web.1]: Unknown command: 'run_gunicorn' 2014-04-23T04:09:26.695465+00:00 app[web.1]: Type 'manage.py help' for usage. 2014-04-23T04:09:28.055144+00:00 heroku[web.1]: State changed from starting to crashed 2014-04-23T04:09:28.049204+00:00 heroku[web.1]: Process exited with status 1 2014-04-23T09:52:14.401914+00:00 heroku[web.1]: State changed from crashed to starting 2014-04-23T09:52:20.442477+00:00 heroku[web.1]: Starting process with command `python manage.py run_gunicorn - b 0.0.0.0:30095 -w 1` 2014-04-23T09:52:22.164719+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/mezzanine/utils/c onf.py:59: UserWarning: TIME_ZONE setting is not set, using closest match: Etc/UTC 2014-04-23T09:52:22.164739+00:00 app[web.1]: warn("TIME_ZONE setting is not set, using closest match: %s" % tz) 2014-04-23T09:52:22.179570+00:00 app[web.1]: Unknown command: 'run_gunicorn' 2014-04-23T09:52:22.179578+00:00 app[web.1]: Type 'manage.py help' for usage. 2014-04-23T09:52:23.715744+00:00 heroku[web.1]: State changed from starting to crashed 2014-04-23T09:52:23.701333+00:00 heroku[web.1]: Process exited with status 1 2014-04-23T16:07:31.408614+00:00 heroku[web.1]: State changed from crashed to starting 2014-04-23T16:07:38.553626+00:00 heroku[web.1]: Starting process with command `python manage.py run_gunicorn - b 0.0.0.0:56763 -w 1` 2014-04-23T16:07:41.125475+00:00 app[web.1]: warn("TIME_ZONE setting is not set, using closest match: %s" % tz) 2014-04-23T16:07:41.238560+00:00 app[web.1]: Unknown command: 'run_gunicorn' 2014-04-23T16:07:41.238566+00:00 app[web.1]: Type 'manage.py help' for usage. 2014-04-23T16:07:41.125462+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/mezzanine/utils/c onf.py:59: UserWarning: TIME_ZONE setting is not set, using closest match: Etc/UTC 2014-04-23T16:07:42.885219+00:00 heroku[web.1]: Process exited with status 1 2014-04-23T16:07:42.896873+00:00 heroku[web.1]: State changed from starting to crashed 2014-04-23T22:09:39.404254+00:00 heroku[web.1]: State changed from crashed to starting 2014-04-23T22:09:49.448643+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/mezzanine/utils/c onf.py:59: UserWarning: TIME_ZONE setting is not set, using closest match: Etc/UTC 2014-04-23T22:09:49.460740+00:00 app[web.1]: Unknown command: 'run_gunicorn' 2014-04-23T22:09:49.460747+00:00 app[web.1]: Type 'manage.py help' for usage. 2014-04-23T22:09:49.448658+00:00 app[web.1]: warn("TIME_ZONE setting is not set, using closest match: %s" % tz) 2014-04-23T22:09:48.480416+00:00 heroku[web.1]: Starting process with command `python manage.py run_gunicorn - b 0.0.0.0:9678 -w 1` 2014-04-23T22:09:50.717983+00:00 heroku[web.1]: State changed from starting to crashed 2014-04-23T22:09:50.696212+00:00 heroku[web.1]: Process exited with status 1 2014-04-24T04:11:51.194122+00:00 heroku[web.1]: State changed from crashed to starting 2014-04-24T04:11:56.788844+00:00 heroku[web.1]: Starting process with command `python manage.py run_gunicorn - b 0.0.0.0:36892 -w 1` 2014-04-24T04:11:58.067181+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/mezzanine/utils/c onf.py:59: UserWarning: TIME_ZONE setting is not set, using closest match: Etc/UTC 2014-04-24T04:11:58.067201+00:00 app[web.1]: warn("TIME_ZONE setting is not set, using closest match: %s" % tz) 2014-04-24T04:11:58.092913+00:00 app[web.1]: Unknown command: 'run_gunicorn' 2014-04-24T04:11:58.092919+00:00 app[web.1]: Type 'manage.py help' for usage. 2014-04-24T04:11:59.280453+00:00 heroku[web.1]: Process exited with status 1 2014-04-24T04:11:59.295201+00:00 heroku[web.1]: State changed from starting to crashed 2014-04-24T09:58:52.585546+00:00 heroku[web.1]: State changed from crashed to starting 2014-04-24T09:58:59.277649+00:00 heroku[web.1]: Starting process with command `python manage.py run_gunicorn - b 0.0.0.0:56234 -w 1` 2014-04-24T09:59:00.934694+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/mezzanine/utils/c onf.py:59: UserWarning: TIME_ZONE setting is not set, using closest match: Etc/UTC 2014-04-24T09:59:00.934710+00:00 app[web.1]: warn("TIME_ZONE setting is not set, using closest match: %s" % tz) 2014-04-24T09:59:00.951280+00:00 app[web.1]: Unknown command: 'run_gunicorn' 2014-04-24T09:59:00.951287+00:00 app[web.1]: Type 'manage.py help' for usage. 2014-04-24T09:59:02.627604+00:00 heroku[web.1]: State changed from starting to crashed 2014-04-24T09:59:02.616971+00:00 heroku[web.1]: Process exited with status 1 2014-04-24T13:30:08+00:00 heroku[slug-compiler]: Slug compilation started 2014-04-24T13:30:44+00:00 heroku[slug-compiler]: Slug compilation finished 2014-04-24T13:30:44.581580+00:00 heroku[web.1]: State changed from crashed to starting 2014-04-24T13:30:44.310696+00:00 heroku[api]: Release v6 created by chetan.s.kaushal@gmail.com 2014-04-24T13:30:44.310620+00:00 heroku[api]: Deploy da509c9 by chetan.s.kaushal@gmail.com 2014-04-24T13:30:51.209645+00:00 heroku[web.1]: Starting process with command `python manage.py run_gunicorn - b 0.0.0.0:28107 -w 1` 2014-04-24T13:30:52.802204+00:00 app[web.1]: Unknown command: 'run_gunicorn' 2014-04-24T13:30:52.802220+00:00 app[web.1]: Type 'manage.py help' for usage. 2014-04-24T13:30:54.569234+00:00 heroku[web.1]: State changed from starting to crashed 2014-04-24T13:30:54.549885+00:00 heroku[web.1]: Process exited with status 1 2014-04-24T13:30:54.569652+00:00 heroku[web.1]: State changed from crashed to starting 2014-04-24T13:31:00.396574+00:00 heroku[web.1]: Starting process with command `python manage.py run_gunicorn - b 0.0.0.0:50627 -w 1` 2014-04-24T13:31:03.282440+00:00 app[web.1]: Unknown command: 'run_gunicorn' 2014-04-24T13:31:03.282451+00:00 app[web.1]: Type 'manage.py help' for usage. 2014-04-24T13:31:04.743794+00:00 heroku[web.1]: Process exited with status 1 2014-04-24T13:31:04.756855+00:00 heroku[web.1]: State changed from starting to crashed 2014-04-24T13:31:06.091140+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=m ezzanine-be.herokuapp.com request_id=c1d2e607-a55c-422c-9ef1-f6a45ace8f82 fwd="1.23.88.93" dyno= connect= serv ice= status=503 bytes= 2014-04-24T13:31:06.829718+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/favicon .ico host=mezzanine-be.herokuapp.com request_id=df6accba-7950-4bec-ae57-116ec3cfe5f6 fwd="1.23.88.93" dyno= co nnect= service= status=503 bytes= 2014-04-24T13:35:10+00:00 heroku[slug-compiler]: Slug compilation started 2014-04-24T13:35:56+00:00 heroku[slug-compiler]: Slug compilation finished 2014-04-24T13:35:56.126982+00:00 heroku[web.1]: State changed from crashed to starting 2014-04-24T13:35:56.003342+00:00 heroku[api]: Release v7 created by chetan.s.kaushal@gmail.com 2014-04-24T13:35:56.003219+00:00 heroku[api]: Deploy 8cdb5a0 by chetan.s.kaushal@gmail.com 2014-04-24T13:36:03.608314+00:00 app[web.1]: ImproperlyConfigured: The SECRET_KEY setting must not be empty. 2014-04-24T13:36:04.981170+00:00 heroku[web.1]: State changed from starting to crashed 2014-04-24T13:36:02.181124+00:00 heroku[web.1]: Starting process with command `python manage.py runserver 0.0. 0.0:59156 --noreload` 2014-04-24T13:36:04.967644+00:00 heroku[web.1]: Process exited with status 1 2014-04-24T13:36:49.185541+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=m ezzanine-be.herokuapp.com request_id=403daa9a-5359-4041-b0a0-a7ecaaf2a839 fwd="1.23.88.93" dyno= connect= serv ice= status=503 bytes= 2014-04-24T13:36:49.802726+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/favicon .ico host=mezzanine-be.herokuapp.com request_id=d0a5e62e-29e4-444d-87f4-0a83f635a53c fwd="1.23.88.93" dyno= co nnect= service= status=503 bytes= 2014-04-24T13:38:54.744538+00:00 heroku[api]: Starting process with command `python manage.py createdb` by che tan.s.kaushal@gmail.com 2014-04-24T13:39:02.543383+00:00 heroku[run.4712]: State changed from starting to up 2014-04-24T13:39:02.443450+00:00 heroku[run.4712]: Awaiting client 2014-04-24T13:39:02.480032+00:00 heroku[run.4712]: Starting process with command `python manage.py createdb` 2014-04-24T13:39:04.781382+00:00 heroku[run.4712]: Process exited with status 1 2014-04-24T13:39:04.792816+00:00 heroku[run.4712]: State changed from up to complete 2014-04-24T13:39:35.844877+00:00 heroku[api]: Starting process with command `python manage.py createdb --noinp ut` by chetan.s.kaushal@gmail.com 2014-04-24T13:39:43.296642+00:00 heroku[run.2213]: Awaiting client 2014-04-24T13:39:43.363388+00:00 heroku[run.2213]: Starting process with command `python manage.py createdb -- noinput` 2014-04-24T13:39:43.338269+00:00 heroku[run.2213]: State changed from starting to up 2014-04-24T13:39:45.504923+00:00 heroku[run.2213]: Process exited with status 1 2014-04-24T13:39:45.513948+00:00 heroku[run.2213]: State changed from up to complete 2014-04-24T13:40:07.033895+00:00 heroku[api]: Starting process with command `python manage.py createdb` by che tan.s.kaushal@gmail.com 2014-04-24T13:40:14.314579+00:00 heroku[run.5886]: Awaiting client 2014-04-24T13:40:14.359512+00:00 heroku[run.5886]: Starting process with command `python manage.py createdb` 2014-04-24T13:40:14.154217+00:00 heroku[run.5886]: State changed from starting to up 2014-04-24T13:40:16.102836+00:00 heroku[run.5886]: State changed from up to complete 2014-04-24T13:40:16.092128+00:00 heroku[run.5886]: Process exited with status 1 ```
2014/04/24
[ "https://Stackoverflow.com/questions/23270915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2539745/" ]
Well, this is more a mathematical problem than a programming one, isn't it. To begin, you have an inner width of 220px inside a div of 200px, aligned left. Your offset is then 10px (half the difference). You need to move the center of the inner div 10px to the left to get it centered. Then. you are applying a scale of 0.75. That means a delta (or change) of 0.25. To get a delta of 10px (the movement that you need), you have to apply it to 40px of initial length (10px divided by 0.25). If your transform is happening 40px to the left of the center of the inner div, it will center it. Now, since the center is at 110px from the left edge, this point 40px to the left of the center is 70px to the right of the left edge. And finally, 70px in a 220px width is 31.81 %. Try it and you will see
Brilliant, thank you @vals. Since the x-origin can be expressed in pixels, we can simplify thus: ``` x = outer width j = inner width s = scale k = js (scaled width) d = 1-s (delta) x-offset = (x-k) / 2d x-offset = (outer width - (inner width * scale)) / 2 (1 - scale) ``` That's immensely useful (sorry @Paulie\_D !)
41,220,699
I have a 'myfile.csv' file which has a 'timestamp' column which starts at (01/05/2015 11:51:00) and finishes at (07/05/2015 23:22:00) A total span of 9,727 minutes 'myfile.csv' also has a column named 'A' which is some numerical value, there are values are multiple values for 'A' within each minute, each with a unique timestamp to the nearest second. I have code as follows ``` df = pd.read_csv('myfile.csv') df = df.set_index('timestamp') df.index = df.index.to_datetime() df.sort_index(inplace=True) df = df['A'].resample('1Min').mean() df.index = (df.index.map(lambda t: t.strftime('%Y-%m-%d %H:%M'))) ``` My problem is that python seems to think 'timestamp' starts at (01/05/2015 11:51:00) -> 5th January and finishes at (07/05/2015 23:22:00) -> 5th July But really 'timestamp' starts at the 1st May and finishes at the 7th of May So the above code produces a dataframe with 261,332 rows, OMG, when it should really only have 9,727 rows. Somehow Python is mixing up the month with the day, misinterpreting the dates, how do I sort this out?
2016/12/19
[ "https://Stackoverflow.com/questions/41220699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6056160/" ]
There are many arguments within `csv_read` that can help you parse dates from a csv straight into your pandas DataFrame. Here we can set `parse_dates` with the columns you want as dates and then use `dayfirst`. This is defaulted to `false` so the following should do what you want, assuming the dates are in the first column. ``` df = pd.read_csv('myfile.csv', parse_dates=[0], dayfirst=True) ``` If the dates column is not the first row, just change the `0` to the column number.
The format of dates that you have included in your question don't seem to match your strftime filter. Take a look at [this](http://strftime.org/) to fix your string parameter. It looks to me that it should be something in the lines of: ``` '%d/%m/%Y %H:%M:%S' ```
7,728,977
I am trying to add a Chinese language to my application written in Django and I have a really hard time with that. I have spent half a day trying different approaches, no success. My application supports few languages, this is part of **settings.py** file: ``` TIME_ZONE = 'Europe/Dublin' LANGUAGE_CODE = 'en' LOCALES = ( #English ('en', u'English'), #Norwegian ('no', u'Norsk'), #Finish ('fi', u'Suomi'), #Simplified Chinese ('zh-CN', u'简体中文'), #Traditional Chinese ('zh-TW', u'繁體中文'), #Japanese ('ja', u'日本語'), ) ``` At the moment all (but Chinese) languages work perfectly. This is a content of **locale directory**: ``` $ ls locale/ en fi ja no zh_CN zh_TW ``` In every directory I have LC\_MESSAGES directory with \*.mo and \*.po files. \*.po files are created by script written in Python, which converts \*.ODS to a text file. \*.mo files are created by **python manage.py compilemessages** command. Language can be selected by user from the proper form in "Preferences" section in my application. Django does not load Chinese translation. That is the problem. Both simplified and traditional does not work. I have tried different variations of language and locale codes in settings.py and in locale directory: zh-CN, zh-cn, zh\_CN, zh\_cn. No success. Perhaps I made a simple mistake? I have added Polish language just for test and everything went fine. Basically I did the same. I have added ('pl', u'Polish') tuple to the settings.py and "locale/pl" with \*.po and \*.mo and LC\_MESSAGES directory... Do you know what might be wrong?
2011/10/11
[ "https://Stackoverflow.com/questions/7728977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989862/" ]
You will need to use lower case for your locale language codes for it to work properly. i.e. use ``` LANGUAGES = ( ('zh-cn', u'简体中文'), # instead of 'zh-CN' ('zh-tw', u'繁體中文'), # instead of 'zh-TW' ) ``` See the language codes specified in <https://code.djangoproject.com/browser/django/trunk/django/conf/global_settings.py>. You will see that it uses `zh-tw` instead of `zh-TW`. Finally, the language directories storing the \*.po and \*.mo files in your locales folder needs to be named `zh_CN` and `zh_TW` respectively for the translations to work properly.
Not sure if you were able to resolve this later, but the problem is with the language directory names in the locale directory. This happens with all languages with a dash in their short-code. The solution is to rename the Chinese directories by replacing the dashes with underscores: zh-cn --> zh\_cn zh-tw --> zh\_tw Hope this helps.