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
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return the same `True`(or `False`) with the pre-allocated `True`(or `False`)? Is it safe to replace `==` with `is` to compare Boolean-values? --- It's not about Best-Practice. I just want to know the Truth.
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
You probably shouldn't ever need to compare booleans. If you are doing something like: ``` if some_bool == True: ... ``` ...just change it to: ``` if some_bool: ... ``` No `is` or `==` needed. As commenters have pointed out, there are valid reasons to compare booleans. If both booleans are unknown and you want to know if one is equal to the other, you should use `==` or `!=` rather than `is` or `is not` (the reason is explained below). Note that this is logically equivalent to `xnor` and `xor` respectively, which don't exist as logical operators in Python. Internally, there should only ever be [two boolean literal objects](http://docs.python.org/library/functions.html#bool) (see also the [C API](http://docs.python.org/c-api/bool.html)), and `bool(x) is True` should be `True` if `bool(x) == True` for any Python program. Two caveats: * This *does not mean* that `x is True` if `x == True`, however (eg. `x = 1`). * This is true for the usual implementation of Python (CPython) but might not be true in other implementations. Hence `==` is a more reliable comparison.
`==` and `is` are both comparison operators, which would return a boolean value - `True` or `False`. True has a numeric value of 1 and False has a numeric value of 0. The operator `==` compare the values of two objects and objects compared are most often are the same types (int vs int, float vs float), If you compare objects of different types, then they are unequal. The operator `is` tests for object identity, 'x is y' is true if both x and y have the same id. That is, they are same objects. So, when you are comparing if you comparing the return values of same type, use == and if you are comparing if two objects are same (be it boolean or anything else), you can use `is`. `42 is 42` is True and is same as `42 == 42`.
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return the same `True`(or `False`) with the pre-allocated `True`(or `False`)? Is it safe to replace `==` with `is` to compare Boolean-values? --- It's not about Best-Practice. I just want to know the Truth.
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
Watch out for what else you may be comparing. ``` >>> 1 == True True >>> 1 is True False ``` True and False will have stable object ids for their lifetime in your python instance. ``` >>> id(True) 4296106928 >>> id(True) 4296106928 ``` `is` compares the id of an object EDIT: adding `or` Since OP is using `or` in question it may be worth pointing this out. **or that evaluates True:** returns the first 'True' object. ``` >>> 1 or True 1 >>> 'a' or True 'a' >>> True or 1 True ``` **or that evaluates False:** returns the last 'False' object ``` >>> False or '' '' >>> '' or False False ``` **and that evaluates to True:** returns the last 'True' object ``` >>> True and 1 1 >>> 1 and True True ``` **and that evaluates to False:** returns the first 'False' object ``` >>> '' and False '' >>> False and '' False ``` This is an important python idiom and it allows concise and compact code for dealing with boolean logic over regular python objects. ``` >>> bool([]) False >>> bool([0]) True >>> bool({}) False >>> bool({False: False}) True >>> bool(0) False >>> bool(-1) True >>> bool('False') True >>> bool('') False ``` Basically 'empty' objects are False, 'non empty' are True. Combining this with @detly's and the other answers should provide some insight into how to use `if` and bools in python.
`==` and `is` are both comparison operators, which would return a boolean value - `True` or `False`. True has a numeric value of 1 and False has a numeric value of 0. The operator `==` compare the values of two objects and objects compared are most often are the same types (int vs int, float vs float), If you compare objects of different types, then they are unequal. The operator `is` tests for object identity, 'x is y' is true if both x and y have the same id. That is, they are same objects. So, when you are comparing if you comparing the return values of same type, use == and if you are comparing if two objects are same (be it boolean or anything else), you can use `is`. `42 is 42` is True and is same as `42 == 42`.
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return the same `True`(or `False`) with the pre-allocated `True`(or `False`)? Is it safe to replace `==` with `is` to compare Boolean-values? --- It's not about Best-Practice. I just want to know the Truth.
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
It seems that all answers deal with `True` and `False` as defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects: ``` >>> True = 1 >>> (2 > 1) True >>> (2 > 1) == True True >>> (2 > 1) is True False ``` If you have to deal with older software, be aware of that.
[The == operator tests for equality The is keyword tests for object identity. Whether we are talking about the same object. Note, that more variables may refer to the same object.](http://zetcode.com/tutorials/pythontutorial/keywords/)
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return the same `True`(or `False`) with the pre-allocated `True`(or `False`)? Is it safe to replace `==` with `is` to compare Boolean-values? --- It's not about Best-Practice. I just want to know the Truth.
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
You probably shouldn't ever need to compare booleans. If you are doing something like: ``` if some_bool == True: ... ``` ...just change it to: ``` if some_bool: ... ``` No `is` or `==` needed. As commenters have pointed out, there are valid reasons to compare booleans. If both booleans are unknown and you want to know if one is equal to the other, you should use `==` or `!=` rather than `is` or `is not` (the reason is explained below). Note that this is logically equivalent to `xnor` and `xor` respectively, which don't exist as logical operators in Python. Internally, there should only ever be [two boolean literal objects](http://docs.python.org/library/functions.html#bool) (see also the [C API](http://docs.python.org/c-api/bool.html)), and `bool(x) is True` should be `True` if `bool(x) == True` for any Python program. Two caveats: * This *does not mean* that `x is True` if `x == True`, however (eg. `x = 1`). * This is true for the usual implementation of Python (CPython) but might not be true in other implementations. Hence `==` is a more reliable comparison.
Yes. There are [guaranteed](http://docs.python.org/library/functions.html#bool) to be exactly two `bool`s, True and False: > > Class bool cannot be subclassed > further. Its only instances are False > and True. > > > That means *if* you know both operands are `bool`, `==` and `is` are equivalent. However, as detly notes, there's usually no reason to use either in this case.
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return the same `True`(or `False`) with the pre-allocated `True`(or `False`)? Is it safe to replace `==` with `is` to compare Boolean-values? --- It's not about Best-Practice. I just want to know the Truth.
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
Yes. There are [guaranteed](http://docs.python.org/library/functions.html#bool) to be exactly two `bool`s, True and False: > > Class bool cannot be subclassed > further. Its only instances are False > and True. > > > That means *if* you know both operands are `bool`, `==` and `is` are equivalent. However, as detly notes, there's usually no reason to use either in this case.
It seems that all answers deal with `True` and `False` as defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects: ``` >>> True = 1 >>> (2 > 1) True >>> (2 > 1) == True True >>> (2 > 1) is True False ``` If you have to deal with older software, be aware of that.
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return the same `True`(or `False`) with the pre-allocated `True`(or `False`)? Is it safe to replace `==` with `is` to compare Boolean-values? --- It's not about Best-Practice. I just want to know the Truth.
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
Yes. There are [guaranteed](http://docs.python.org/library/functions.html#bool) to be exactly two `bool`s, True and False: > > Class bool cannot be subclassed > further. Its only instances are False > and True. > > > That means *if* you know both operands are `bool`, `==` and `is` are equivalent. However, as detly notes, there's usually no reason to use either in this case.
[The == operator tests for equality The is keyword tests for object identity. Whether we are talking about the same object. Note, that more variables may refer to the same object.](http://zetcode.com/tutorials/pythontutorial/keywords/)
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always return the same `True`(or `False`) with the pre-allocated `True`(or `False`)? Is it safe to replace `==` with `is` to compare Boolean-values? --- It's not about Best-Practice. I just want to know the Truth.
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
Watch out for what else you may be comparing. ``` >>> 1 == True True >>> 1 is True False ``` True and False will have stable object ids for their lifetime in your python instance. ``` >>> id(True) 4296106928 >>> id(True) 4296106928 ``` `is` compares the id of an object EDIT: adding `or` Since OP is using `or` in question it may be worth pointing this out. **or that evaluates True:** returns the first 'True' object. ``` >>> 1 or True 1 >>> 'a' or True 'a' >>> True or 1 True ``` **or that evaluates False:** returns the last 'False' object ``` >>> False or '' '' >>> '' or False False ``` **and that evaluates to True:** returns the last 'True' object ``` >>> True and 1 1 >>> 1 and True True ``` **and that evaluates to False:** returns the first 'False' object ``` >>> '' and False '' >>> False and '' False ``` This is an important python idiom and it allows concise and compact code for dealing with boolean logic over regular python objects. ``` >>> bool([]) False >>> bool([0]) True >>> bool({}) False >>> bool({False: False}) True >>> bool(0) False >>> bool(-1) True >>> bool('False') True >>> bool('') False ``` Basically 'empty' objects are False, 'non empty' are True. Combining this with @detly's and the other answers should provide some insight into how to use `if` and bools in python.
[The == operator tests for equality The is keyword tests for object identity. Whether we are talking about the same object. Note, that more variables may refer to the same object.](http://zetcode.com/tutorials/pythontutorial/keywords/)
62,745,685
I am a beginner in Python. Here's what I am trying to do : ```python import numpy as np r10 = np.array([[i for i in range(0,10)],[i*10 for i in range(0,10)]]).T r6 = np.array([[i for i in range(0,6)],[i*10 for i in range(0,6)]]).T r_comb = np.array([[r10],[r6]]).T np.savetxt('out.txt',r_comb) ``` Using np.savetxt gives me the following error since it only supports 1-D array : ```python --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding) 1433 try: -> 1434 v = format % tuple(row) + newline 1435 except TypeError: TypeError: only size-1 arrays can be converted to Python scalars During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-88-c3147f076055> in <module> ----> 1 np.savetxt('out.txt',r_comb) <__array_function__ internals> in savetxt(*args, **kwargs) ~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding) 1434 v = format % tuple(row) + newline 1435 except TypeError: -> 1436 raise TypeError("Mismatch between array dtype ('%s') and " 1437 "format specifier ('%s')" 1438 % (str(X.dtype), format)) TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e %.18e') ``` Is there any other way of saving the contents of the variable r\_comb to a .txt file so that I can use it for other plotting programs? Basically,I want the text file to look like this : ```python 0 0.0 0 0.0 1 0.1 1 0.1 2 0.2 2 0.2 3 0.3 3 0.3 4 0.4 4 0.4 5 0.5 5 0.5 6 0.6 7 0.7 8 0.8 9 0.9 ``` Image showing how the contents of the text file should look [![enter image description here](https://i.stack.imgur.com/dLpbW.png)](https://i.stack.imgur.com/dLpbW.png)
2020/07/05
[ "https://Stackoverflow.com/questions/62745685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13872751/" ]
How about using a ref as the gatekeepr ``` function useEffectIfReady(fn, deps = [], isReady = true) { const readyWasToggled = useRef(isReady); /* There are 2 states: 0 - initial 1 - ready was toggled */ const getDep = () => { if (readyWasToggled.current) { return 1; } if (isReady) { readyWasToggled.current = true; } return 0; }; useEffect(() => { if (!isReady) { return; } return fn(); }, [...deps, fn, getDep()]); } ``` [![Edit optimistic-wu-cbfd5](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/optimistic-wu-cbfd5?fontsize=14&hidenavigation=1&theme=dark)
Try splitting the useEffect in this case for each state, just an idea based on your codes ``` useEffect(() => { // your codes here if (!isTrue) { return; } }, [isTrue]); useEffect(() => { // your another set of codes here someFunction(dep); }, [dep]) ```
62,745,685
I am a beginner in Python. Here's what I am trying to do : ```python import numpy as np r10 = np.array([[i for i in range(0,10)],[i*10 for i in range(0,10)]]).T r6 = np.array([[i for i in range(0,6)],[i*10 for i in range(0,6)]]).T r_comb = np.array([[r10],[r6]]).T np.savetxt('out.txt',r_comb) ``` Using np.savetxt gives me the following error since it only supports 1-D array : ```python --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding) 1433 try: -> 1434 v = format % tuple(row) + newline 1435 except TypeError: TypeError: only size-1 arrays can be converted to Python scalars During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-88-c3147f076055> in <module> ----> 1 np.savetxt('out.txt',r_comb) <__array_function__ internals> in savetxt(*args, **kwargs) ~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding) 1434 v = format % tuple(row) + newline 1435 except TypeError: -> 1436 raise TypeError("Mismatch between array dtype ('%s') and " 1437 "format specifier ('%s')" 1438 % (str(X.dtype), format)) TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e %.18e') ``` Is there any other way of saving the contents of the variable r\_comb to a .txt file so that I can use it for other plotting programs? Basically,I want the text file to look like this : ```python 0 0.0 0 0.0 1 0.1 1 0.1 2 0.2 2 0.2 3 0.3 3 0.3 4 0.4 4 0.4 5 0.5 5 0.5 6 0.6 7 0.7 8 0.8 9 0.9 ``` Image showing how the contents of the text file should look [![enter image description here](https://i.stack.imgur.com/dLpbW.png)](https://i.stack.imgur.com/dLpbW.png)
2020/07/05
[ "https://Stackoverflow.com/questions/62745685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13872751/" ]
How about using a ref as the gatekeepr ``` function useEffectIfReady(fn, deps = [], isReady = true) { const readyWasToggled = useRef(isReady); /* There are 2 states: 0 - initial 1 - ready was toggled */ const getDep = () => { if (readyWasToggled.current) { return 1; } if (isReady) { readyWasToggled.current = true; } return 0; }; useEffect(() => { if (!isReady) { return; } return fn(); }, [...deps, fn, getDep()]); } ``` [![Edit optimistic-wu-cbfd5](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/optimistic-wu-cbfd5?fontsize=14&hidenavigation=1&theme=dark)
If I have understood your query correctly, you need to execute the `someFn()` depending on the value of isTrue. Though there are ways using custom hooks to compare old and new values and that can be used to solve your problem here, I think there is a much simpler solution to it. Simply, removing the `isTrue` from the dependency array. This will make sure that your `useEffect` runs only when the `dep` changes. If at that point, i`sTrue == true` then nothing gets executed, otherwise your code gets executed. ``` useEffect(() => { if (!isTrue) { return; } someFunction(dep); }, [dep]); ```
62,745,685
I am a beginner in Python. Here's what I am trying to do : ```python import numpy as np r10 = np.array([[i for i in range(0,10)],[i*10 for i in range(0,10)]]).T r6 = np.array([[i for i in range(0,6)],[i*10 for i in range(0,6)]]).T r_comb = np.array([[r10],[r6]]).T np.savetxt('out.txt',r_comb) ``` Using np.savetxt gives me the following error since it only supports 1-D array : ```python --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding) 1433 try: -> 1434 v = format % tuple(row) + newline 1435 except TypeError: TypeError: only size-1 arrays can be converted to Python scalars During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-88-c3147f076055> in <module> ----> 1 np.savetxt('out.txt',r_comb) <__array_function__ internals> in savetxt(*args, **kwargs) ~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding) 1434 v = format % tuple(row) + newline 1435 except TypeError: -> 1436 raise TypeError("Mismatch between array dtype ('%s') and " 1437 "format specifier ('%s')" 1438 % (str(X.dtype), format)) TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e %.18e') ``` Is there any other way of saving the contents of the variable r\_comb to a .txt file so that I can use it for other plotting programs? Basically,I want the text file to look like this : ```python 0 0.0 0 0.0 1 0.1 1 0.1 2 0.2 2 0.2 3 0.3 3 0.3 4 0.4 4 0.4 5 0.5 5 0.5 6 0.6 7 0.7 8 0.8 9 0.9 ``` Image showing how the contents of the text file should look [![enter image description here](https://i.stack.imgur.com/dLpbW.png)](https://i.stack.imgur.com/dLpbW.png)
2020/07/05
[ "https://Stackoverflow.com/questions/62745685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13872751/" ]
How about using a ref as the gatekeepr ``` function useEffectIfReady(fn, deps = [], isReady = true) { const readyWasToggled = useRef(isReady); /* There are 2 states: 0 - initial 1 - ready was toggled */ const getDep = () => { if (readyWasToggled.current) { return 1; } if (isReady) { readyWasToggled.current = true; } return 0; }; useEffect(() => { if (!isReady) { return; } return fn(); }, [...deps, fn, getDep()]); } ``` [![Edit optimistic-wu-cbfd5](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/optimistic-wu-cbfd5?fontsize=14&hidenavigation=1&theme=dark)
If I've understood correctly then the behaviour you're looking for is: * if `isReady` becomes true for the first time, run `fn()` * if `isReady` flips from false to true: 1. `deps` have changed since last time ready, run `fn()` 2. `deps` have not changed since last time ready, do not run `fn()` * if `deps` change and `isReady` is true, run `fn()` I worked this out from plugging your hook into some UI code, if it's not correct let me know and I'll change/delete this. It seems to me that `isReady` and `deps` do not have a straightforward relationship, as in they do not correlate well enough for a single `useEffect` to handle. They are responsible for different things and have to be handled separately. I would try and refactor things higher up in the logic so that they will play nicer together, outside the react render cycle if possible, but I understand that isn't always the case. If so, using a gate and `refs` to control the flow between them makes the most sense to me. If you only pass one `dep` to the hook it makes things a bit simpler: ``` function useGatedEffect(fn, dep, isReady = true) { const gate = useRef(isReady); const prev = useRef(dep); useEffect(() => { gate.current = isReady; if (gate.current && prev.current !== null) { fn(prev.current); prev.current = null; } }, [isReady, fn]); useEffect(() => { gate.current ? fn(dep) : (prev.current = dep); }, [dep, fn]); } ``` However, if you have to pass in an unspecified number of dependencies then you are going to have to do your own equality checks. React will throw warnings if you try and pass spread objects to a `useEffect` and it's better for readability to have them hard-coded anyway. As far as I can tell this does the same thing as your original hook, but separates the (simple) comparison logic which will hopefully make it easier to refactor and maintain: ```js const { useState, useEffect, useRef, useCallback } = React; function useGatedEffect(fn, deps = [], isReady = true) { const gate = useRef(isReady); const prev = useRef(deps); const [compared, setCompared] = useState(deps); useEffect(() => { depsChanged(compared, deps) && setCompared(deps); }, [compared, deps]); useEffect(() => { gate.current = isReady; if (gate.current && prev.current.length !== 0) { fn(...prev.current); prev.current = []; } }, [isReady, fn]); useEffect(() => { gate.current ? fn(...compared) : (prev.current = compared); }, [compared, fn]); function depsChanged(prev, next) { return next.some((item, i) => prev[i] !== item); } } function App() { const [saved, setSaved] = useState(""); const [string, setString] = useState("hello"); const [ready, setReady] = useState(false); const callback = useCallback(dep => { console.log(dep); setString(dep); }, []); useGatedEffect(callback, [saved], ready); return ( <div> <h1>{string}</h1> <input type="text" onChange={e => setSaved(e.target.value)} /> <button onClick={() => setReady(!ready)}> Set Ready: {(!ready).toString()} </button> </div> ); } ReactDOM.render(<App/>, document.getElementById('root')); ``` ```html <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <div id="root"></div> ```
62,745,685
I am a beginner in Python. Here's what I am trying to do : ```python import numpy as np r10 = np.array([[i for i in range(0,10)],[i*10 for i in range(0,10)]]).T r6 = np.array([[i for i in range(0,6)],[i*10 for i in range(0,6)]]).T r_comb = np.array([[r10],[r6]]).T np.savetxt('out.txt',r_comb) ``` Using np.savetxt gives me the following error since it only supports 1-D array : ```python --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding) 1433 try: -> 1434 v = format % tuple(row) + newline 1435 except TypeError: TypeError: only size-1 arrays can be converted to Python scalars During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-88-c3147f076055> in <module> ----> 1 np.savetxt('out.txt',r_comb) <__array_function__ internals> in savetxt(*args, **kwargs) ~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding) 1434 v = format % tuple(row) + newline 1435 except TypeError: -> 1436 raise TypeError("Mismatch between array dtype ('%s') and " 1437 "format specifier ('%s')" 1438 % (str(X.dtype), format)) TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e %.18e') ``` Is there any other way of saving the contents of the variable r\_comb to a .txt file so that I can use it for other plotting programs? Basically,I want the text file to look like this : ```python 0 0.0 0 0.0 1 0.1 1 0.1 2 0.2 2 0.2 3 0.3 3 0.3 4 0.4 4 0.4 5 0.5 5 0.5 6 0.6 7 0.7 8 0.8 9 0.9 ``` Image showing how the contents of the text file should look [![enter image description here](https://i.stack.imgur.com/dLpbW.png)](https://i.stack.imgur.com/dLpbW.png)
2020/07/05
[ "https://Stackoverflow.com/questions/62745685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13872751/" ]
If I have understood your query correctly, you need to execute the `someFn()` depending on the value of isTrue. Though there are ways using custom hooks to compare old and new values and that can be used to solve your problem here, I think there is a much simpler solution to it. Simply, removing the `isTrue` from the dependency array. This will make sure that your `useEffect` runs only when the `dep` changes. If at that point, i`sTrue == true` then nothing gets executed, otherwise your code gets executed. ``` useEffect(() => { if (!isTrue) { return; } someFunction(dep); }, [dep]); ```
Try splitting the useEffect in this case for each state, just an idea based on your codes ``` useEffect(() => { // your codes here if (!isTrue) { return; } }, [isTrue]); useEffect(() => { // your another set of codes here someFunction(dep); }, [dep]) ```
62,745,685
I am a beginner in Python. Here's what I am trying to do : ```python import numpy as np r10 = np.array([[i for i in range(0,10)],[i*10 for i in range(0,10)]]).T r6 = np.array([[i for i in range(0,6)],[i*10 for i in range(0,6)]]).T r_comb = np.array([[r10],[r6]]).T np.savetxt('out.txt',r_comb) ``` Using np.savetxt gives me the following error since it only supports 1-D array : ```python --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding) 1433 try: -> 1434 v = format % tuple(row) + newline 1435 except TypeError: TypeError: only size-1 arrays can be converted to Python scalars During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-88-c3147f076055> in <module> ----> 1 np.savetxt('out.txt',r_comb) <__array_function__ internals> in savetxt(*args, **kwargs) ~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\npyio.py in savetxt(fname, X, fmt, delimiter, newline, header, footer, comments, encoding) 1434 v = format % tuple(row) + newline 1435 except TypeError: -> 1436 raise TypeError("Mismatch between array dtype ('%s') and " 1437 "format specifier ('%s')" 1438 % (str(X.dtype), format)) TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e %.18e') ``` Is there any other way of saving the contents of the variable r\_comb to a .txt file so that I can use it for other plotting programs? Basically,I want the text file to look like this : ```python 0 0.0 0 0.0 1 0.1 1 0.1 2 0.2 2 0.2 3 0.3 3 0.3 4 0.4 4 0.4 5 0.5 5 0.5 6 0.6 7 0.7 8 0.8 9 0.9 ``` Image showing how the contents of the text file should look [![enter image description here](https://i.stack.imgur.com/dLpbW.png)](https://i.stack.imgur.com/dLpbW.png)
2020/07/05
[ "https://Stackoverflow.com/questions/62745685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13872751/" ]
If I've understood correctly then the behaviour you're looking for is: * if `isReady` becomes true for the first time, run `fn()` * if `isReady` flips from false to true: 1. `deps` have changed since last time ready, run `fn()` 2. `deps` have not changed since last time ready, do not run `fn()` * if `deps` change and `isReady` is true, run `fn()` I worked this out from plugging your hook into some UI code, if it's not correct let me know and I'll change/delete this. It seems to me that `isReady` and `deps` do not have a straightforward relationship, as in they do not correlate well enough for a single `useEffect` to handle. They are responsible for different things and have to be handled separately. I would try and refactor things higher up in the logic so that they will play nicer together, outside the react render cycle if possible, but I understand that isn't always the case. If so, using a gate and `refs` to control the flow between them makes the most sense to me. If you only pass one `dep` to the hook it makes things a bit simpler: ``` function useGatedEffect(fn, dep, isReady = true) { const gate = useRef(isReady); const prev = useRef(dep); useEffect(() => { gate.current = isReady; if (gate.current && prev.current !== null) { fn(prev.current); prev.current = null; } }, [isReady, fn]); useEffect(() => { gate.current ? fn(dep) : (prev.current = dep); }, [dep, fn]); } ``` However, if you have to pass in an unspecified number of dependencies then you are going to have to do your own equality checks. React will throw warnings if you try and pass spread objects to a `useEffect` and it's better for readability to have them hard-coded anyway. As far as I can tell this does the same thing as your original hook, but separates the (simple) comparison logic which will hopefully make it easier to refactor and maintain: ```js const { useState, useEffect, useRef, useCallback } = React; function useGatedEffect(fn, deps = [], isReady = true) { const gate = useRef(isReady); const prev = useRef(deps); const [compared, setCompared] = useState(deps); useEffect(() => { depsChanged(compared, deps) && setCompared(deps); }, [compared, deps]); useEffect(() => { gate.current = isReady; if (gate.current && prev.current.length !== 0) { fn(...prev.current); prev.current = []; } }, [isReady, fn]); useEffect(() => { gate.current ? fn(...compared) : (prev.current = compared); }, [compared, fn]); function depsChanged(prev, next) { return next.some((item, i) => prev[i] !== item); } } function App() { const [saved, setSaved] = useState(""); const [string, setString] = useState("hello"); const [ready, setReady] = useState(false); const callback = useCallback(dep => { console.log(dep); setString(dep); }, []); useGatedEffect(callback, [saved], ready); return ( <div> <h1>{string}</h1> <input type="text" onChange={e => setSaved(e.target.value)} /> <button onClick={() => setReady(!ready)}> Set Ready: {(!ready).toString()} </button> </div> ); } ReactDOM.render(<App/>, document.getElementById('root')); ``` ```html <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <div id="root"></div> ```
Try splitting the useEffect in this case for each state, just an idea based on your codes ``` useEffect(() => { // your codes here if (!isTrue) { return; } }, [isTrue]); useEffect(() => { // your another set of codes here someFunction(dep); }, [dep]) ```
66,015,125
I am running python3.9 on ubuntu 18.04. I already went ahead and rand the command `sudo apt-get install python-scipy` and got the message: ``` Reading package lists... Done Building dependency tree Reading state information... Done python-scipy is already the newest version (0.19.1-2ubuntu1). The following packages were automatically installed and are no longer required: linux-hwe-5.4-headers-5.4.0-42 linux-hwe-5.4-headers-5.4.0-53 linux-hwe-5.4-headers-5.4.0-56 linux-hwe-5.4-headers-5.4.0-58 linux-hwe-5.4-headers-5.4.0-59 linux-hwe-5.4-headers-5.4.0-60 Use 'sudo apt autoremove' to remove them. 0 upgraded, 0 newly installed, 0 to remove and 12 not upgraded. ``` Yet, when I try to run my python3.9 code which uses `from scipy import integrate`, I get the error: ``` ModuleNotFoundError: No module named 'scipy' ``` I already read this [post](https://stackoverflow.com/questions/55043789/importerror-no-module-named-scipy-sparse/55043942) and tried uninstalling and installing scipy using ``` sudo apt-get install python3-scipy ``` But this did not work. Any suggestions? **Edit 1**: I tried `sudo pip3 install scipy` which produced the message: ``` The directory '/home/nick/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/nick/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. ``` Yet, when I tried to run the code again, I still get the same `ImportError`.
2021/02/02
[ "https://Stackoverflow.com/questions/66015125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13972346/" ]
Maybe try ```sh python3.9 -m pip install scipy --user ``` which would use pip of python3.9 to install the package to a place without sudo privilege
Try `pip3 install scipy`, if that returns an `ERRNO 13: access denied` then try `pip3 install scipy --user`
66,015,125
I am running python3.9 on ubuntu 18.04. I already went ahead and rand the command `sudo apt-get install python-scipy` and got the message: ``` Reading package lists... Done Building dependency tree Reading state information... Done python-scipy is already the newest version (0.19.1-2ubuntu1). The following packages were automatically installed and are no longer required: linux-hwe-5.4-headers-5.4.0-42 linux-hwe-5.4-headers-5.4.0-53 linux-hwe-5.4-headers-5.4.0-56 linux-hwe-5.4-headers-5.4.0-58 linux-hwe-5.4-headers-5.4.0-59 linux-hwe-5.4-headers-5.4.0-60 Use 'sudo apt autoremove' to remove them. 0 upgraded, 0 newly installed, 0 to remove and 12 not upgraded. ``` Yet, when I try to run my python3.9 code which uses `from scipy import integrate`, I get the error: ``` ModuleNotFoundError: No module named 'scipy' ``` I already read this [post](https://stackoverflow.com/questions/55043789/importerror-no-module-named-scipy-sparse/55043942) and tried uninstalling and installing scipy using ``` sudo apt-get install python3-scipy ``` But this did not work. Any suggestions? **Edit 1**: I tried `sudo pip3 install scipy` which produced the message: ``` The directory '/home/nick/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/nick/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. ``` Yet, when I tried to run the code again, I still get the same `ImportError`.
2021/02/02
[ "https://Stackoverflow.com/questions/66015125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13972346/" ]
Maybe try ```sh python3.9 -m pip install scipy --user ``` which would use pip of python3.9 to install the package to a place without sudo privilege
use pipwin ``` pip install pipwin ``` after download ``` pipwin install scipy ```
66,015,125
I am running python3.9 on ubuntu 18.04. I already went ahead and rand the command `sudo apt-get install python-scipy` and got the message: ``` Reading package lists... Done Building dependency tree Reading state information... Done python-scipy is already the newest version (0.19.1-2ubuntu1). The following packages were automatically installed and are no longer required: linux-hwe-5.4-headers-5.4.0-42 linux-hwe-5.4-headers-5.4.0-53 linux-hwe-5.4-headers-5.4.0-56 linux-hwe-5.4-headers-5.4.0-58 linux-hwe-5.4-headers-5.4.0-59 linux-hwe-5.4-headers-5.4.0-60 Use 'sudo apt autoremove' to remove them. 0 upgraded, 0 newly installed, 0 to remove and 12 not upgraded. ``` Yet, when I try to run my python3.9 code which uses `from scipy import integrate`, I get the error: ``` ModuleNotFoundError: No module named 'scipy' ``` I already read this [post](https://stackoverflow.com/questions/55043789/importerror-no-module-named-scipy-sparse/55043942) and tried uninstalling and installing scipy using ``` sudo apt-get install python3-scipy ``` But this did not work. Any suggestions? **Edit 1**: I tried `sudo pip3 install scipy` which produced the message: ``` The directory '/home/nick/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/nick/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. ``` Yet, when I tried to run the code again, I still get the same `ImportError`.
2021/02/02
[ "https://Stackoverflow.com/questions/66015125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13972346/" ]
use pipwin ``` pip install pipwin ``` after download ``` pipwin install scipy ```
Try `pip3 install scipy`, if that returns an `ERRNO 13: access denied` then try `pip3 install scipy --user`
31,568,936
I am using Selenium webdriver with firefox. I am wondering if there is a setting i can change such that it to only requesting resources from certain domains. (Specifically i want it only to request content which is on the same domain as the webpage itself). My current set up, written in Python, is: ```python from selenium import webdriver firefox_profile = webdriver.FirefoxProfile() ## Here, I change various default setting in Firefox, and install a couple of monitoring extensions driver = webdriver.Firefox(firefox_profile) driver.get(web_address) ``` What i want to do, is if i specify the web address `wwww.domain.com`, then to only load content served by `domain.com`, and not e.g. all the tracking content hosted by other domains that would typically be requested. Hoping could be achieved by a change to the profile settings in firefox, or via an extension. Note - there is a similar question (without an answer) - [Restricting Selenium/Webdriver/HtmlUnit to a certain domain](https://stackoverflow.com/questions/6468624/restricting-selenium-webdriver-htmlunit-to-a-certain-domain) - but it is four years old, and i think Selenium has evolved a lot since then.
2015/07/22
[ "https://Stackoverflow.com/questions/31568936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2801069/" ]
With thanks to Vicky, (who's approach of using Proxy settings i followed - although directly from Selenium), the code below will change the proxy settings in firefox such that it will not connect to a domain except that on the white-list. I suspect several setting changes are unnecessary and can be omitted for most purposes. Code in Python. ```py from selenium import webdriver firefox_profile = webdriver.FirefoxProfile() ## replace desired_domain.com below with whitelisted domain. Separate domains by comma. firefox_profile.set_preference("network.proxy.no_proxies_on","localhost,127.0.0.1,desired_domain.com") firefox_profile.set_preference("network.proxy.backup.ftp","0.0.0.0") firefox_profile.set_preference("network.proxy.backup.ftp_port",1) firefox_profile.set_preference("network.proxy.backup.socks","0.0.0.0") firefox_profile.set_preference("network.proxy.backup.socks_port",1) firefox_profile.set_preference("network.proxy.backup.ssl","0.0.0.0") firefox_profile.set_preference("network.proxy.backup.ssl_port",1) firefox_profile.set_preference("network.proxy.ftp","0.0.0.0") firefox_profile.set_preference("network.proxy.ftp_port",1) firefox_profile.set_preference("network.proxy.http","0.0.0.0") firefox_profile.set_preference("network.proxy.http_port",1) firefox_profile.set_preference("network.proxy.socks","0.0.0.0") firefox_profile.set_preference("network.proxy.socks_port",1) firefox_profile.set_preference("network.proxy.ssl","0.0.0.0") firefox_profile.set_preference("network.proxy.ssl_port",1) firefox_profile.set_preference("network.proxy.type",1) firefox_profile.set_preference("network.proxy.share_proxy_settings",True) driver = webdriver.Firefox(firefox_profile) driver.get(web_address_desired) ```
I think it is still impossible in selenium.But you can still achieve this by using proxies like browsermob. Webdriver integrates well with [browsermob](https://github.com/lightbody/browsermob-proxy) proxy. **Sample pseudeocode in java** ```java //LittleProxy-powered 2.1.0 release LegacyProxyServer server = new BrowserMobProxyServer(); server.start(0); // Blacklist websites server.blacklistRequests("https?://.*\\.blocksite\\.com/.*", 410);//these sites will be blocked /// get the Selenium proxy object Proxy proxy = ClientUtil.createSeleniumProxy(server); // configure it as a desired capability DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(CapabilityType.PROXY, proxy); // initialize the driver with the capabilities ; Webdriver driver = new FirefoxDriver(capabilities); ``` Hope this helps you.Kindly get back if you need any further help
61,424,762
I am a beginner in python. I am currently building an online video study website like Udemy and Treehouse using Flask. The little issue is that, the videos on the site can be downloaded by viewing or inspecting the source code. Browsers with video download extension (firefox, Chrome etc) can easily download videos when the video page loads. The HTML and python codes are shown below ``` <video id="videoElementID" width="100%" oncontextmenu="return false;" controlsList="nodownload" controls> <source src="{{ videoclip }}" id="video" type="video/mp4"> </video> ``` ``` @posts.route("/<int:post_id>/<int:chapters_id>/<int:video_id>", methods=['GET','POST']) @login_required def view_videos(post_id, chapters_id, video_id): posts=Post.query.get_or_404(post_id) if posts.author != current_user: abort(403) chapters=C.query.get_or_404(chapters_id) videos=V.query.get_or_404(video_id) videoclip = url_for('static', filename='stylesheets/v_uploads/' + posts.author.username + '/' + posts.course_name + '/' + videos.video_file) return render_template('video.html', title="view video: ", videoclip=videoclip, posts=posts, chapters = chapters, videos=videos) ``` This is what I want: 1. to prevent browsers with file download extension from downloading the videos on the site 2. to hide the video url from the source code maybe by encrypting the path or the filename or the video itself 3. or more... I have tried .htaccess but i think it only works with PHP. I tried to encrypt the code but i couldn't do it successfully. I have checked stackoverflow questions, but wasn't successful. I know its impossible to completely stop viewers from downloading but i just want to make it harder to download. Please I really need you guys to help me out. Thanks
2020/04/25
[ "https://Stackoverflow.com/questions/61424762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12172995/" ]
I don't think the problem comes from the flask side, but from the frontend side. So you might check if this is possible through javascript. I quickly looked into it and saw the question below: I think you are facing a problem related to that mentioned in - [Prevent HTML5 video from being downloaded (right-click saved)?](https://stackoverflow.com/questions/9756837/prevent-html5-video-from-being-downloaded-right-click-saved) this article.
You have a couple of options here to make it more difficult, in order of difficulty: 1. You absolutely can use .htaccess (it is a web server feature--nothing to do with PHP) to require the referrer to be your site. Don't allow access to the video file if the referrer doesn't contain your site. ([See here for how to do this in Apache or Nginx](https://geekflare.com/block-unwanted-requests/)) 2. Use the canvas technique [described here](https://stackoverflow.com/questions/41703555/prevent-downloading-videos-in-temp-folder-while-watching-videos-in-web-browser) 3. HTTP live streaming ([For example with Nginx](https://www.nginx.com/products/nginx/modules/rtmp-media-streaming/)) 4. Use [CSRF tokens](https://portswigger.net/web-security/csrf/tokens)
58,487,038
I have a `while` loop that exits when an `if(condition){break;}` is met, after an unknown number of iterations. Inside the `while` loop, a function is called, that will return an array of variable size at every iteration. I know in `python` I could just append the arrays one to each other, and in the end I would have an array of arrays of variable size. What is the right approach to do it in `C`? Here is the relevant part of my code (I know it is not a MWE, many parts are missing, but I hope it is still understandable): ``` int find_zeros(double *kappa, double *zeros){ // reset the counter "z" int z = 0; // do some calculations and compute the zeros // update the value of z for every zero found // "zeros" now contains "z" elements return z; } double *foo(){ // allocate memory for the "zeros" array (I know that N>z) double *zeros = (double *) malloc (sizeof(double) *N); // variable to count the elements of the "zeros" array int z; while (1){ z = find_zeros(kappa, zeros); // if no zeros where found, exit the while loop if (z==0){ break; } // now we know how many zeros we have (z has been updated // by find_zeros()), so we can reallocate the memory zeros = (double *) realloc(zeros, sizeof(double) *z); // append the zeros somewhere (how?!) // in python I would do: zeros_list.append(zeros) } // free the memory for the "zeros" array free(zeros); // return all the zeros found // in python I would do: return zeros_list } int main(){ double *zeros_list = what?? // how do I allocate memory of a thing that I don't // know how big it is going to be? zeros_list = foo(); } ```
2019/10/21
[ "https://Stackoverflow.com/questions/58487038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9104884/" ]
You need to store store the zeros in `foo` independently from the values returned by `find_zeros`, as you would in Python, where you'd have separate variables `zeros_list` and `zeros`. Python's `list.append` method is realized in two steps: first the array is reallocated to new capacity with `realloc` (you already have that part), and then the new value is assigned to the newly available space. Since you are creating an array of arrays, you also need to copy the values from their temporary location to the new one with `memcpy()`. For example (untested, in absence of a MWE): ``` struct floatvec { double *values; int length; } struct floatvec *foo(int *howmany) { struct floatvec *zeros_list = NULL; int zeros_cnt = 0; static double zeros[N]; while (1) { int z = find_zeros(kappa, zeros); if (z == 0) break; struct floatvec new = { .values = malloc(z * sizeof(double)), .length = z }; if (!new.values) return NULL; memcpy(new.values, zeros, sizeof(double) * z); zeros_list = realloc(zeros_list, sizeof(struct floatvec) * (zeros_cnt + 1)); if (!zeros_list) return NULL; zeros_list[zeros_cnt++] = new; } *howmany = zeros_cnt; return zeros_list; } ``` Usage example: ``` int cnt; struct floatvec *all_zeros = foo(&cnt); for (int i = 0; i < cnt; i++) { struct floatvec *curr = all_zeros[i]; for (int j = 0; j < curr->length; j++) printf("%lf\n", curr->values[j]); } ``` A couple of unrelated notes: * don't cast the result of [`malloc` and `realloc`](https://stackoverflow.com/a/605858/1600898). * check whether `malloc` returned NULL and abort your program or make an error return to the caller. **EDIT**: updated the answer to match the edited question.
regarding your question: *// append the zeros somewhere (how?!)* the easiest way is a call to `memcpy()` similar to: ``` memcpy( &zeros[ last used offset ], newXeros, sizeof( newzeros ) ); ```
35,241,760
I'm running this every minute to debug and it keeps returning with `com.apple.xpc.launchd[1] (com.me.DesktopChanger[16390]): Service exited with abnormal code: 2` ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <!-- The label should be the same as the filename without the extension --> <string>com.me.DesktopChanger</string> <!-- Specify how to run your program here --> <key>ProgramArguments</key> <array> <string>/usr/bin/python</string> <string>~/Library/Application\ Support/DesktopChanger/DesktopChanger.py</string> </array> <key>StartInterval</key> <integer>60</integer> </dict> </plist> ``` The launchd script is called: `com.me.DesktopChanger.plist` The python script is located at: `/Users/Tom/Library/Application Support/DesktopChanger/DesktopChanger.py` and `which python` returns: `/usr/bin/python` running `ls -l` also returns: `-rw-r--r--@ 1 Tom staff 623 6 Feb 13:40 com.me.DesktopChanger.plist` and the python script with `ls -l` shows: `-rwxr-xr-x@ 1 Tom staff 672 2 Dec 14:24 DesktopChanger.py`
2016/02/06
[ "https://Stackoverflow.com/questions/35241760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3042759/" ]
You can use the `reduce` method. ``` let placeNames = results.reduce("") { (placeNames, place) -> String in return placeNames + place.name + " " } ``` Now you have a single `String` with the concatenation of all the place names. Short notation -------------- You can also write it as follow ``` let placeNames = results.reduce("") { $0 + $1.name + " " } ``` Example ------- Lets say `Place` is defined as follow (I am using a `Struct` however a `Class` does work as well) ``` struct Place { let name: String } ``` Now let's define `results` as an array of `Place(s)` ``` let results = [Place(name: "Italy"), Place(name: "UK"), Place(name: "USA")] ``` And finally let's test the code ``` let placeNames = results.reduce("") { $0 + " " + $1.name } print(placeNames) // "Italy UK USA " ``` Removing the last blank space ----------------------------- You maybe have noticed that a blank space is appended at the and of the generated `String`. We can get rid of that updating the code as follow ``` let placeNames = String( places .reduce("") { $0 + $1.name + " " } .characters .dropLast() ) ``` Why this solution is better then a for loop? -------------------------------------------- The code I am suggesting here does follow the **Functional Programming** paradigm. There are several advantages over the classic for loop: 1. It's thread safe: since I am only using immutable values you don't have to worry about other threads that could change your values while you are using them. 2. It's less error prone because it's more declarative: we are describing how the result should be, not how to build it. That's it :)
You can do it without a loop: (the '$0' is the argument in the closure) ``` results.forEach{ print($0, terminator:" ") } ```
35,241,760
I'm running this every minute to debug and it keeps returning with `com.apple.xpc.launchd[1] (com.me.DesktopChanger[16390]): Service exited with abnormal code: 2` ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <!-- The label should be the same as the filename without the extension --> <string>com.me.DesktopChanger</string> <!-- Specify how to run your program here --> <key>ProgramArguments</key> <array> <string>/usr/bin/python</string> <string>~/Library/Application\ Support/DesktopChanger/DesktopChanger.py</string> </array> <key>StartInterval</key> <integer>60</integer> </dict> </plist> ``` The launchd script is called: `com.me.DesktopChanger.plist` The python script is located at: `/Users/Tom/Library/Application Support/DesktopChanger/DesktopChanger.py` and `which python` returns: `/usr/bin/python` running `ls -l` also returns: `-rw-r--r--@ 1 Tom staff 623 6 Feb 13:40 com.me.DesktopChanger.plist` and the python script with `ls -l` shows: `-rwxr-xr-x@ 1 Tom staff 672 2 Dec 14:24 DesktopChanger.py`
2016/02/06
[ "https://Stackoverflow.com/questions/35241760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3042759/" ]
You can use the `reduce` method. ``` let placeNames = results.reduce("") { (placeNames, place) -> String in return placeNames + place.name + " " } ``` Now you have a single `String` with the concatenation of all the place names. Short notation -------------- You can also write it as follow ``` let placeNames = results.reduce("") { $0 + $1.name + " " } ``` Example ------- Lets say `Place` is defined as follow (I am using a `Struct` however a `Class` does work as well) ``` struct Place { let name: String } ``` Now let's define `results` as an array of `Place(s)` ``` let results = [Place(name: "Italy"), Place(name: "UK"), Place(name: "USA")] ``` And finally let's test the code ``` let placeNames = results.reduce("") { $0 + " " + $1.name } print(placeNames) // "Italy UK USA " ``` Removing the last blank space ----------------------------- You maybe have noticed that a blank space is appended at the and of the generated `String`. We can get rid of that updating the code as follow ``` let placeNames = String( places .reduce("") { $0 + $1.name + " " } .characters .dropLast() ) ``` Why this solution is better then a for loop? -------------------------------------------- The code I am suggesting here does follow the **Functional Programming** paradigm. There are several advantages over the classic for loop: 1. It's thread safe: since I am only using immutable values you don't have to worry about other threads that could change your values while you are using them. 2. It's less error prone because it's more declarative: we are describing how the result should be, not how to build it. That's it :)
If you want the put the results right into one string you can do: ``` let results = (try? myContext.executeFetchRequest(fetchRequest)) as? [Places] ?? [] let places = results.flatMap { $0.name }.joinWithSeparator(" ") ```
35,241,760
I'm running this every minute to debug and it keeps returning with `com.apple.xpc.launchd[1] (com.me.DesktopChanger[16390]): Service exited with abnormal code: 2` ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <!-- The label should be the same as the filename without the extension --> <string>com.me.DesktopChanger</string> <!-- Specify how to run your program here --> <key>ProgramArguments</key> <array> <string>/usr/bin/python</string> <string>~/Library/Application\ Support/DesktopChanger/DesktopChanger.py</string> </array> <key>StartInterval</key> <integer>60</integer> </dict> </plist> ``` The launchd script is called: `com.me.DesktopChanger.plist` The python script is located at: `/Users/Tom/Library/Application Support/DesktopChanger/DesktopChanger.py` and `which python` returns: `/usr/bin/python` running `ls -l` also returns: `-rw-r--r--@ 1 Tom staff 623 6 Feb 13:40 com.me.DesktopChanger.plist` and the python script with `ls -l` shows: `-rwxr-xr-x@ 1 Tom staff 672 2 Dec 14:24 DesktopChanger.py`
2016/02/06
[ "https://Stackoverflow.com/questions/35241760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3042759/" ]
You can use the `reduce` method. ``` let placeNames = results.reduce("") { (placeNames, place) -> String in return placeNames + place.name + " " } ``` Now you have a single `String` with the concatenation of all the place names. Short notation -------------- You can also write it as follow ``` let placeNames = results.reduce("") { $0 + $1.name + " " } ``` Example ------- Lets say `Place` is defined as follow (I am using a `Struct` however a `Class` does work as well) ``` struct Place { let name: String } ``` Now let's define `results` as an array of `Place(s)` ``` let results = [Place(name: "Italy"), Place(name: "UK"), Place(name: "USA")] ``` And finally let's test the code ``` let placeNames = results.reduce("") { $0 + " " + $1.name } print(placeNames) // "Italy UK USA " ``` Removing the last blank space ----------------------------- You maybe have noticed that a blank space is appended at the and of the generated `String`. We can get rid of that updating the code as follow ``` let placeNames = String( places .reduce("") { $0 + $1.name + " " } .characters .dropLast() ) ``` Why this solution is better then a for loop? -------------------------------------------- The code I am suggesting here does follow the **Functional Programming** paradigm. There are several advantages over the classic for loop: 1. It's thread safe: since I am only using immutable values you don't have to worry about other threads that could change your values while you are using them. 2. It's less error prone because it's more declarative: we are describing how the result should be, not how to build it. That's it :)
I wanted to specify 2 things FRP === You can use function style on sequence types. In this can you want to transform an array of `Places` in a array of `name` of the places. To do that you can use the `map` function. `places.map{$0.name}` will returns an array of name. As name is optional, use `flatMap` instead that strip out `nil` values `let string = places.flatMap{$0.name}.joinWithSeparator(", ")` Error throwing -------------- You are using `as!` to cast. You won't be able to recover error if this fails. You may want to add a security in your code, in a simple manner. ### Throwing unwraping You can declare a function that throws an error when unwrapping. ``` enum UnwrapError: ErrorType { case Failed } func unwrap<A>(optional: A?) throws -> A { guard let unwrap = optional else { throw UnwrapError.Failed } return unwrap } do { let results = try unwrap(myContext.executeFetchRequest(fetchRequest) as? [Places]) print(places.flatMap{$0.name}.joinWithSeparator(", ")) } catch let error as NSError { // failure print("Fetch failed: \(error.localizedDescription)") } ``` Then you may want to unit test your `fetchRequest` to check that it returns `[Places]`
35,241,760
I'm running this every minute to debug and it keeps returning with `com.apple.xpc.launchd[1] (com.me.DesktopChanger[16390]): Service exited with abnormal code: 2` ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <!-- The label should be the same as the filename without the extension --> <string>com.me.DesktopChanger</string> <!-- Specify how to run your program here --> <key>ProgramArguments</key> <array> <string>/usr/bin/python</string> <string>~/Library/Application\ Support/DesktopChanger/DesktopChanger.py</string> </array> <key>StartInterval</key> <integer>60</integer> </dict> </plist> ``` The launchd script is called: `com.me.DesktopChanger.plist` The python script is located at: `/Users/Tom/Library/Application Support/DesktopChanger/DesktopChanger.py` and `which python` returns: `/usr/bin/python` running `ls -l` also returns: `-rw-r--r--@ 1 Tom staff 623 6 Feb 13:40 com.me.DesktopChanger.plist` and the python script with `ls -l` shows: `-rwxr-xr-x@ 1 Tom staff 672 2 Dec 14:24 DesktopChanger.py`
2016/02/06
[ "https://Stackoverflow.com/questions/35241760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3042759/" ]
If you want the put the results right into one string you can do: ``` let results = (try? myContext.executeFetchRequest(fetchRequest)) as? [Places] ?? [] let places = results.flatMap { $0.name }.joinWithSeparator(" ") ```
You can do it without a loop: (the '$0' is the argument in the closure) ``` results.forEach{ print($0, terminator:" ") } ```
35,241,760
I'm running this every minute to debug and it keeps returning with `com.apple.xpc.launchd[1] (com.me.DesktopChanger[16390]): Service exited with abnormal code: 2` ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <!-- The label should be the same as the filename without the extension --> <string>com.me.DesktopChanger</string> <!-- Specify how to run your program here --> <key>ProgramArguments</key> <array> <string>/usr/bin/python</string> <string>~/Library/Application\ Support/DesktopChanger/DesktopChanger.py</string> </array> <key>StartInterval</key> <integer>60</integer> </dict> </plist> ``` The launchd script is called: `com.me.DesktopChanger.plist` The python script is located at: `/Users/Tom/Library/Application Support/DesktopChanger/DesktopChanger.py` and `which python` returns: `/usr/bin/python` running `ls -l` also returns: `-rw-r--r--@ 1 Tom staff 623 6 Feb 13:40 com.me.DesktopChanger.plist` and the python script with `ls -l` shows: `-rwxr-xr-x@ 1 Tom staff 672 2 Dec 14:24 DesktopChanger.py`
2016/02/06
[ "https://Stackoverflow.com/questions/35241760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3042759/" ]
If you want the put the results right into one string you can do: ``` let results = (try? myContext.executeFetchRequest(fetchRequest)) as? [Places] ?? [] let places = results.flatMap { $0.name }.joinWithSeparator(" ") ```
I wanted to specify 2 things FRP === You can use function style on sequence types. In this can you want to transform an array of `Places` in a array of `name` of the places. To do that you can use the `map` function. `places.map{$0.name}` will returns an array of name. As name is optional, use `flatMap` instead that strip out `nil` values `let string = places.flatMap{$0.name}.joinWithSeparator(", ")` Error throwing -------------- You are using `as!` to cast. You won't be able to recover error if this fails. You may want to add a security in your code, in a simple manner. ### Throwing unwraping You can declare a function that throws an error when unwrapping. ``` enum UnwrapError: ErrorType { case Failed } func unwrap<A>(optional: A?) throws -> A { guard let unwrap = optional else { throw UnwrapError.Failed } return unwrap } do { let results = try unwrap(myContext.executeFetchRequest(fetchRequest) as? [Places]) print(places.flatMap{$0.name}.joinWithSeparator(", ")) } catch let error as NSError { // failure print("Fetch failed: \(error.localizedDescription)") } ``` Then you may want to unit test your `fetchRequest` to check that it returns `[Places]`
18,782,620
(disclaimer: this is my first stackoverflow question so forgive me in advance if I'm not too clear) **Expected results:** My task is to find company legal identifiers in a string representing a company name, then separate them from it and save them in a separate string. The company names have already been cleaned so that they only contain alphanumeric lowercase characters. Example: ``` company_1 = 'uber wien abcd gmbh' company_2 = 'uber wien abcd g m b h' company_3 = 'uber wien abcd ges mbh' ``` should result in ``` company_1_name = 'uber wien abcd' company_1_legal = 'gmbh' company_2_name = 'uber wien abcd' company_2_legal = 'gmbh' company_3_name = 'uber wien abcd' company_3_legal = 'gesmbh' ``` **Where I am right now:** I load the list of all company ids up from a csv file. Austria provides a good example. Two legal ids are: ``` gmbh gesmbh ``` I use a regex expression that tells me **IF** the company name contains the legal identifier. However, this regex removes *all* spaces from the string in order to identify the legal id. ``` company_1_nospace = 'uberwienabcdgmbh' company_2_nospace = 'uberwienabcdgmbh' company_3_nospace = 'uberwienabcdgesmbh' ``` since I look for the regex in the string without spaces, I am able to see that all three companies have legal ids inside their name. **Where I am stuck:** I can say whether there is a legal id in `company_1`, `company_2`, and `company_3` but I can only remove it from `company_1`. In fact, I cannot remove `g m b h` because it does not match, but I can say that it is a legal id. The only way I could remove it is to also remove spaces in the rest of the company name, which I dont want to do (it would only be a last resort option) Even if I were to insert spaces into `gmbh` to match it with `g m b h`, I would then not pick up `ges mbh` or `ges m b h`. (Note that the same thing happens for other countries) **My code:** ``` import re re_code = re.compile('^gmbh|gmbh$|^gesmbh|gesmbh$') comp_id_re = re_code.search(re.sub('\s+', '', company_name)) if comp_id_re: company_id = comp_id_re.group() company_name = re.sub(re_code, '', company_name).strip() else: company_id = '' ``` Is there a way for python to *understand* which characters to remove from the original string? Or would it just be easier if somehow (that's another problem) I find all possible alternatives for legal id spacing? ie from `gmbh` I create `g mbh`, `gm bh`, `gmb h`, `g m bh`, etc... and use that for matching/extraction? I hope I have been clear enough with my explanation. Thinking about a title for this was rather difficult. **UPDATE 1:** company ids are usually at the end of the company name string. They can occasionally be at the beginning in some countries. **UPDATE 2:** I think this takes care of the company ids inside the company name. It works for legal ids at the end of the company name, but it does not work for company ids at the beginning ``` legal_regex = '^ltd|ltd$|^gmbh|gmbh$|^gesmbh|gesmbh$' def foo(name, legal_regex): #compile regex that matches company ids at beginning/end of string re_code = re.compile(legal_regex) #remove spaces name_stream = name.replace(' ','') #find regex matches for legal ids comp_id_re = re_code.search(name_stream) #save company_id, remove it from string if comp_id_re: company_id = comp_id_re.group() name_stream = re.sub(re_code, '', name_stream).strip() else: company_id = '' #restore spaced string (only works if id is at the end) name_stream_it = iter(name_stream) company_name = ''.join(next(name_stream_it) if e != ' ' else ' ' for e in name) return (company_name, company_id) ```
2013/09/13
[ "https://Stackoverflow.com/questions/18782620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2775630/" ]
Non-Regex solution would be easier here, and this is how, I would do it ``` legal_ids = """gmbh gesmbh""" def foo(name, legal_ids): #Remove all spaces from the string name_stream = name.replace(' ','') #Now iterate through the legal_ids for id in legal_ids: #Remove the legal ID's from the string name_stream = name_stream.replace(id, '') #Now Create an iterator of the modified string name_stream_it = iter(name_stream) #Fill in the missing/removed spaces return ''.join(next(name_stream_it) if e != ' ' else ' ' for e in name) foo(company_1, legal_ids.splitlines()) 'uber wien abcd ' foo(company_2, legal_ids.splitlines()) 'uber wien abcd ' foo(company_3, legal_ids.splitlines()) 'uber wien abcd ' ```
Here's the code I came up with: ``` company_1 = 'uber wien abcd gmbh' company_2 = 'uber wien abcd g m b h' company_3 = 'uber wien abcd ges mbh' legalids = ["gmbh", "gesmbh"] def info(company, legalids): for legalid in legalids: found = [] last_pos = len(company)-1 pos = len(legalid)-1 while True: if len(legalid) == len(found): newfound = found newfound.reverse() if legalid == ''.join(newfound): return [company[:last_pos+1].strip(' '), legalid] else: break if company[last_pos] == ' ': last_pos -= 1 continue elif company[last_pos] == legalid[pos]: found.append(company[last_pos]) pos -= 1 else: break last_pos -= 1 return print(info(company_1, legalids)) print(info(company_2, legalids)) print(info(company_3, legalids)) ``` Output: ``` ['uber wien abcd', 'gmbh'] ['uber wien abcd', 'gmbh'] ['uber wien abcd', 'gesmbh'] ```
18,782,620
(disclaimer: this is my first stackoverflow question so forgive me in advance if I'm not too clear) **Expected results:** My task is to find company legal identifiers in a string representing a company name, then separate them from it and save them in a separate string. The company names have already been cleaned so that they only contain alphanumeric lowercase characters. Example: ``` company_1 = 'uber wien abcd gmbh' company_2 = 'uber wien abcd g m b h' company_3 = 'uber wien abcd ges mbh' ``` should result in ``` company_1_name = 'uber wien abcd' company_1_legal = 'gmbh' company_2_name = 'uber wien abcd' company_2_legal = 'gmbh' company_3_name = 'uber wien abcd' company_3_legal = 'gesmbh' ``` **Where I am right now:** I load the list of all company ids up from a csv file. Austria provides a good example. Two legal ids are: ``` gmbh gesmbh ``` I use a regex expression that tells me **IF** the company name contains the legal identifier. However, this regex removes *all* spaces from the string in order to identify the legal id. ``` company_1_nospace = 'uberwienabcdgmbh' company_2_nospace = 'uberwienabcdgmbh' company_3_nospace = 'uberwienabcdgesmbh' ``` since I look for the regex in the string without spaces, I am able to see that all three companies have legal ids inside their name. **Where I am stuck:** I can say whether there is a legal id in `company_1`, `company_2`, and `company_3` but I can only remove it from `company_1`. In fact, I cannot remove `g m b h` because it does not match, but I can say that it is a legal id. The only way I could remove it is to also remove spaces in the rest of the company name, which I dont want to do (it would only be a last resort option) Even if I were to insert spaces into `gmbh` to match it with `g m b h`, I would then not pick up `ges mbh` or `ges m b h`. (Note that the same thing happens for other countries) **My code:** ``` import re re_code = re.compile('^gmbh|gmbh$|^gesmbh|gesmbh$') comp_id_re = re_code.search(re.sub('\s+', '', company_name)) if comp_id_re: company_id = comp_id_re.group() company_name = re.sub(re_code, '', company_name).strip() else: company_id = '' ``` Is there a way for python to *understand* which characters to remove from the original string? Or would it just be easier if somehow (that's another problem) I find all possible alternatives for legal id spacing? ie from `gmbh` I create `g mbh`, `gm bh`, `gmb h`, `g m bh`, etc... and use that for matching/extraction? I hope I have been clear enough with my explanation. Thinking about a title for this was rather difficult. **UPDATE 1:** company ids are usually at the end of the company name string. They can occasionally be at the beginning in some countries. **UPDATE 2:** I think this takes care of the company ids inside the company name. It works for legal ids at the end of the company name, but it does not work for company ids at the beginning ``` legal_regex = '^ltd|ltd$|^gmbh|gmbh$|^gesmbh|gesmbh$' def foo(name, legal_regex): #compile regex that matches company ids at beginning/end of string re_code = re.compile(legal_regex) #remove spaces name_stream = name.replace(' ','') #find regex matches for legal ids comp_id_re = re_code.search(name_stream) #save company_id, remove it from string if comp_id_re: company_id = comp_id_re.group() name_stream = re.sub(re_code, '', name_stream).strip() else: company_id = '' #restore spaced string (only works if id is at the end) name_stream_it = iter(name_stream) company_name = ''.join(next(name_stream_it) if e != ' ' else ' ' for e in name) return (company_name, company_id) ```
2013/09/13
[ "https://Stackoverflow.com/questions/18782620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2775630/" ]
I think I got to an acceptable solution. I used part of my original code, part of the code by @Abhijit and the main idea behind @wei2912 's code. Thank you all Here is the code I am going to use: ``` legal_ids = '^ltd|ltd$|^gmbh|gmbh$|^gesmbh|gesmbh$' def foo(name, legal_ids): #initialize re (company id at beginning or end of string) re_code = re.compile(legal_ids) #remove spaces from name name_stream = name.replace(' ','') #search for matches comp_id_re = re_code.search(name_stream) if comp_id_re: #match was found, extract the matching company id company_id = comp_id_re.group() #remove the id from the string without spaces name_stream = re.sub(re_code, '', name_stream).strip() if comp_id_re.start()>0: #the legal id was NOT at the beginning of the string, proceed normally name_stream_it = iter(name_stream) final_name = ''.join(next(name_stream_it) if e != ' ' else ' ' for e in name) else: #the legal id was at the beginning of the string, so do the same as above, but with the reversed strings name_stream_it = iter(name_stream[::-1]) final_name = ''.join(next(name_stream_it) if e != ' ' else ' ' for e in name[::-1]) #reverse the string to get it back to normal final_name = final_name[::-1] else: company_id = '' final_name = name return (final_name.strip(), company_id) ```
Here's the code I came up with: ``` company_1 = 'uber wien abcd gmbh' company_2 = 'uber wien abcd g m b h' company_3 = 'uber wien abcd ges mbh' legalids = ["gmbh", "gesmbh"] def info(company, legalids): for legalid in legalids: found = [] last_pos = len(company)-1 pos = len(legalid)-1 while True: if len(legalid) == len(found): newfound = found newfound.reverse() if legalid == ''.join(newfound): return [company[:last_pos+1].strip(' '), legalid] else: break if company[last_pos] == ' ': last_pos -= 1 continue elif company[last_pos] == legalid[pos]: found.append(company[last_pos]) pos -= 1 else: break last_pos -= 1 return print(info(company_1, legalids)) print(info(company_2, legalids)) print(info(company_3, legalids)) ``` Output: ``` ['uber wien abcd', 'gmbh'] ['uber wien abcd', 'gmbh'] ['uber wien abcd', 'gesmbh'] ```
51,030,872
Using Tensorflow 1.8.0, we are running into an issue whenever we attempt to build a categorical column. Here is a full example demonstrating the problem. It runs as-is (using only numeric columns). Uncommenting the indicator column definition and data generates a stack trace ending in `tensorflow.python.framework.errors_impl.InternalError: Unable to get element as bytes.` ``` import tensorflow as tf import numpy as np def feature_numeric(key): return tf.feature_column.numeric_column(key=key, default_value=0) def feature_indicator(key, vocabulary): return tf.feature_column.indicator_column( tf.feature_column.categorical_column_with_vocabulary_list( key=key, vocabulary_list=vocabulary )) labels = ['Label1','Label2','Label3'] model = tf.estimator.DNNClassifier( feature_columns=[ feature_numeric("number"), # feature_indicator("indicator", ["A","B","C"]), ], hidden_units=[64, 16, 8], model_dir='./models', n_classes=len(labels), label_vocabulary=labels) def train(inputs, training): model.train( input_fn=tf.estimator.inputs.numpy_input_fn( x=inputs, y=training, shuffle=True ), steps=1) inputs = { "number": np.array([1,2,3,4,5]), # "indicator": np.array([ # ["A"], # ["B"], # ["C"], # ["A", "A"], # ["A", "B", "C"], # ]), } training = np.array(['Label1','Label2','Label3','Label2','Label1']) train(inputs, training) ``` Attempts to use an embedding fare no better. Using only numeric inputs, we can successfully scale to thousands of input nodes, and in fact we have temporarily expanded our categorical features in the preprocessor to simulate indicators. The documentation for `categorical_column_*()` and `indicator_column()` are awash in references to features we're pretty sure we're not using (proto inputs, whatever `bytes_list` is) but maybe we're wrong on that?
2018/06/25
[ "https://Stackoverflow.com/questions/51030872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3955068/" ]
The issue here is related to the ragged shape of the "indicator" input array (some elements are of length 1, one is length 2, one is length 3). If you pad your input lists with some non-vocabulary string (I used "Z" for example since your vocabulary is "A", "B", "C"), you'll get the expected results: ``` inputs = { "number": np.array([1,2,3,4,5]), "indicator": np.array([ ["A", "Z", "Z"], ["B", "Z", "Z"], ["C", "Z", "Z"], ["A", "A", "Z"], ["A", "B", "C"] ]) } ``` You can verify that this works by printing the resulting tensor: ``` dense = tf.feature_column.input_layer( inputs, [ feature_numeric("number"), feature_indicator("indicator", ["A","B","C"]), ]) with tf.train.MonitoredTrainingSession() as sess: print(dense) print(sess.run(dense)) ```
From what I can tell, the difficulty is that you are trying to make an indicator column from an array of arrays. I collapsed your indicator array to ``` "indicator": np.array([ "A", "B", "C", "AA", "ABC", ]) ``` ... and the thing ran. More, I can't find any example where the vocabulary array is anything but a flat array of strings.
28,654,247
I want to remove the heteroatoms (HETATM)s from PDB text files that I have locally. I found a perl script that apparently needs a quick tweak to make it do what I want but I'm unsure of what that tweak is. ``` !#/usr/bin/env perl open(FILE,"file.pdb"); @file=<FILE>; foreach (@file){ if (/^HETATM/){ print $_,"\n"; }} ``` Also, if anyone has an existing perl or python script that they are OK with sharing, I would greatly appreciate it.
2015/02/22
[ "https://Stackoverflow.com/questions/28654247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4589414/" ]
In R you can use the [Bio3D package](http://thegrantlab.org/bio3d/): ``` library(bio3d) # read pdb pdb <- read.pdb("1hel") # make a subset based on TYPE new <- trim.pdb(pdb, type="ATOM") # write new pdb to disk write.pdb(new, file="1hel_ATOM.pdb") ``` This can also be combined with various other selection criteria, e.g. chain id, residue number, residue name, etc etc: ``` # select ATOM records for chain A n1 <- trim.pdb(pdb, type="ATOM", chain="A") # select residue numbers 10 through 20 n2 <- trim.pdb(pdb, resno=10:20) ```
In PERL Try this ``` use warnings; use strict; my $filename = "4BI7.pdb"; die "Error opening file" unless (open my $handler , '<' , "$filename"); open my $newfile, '>', "filename.pdb" or die "New file not create"; while($_ = <$handler>){ print $newfile "$_" unless /^HETATM.*/; } ```
57,771,019
I want to write something like this when expressed in python. ``` a = int(input()) for i in range(a): b = input() print(b) ``` And this is what I actually wrote. ``` (let [a][(read-line)] (for[i (range [a])] (defn b[string] (= (read-line) b) (println [b])))) ``` But now there are many errors.
2019/09/03
[ "https://Stackoverflow.com/questions/57771019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5237648/" ]
Similar to the Python flow. ``` (doseq [_ (range (Integer. (read-line))) :let [b (read-line)]] (println b)) ``` Even closer to Python code: ``` (let [a (Integer. (read-line))] (doseq [i (range a) :let [b (read-line)]] (println b))) ``` More functional Code ``` (mapv println (repeatedly (Integer. (read-line)) read-line)) ``` But more idiomatic (per Sean Corfield) ``` (run! println (repeatedly (Integer. (read-line)) read-line)) ```
Off the top of my head, you could do something like: `(map (fn [_] (println (read-line))) (range (Integer/parseInt (read-line))))` There may be something more appropriate than a map here, read the clojure documentation. The clojure standard library has a lot of cool stuff :) Edit: @SeanCorfield brought up a good point in the comments, using [run!](https://clojuredocs.org/clojure.core/run!) would be a better choice here since we don't care about the return value of map.
57,771,019
I want to write something like this when expressed in python. ``` a = int(input()) for i in range(a): b = input() print(b) ``` And this is what I actually wrote. ``` (let [a][(read-line)] (for[i (range [a])] (defn b[string] (= (read-line) b) (println [b])))) ``` But now there are many errors.
2019/09/03
[ "https://Stackoverflow.com/questions/57771019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5237648/" ]
Similar to the Python flow. ``` (doseq [_ (range (Integer. (read-line))) :let [b (read-line)]] (println b)) ``` Even closer to Python code: ``` (let [a (Integer. (read-line))] (doseq [i (range a) :let [b (read-line)]] (println b))) ``` More functional Code ``` (mapv println (repeatedly (Integer. (read-line)) read-line)) ``` But more idiomatic (per Sean Corfield) ``` (run! println (repeatedly (Integer. (read-line)) read-line)) ```
or this... ```clj (repeatedly (read-string (read-line)) (comp println read-line)) ```
36,267,936
Given a 2-dimensional array in python, I would like to normalize each row with the following norms: * Norm 1: **L\_1** * Norm 2: **L\_2** * Norm Inf: **L\_Inf** I have started this code: ``` from numpy import linalg as LA X = np.array([[1, 2, 3, 6], [4, 5, 6, 5], [1, 2, 5, 5], [4, 5,10,25], [5, 2,10,25]]) print X.shape x = np.array([LA.norm(v,ord=1) for v in X]) print x ``` Output: ``` (5, 4) # array dimension [12 20 13 44 42] # L1 on each Row ``` How can I modify the code such that WITHOUT using LOOP, I can directly have the rows of the matrix normalized? (Given the norm values above) I tried : ``` l1 = X.sum(axis=1) print l1 print X/l1.reshape(5,1) [12 20 13 44 42] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] ``` but the output is zero.
2016/03/28
[ "https://Stackoverflow.com/questions/36267936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4208169/" ]
This is the L₁ norm: ``` >>> np.abs(X).sum(axis=1) array([12, 20, 13, 44, 42]) ``` This is the L₂ norm: ``` >>> np.sqrt((X * X).sum(axis=1)) array([ 7.07106781, 10.09950494, 7.41619849, 27.67670501, 27.45906044]) ``` This is the L∞ norm: ``` >>> np.abs(X).max(axis=1) array([ 6, 6, 5, 25, 25]) ``` To normalise rows, just divide by the norm. For example, using L₂ normalisation: ``` >>> l2norm = np.sqrt((X * X).sum(axis=1)) >>> X / l2norm.reshape(5,1) array([[ 0.14142136, 0.28284271, 0.42426407, 0.84852814], [ 0.39605902, 0.49507377, 0.59408853, 0.49507377], [ 0.13483997, 0.26967994, 0.67419986, 0.67419986], [ 0.14452587, 0.18065734, 0.36131469, 0.90328672], [ 0.18208926, 0.0728357 , 0.36417852, 0.9104463 ]]) >>> np.sqrt((_ * _).sum(axis=1)) array([ 1., 1., 1., 1., 1.]) ``` --- More direct is the `norm` method in `numpy.linalg`, if you have it available: ``` >>> from numpy.linalg import norm >>> norm(X, axis=1, ord=1) # L-1 norm array([12, 20, 13, 44, 42]) >>> norm(X, axis=1, ord=2) # L-2 norm array([ 7.07106781, 10.09950494, 7.41619849, 27.67670501, 27.45906044]) >>> norm(X, axis=1, ord=np.inf) # L-∞ norm array([ 6, 6, 5, 25, 25]) ``` --- *(after OP edit):* You saw zero values because `/` is an integer division in Python 2.x. Either upgrade to Python 3, or change dtype to float to avoid that integer division: ``` >>> linfnorm = norm(X, axis=1, ord=np.inf) >>> X.astype(np.float) / linfnorm[:,None] array([[ 0.16666667, 0.33333333, 0.5 , 1. ], [ 0.66666667, 0.83333333, 1. , 0.83333333], [ 0.2 , 0.4 , 1. , 1. ], [ 0.16 , 0.2 , 0.4 , 1. ], [ 0.2 , 0.08 , 0.4 , 1. ]]) ```
You can pass `axis=1` parameter: ``` In [58]: LA.norm(X, axis=1, ord=1) Out[58]: array([12, 20, 13, 44, 42]) In [59]: LA.norm(X, axis=1, ord=2) Out[59]: array([ 7.07106781, 10.09950494, 7.41619849, 27.67670501, 27.45906044]) ```
28,975,468
When I run ipython notebook; I get "ImportError: IPython.html requires pyzmq >= 13" error message in console. I already run " pip install "ipython[notebook]" " but I can not run the notebook. Could you pls assist how to solve this issue. ``` C:\Python27\Scripts>ipython notebook Traceback (most recent call last): File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "C:\Python27\lib\runpy.py", line 72, in _run_code exec code in run_globals File "C:\Python27\Scripts\ipython.exe\__main__.py", line 9, in <module> File "C:\Python27\lib\site-packages\IPython\__init__.py", line 120, in start_ipython return launch_new_instance(argv=argv, **kwargs) File "C:\Python27\lib\site-packages\IPython\config\application.py", line 573, in launch_instance app.initialize(argv) File "<string>", line 2, in initialize File "C:\Python27\lib\site-packages\IPython\config\application.py", line 75, in catch_config_error return method(app, *args, **kwargs) File "C:\Python27\lib\site-packages\IPython\terminal\ipapp.py", line 321, in initialize super(TerminalIPythonApp, self).initialize(argv) File "<string>", line 2, in initialize File "C:\Python27\lib\site-packages\IPython\config\application.py", line 75, in catch_config_error return method(app, *args, **kwargs) File "C:\Python27\lib\site-packages\IPython\core\application.py", line 369, in initialize self.parse_command_line(argv) File "C:\Python27\lib\site-packages\IPython\terminal\ipapp.py", line 316, in parse_command_line return super(TerminalIPythonApp, self).parse_command_line(argv) File "<string>", line 2, in parse_command_line File "C:\Python27\lib\site-packages\IPython\config\application.py", line 75, in catch_config_error return method(app, *args, **kwargs) File "C:\Python27\lib\site-packages\IPython\config\application.py", line 471, in parse_command_line return self.initialize_subcommand(subc, subargv) File "<string>", line 2, in initialize_subcommand File "C:\Python27\lib\site-packages\IPython\config\application.py", line 75, in catch_config_error return method(app, *args, **kwargs) File "C:\Python27\lib\site-packages\IPython\config\application.py", line 402, in initialize_subcommand subapp = import_item(subapp) File "C:\Python27\lib\site-packages\IPython\utils\importstring.py", line 42, in import_item module = __import__(package, fromlist=[obj]) File "C:\Python27\lib\site-packages\IPython\html\notebookapp.py", line 29, in <module> check_for_zmq('13', 'IPython.html') File "C:\Python27\lib\site-packages\IPython\utils\zmqrelated.py", line 12, in check_for_zmq raise ImportError("%s requires pyzmq >= %s"%(required_by,minimum_version)) ImportError: IPython.html requires pyzmq >= 13 ```
2015/03/10
[ "https://Stackoverflow.com/questions/28975468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2993130/" ]
Looks like you need the pyzmq package (version >= 13). You can try installing it (or upgrading if need be) with : `pip install --upgrade pyzmq`
These works for me ( win8 + anaconda 2.7.10 ) * Uninstall zmq 4.0.4. * Install zmq 3.2.4. * pip uninstall ipython * pip install "ipython[all]" * pip uninstall pyzmq * pip install pyzmq
37,888,923
I have a datafile like this: ``` # coating file for detector A/R # column 1 is the angle of incidence (degrees) # column 2 is the wavelength (microns) # column 3 is the transmission probability # column 4 is the reflection probability 14.2000 0.531000 0.0618000 0.938200 14.2000 0.532000 0.0790500 0.920950 14.2000 0.533000 0.0998900 0.900110 # it has lots of other lines # datafile can be obtained from pastebin ``` The link to input datafile is: <http://pastebin.com/NaNbEm3E> I like to create 20 files from this input such that each files have the comments line. That is : ``` #out1.txt #comments first part of one-twentieth data # out2.txt # given comments second part of one-twentieth data # and so on upto out20.txt ``` How can we do so in python? My intitial attempt is like this: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- # Author : Bhishan Poudel # Date : May 23, 2016 # Imports from __future__ import print_function import numpy as np import pandas as pd import matplotlib.pyplot as plt # read in comments from the file infile = 'filecopy_multiple.txt' outfile = 'comments.txt' comments = [] with open(infile, 'r') as fi, open (outfile, 'a') as fo: for line in fi.readlines(): if line.startswith('#'): comments.append(line) print(line) fo.write(line) #============================================================================== # read in a file # infile = infile colnames = ['angle', 'wave','trans','refl'] print('{} {} {} {}'.format('\nreading file : ', infile, '','' )) df = pd.read_csv(infile,sep='\s+', header = None,skiprows = 0, comment='#',names=colnames,usecols=(0,1,2,3)) print('{} {} {} {}'.format('length of df : ', len(df),'','')) # write 20 files df = df nfiles = 20 nrows = int(len(df)/nfiles) groups = df.groupby( np.arange(len(df.index)) / nrows ) for (frameno, frame) in groups: frame.to_csv("output_%s.csv" % frameno,index=None, header=None,sep='\t') ``` Till now I have twenty splitted files. I just want to copy the comments lines to each of the files. But the question is: `how to do so?` There should be some easier method than creating another 20 output files with comments only and appending twenty\_splitted\_files to them. Some useful links are following: [How to split a dataframe column into multiple columns](https://stackoverflow.com/questions/18034361/how-to-split-a-dataframe-column-into-multiple-columns) [How to split a DataFrame column in python](https://stackoverflow.com/questions/34733587/how-to-split-a-dataframe-column-in-python) [Split a large pandas dataframe](https://stackoverflow.com/questions/17315737/split-a-large-pandas-dataframe)
2016/06/17
[ "https://Stackoverflow.com/questions/37888923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5200329/" ]
`inline-block` by default is `vertical-aligne`d `baseline`, and you are setting it to `middle` the first but you need to set it to `top` ```css .logo-letter-text { width: 1em; text-align: center; font-family: "Bebas Kai"; font-weight: 400; color: rgba(246, 244, 229, 1.0); } .nav-menu { position: relative; position: fixed; top: 0; width: 100%; height: 8%; background: rgba(18, 18, 18, 1.0); } .nav-menu ul { margin: 0; padding: 0; list-style-type: none; height: 100%; text-align: left; padding-left: 30px; border: 2px solid rgba(255, 255, 255, 1.0); } .nav-menu ul li { border: 2px solid rgba(255, 0, 255, 1.0); list-style-type: none; line-height: 50px; padding-left: 12px; padding-right: 12px; height: auto; display: inline-block; vertical-align: top; } .nav-menu ul li:nth-child(n+2) { color: rgba(86, 86, 86, 1.0); } .nav-menu ul li:hover { color: rgba(255, 255, 255, 1.0); } .nav-menu ul li:nth-child(1) { border: 2px solid rgba(255, 0, 0, 1.0); background: rgba(255, 102, 0, 1.0); padding: 0; margin: 0; } .nav-menu ul li:nth-child(n+2) { font-size: 40px; } ``` ```html <body class="bg-theme-main"> <nav class="nav-menu"> <ul> <li><span class="logo-letter-text">M </span><span class="logo-letter-text">B </span><span class="logo-letter-text">A </span> </li> <li><span>A</span> </li> <li><span>B</span> </li> <li><span>C</span> </li> <li><span>D</span> </li> </ul> </nav> </body> ```
Instead of using `.nav-menu ul li {display: inline-block}` Use `.nav-menu ul li {float: left;}` See fiddle <https://jsfiddle.net/4uggcyro/4/> Or another solution would be to use `display: flex;` ``` .nav-menu ul { display: flex; flex-direction: row; } ``` See fiddle <https://jsfiddle.net/4uggcyro/6/>
12,405,322
I have written a code for parallel programming in python.I am using pp module for this. job\_server = pp.Server(ncpus, ppservers=ppservers) where ncpus=8 which is no. of core in my system. python version:2.6.5. pp version:1.6.2. But I am facing an error as follows, ``` Traceback (most recent call last): File "/home/a3rmt/LIVE_ECG/file_video.py", line 613, in <module> MakeImagesThread(array_file) File "/home/a3rmt/LIVE_ECG/file_video.py", line 502, in MakeImagesThread job_server = pp.Server(ncpus, ppservers=ppservers) File "/usr/lib/pymodules/python2.6/pp.py", line 366, in __init__ raise ValueError("secret must be set using command-line option or configuration file") ValueError: secret must be set using command-line option or configuration file ```
2012/09/13
[ "https://Stackoverflow.com/questions/12405322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1372331/" ]
The theme is not used as part of the FPC uri and therefore there is only one cache per package. I wrote a little extension to fix the issue and you can grab it on Github. <https://github.com/benjy14/MobileFpcFix>
I have a feeling that the design exceptions support in Enterprise/PageCache work at the *package* level and not the *theme* level. Take a look at the code referencing design exceptions in app/code/core/Enterprise/PageCache/Model/Observer.php. My first suggestion would be to contact EE support, perhaps they can provide an appropriate solution or a patch. Alternatively, you can modify the caching key mechanism by rewriting enterprise\_pagecache/processor: ``` public function prepareCacheId($id) { $package = Mage::getDesign()->getPackageName(); $templateTheme = Mage::getDesign()->getTheme('template'); $id = $id.'_'.$package.'_'.$templateTheme; return parent::prepareCacheId($id); } ```
12,405,322
I have written a code for parallel programming in python.I am using pp module for this. job\_server = pp.Server(ncpus, ppservers=ppservers) where ncpus=8 which is no. of core in my system. python version:2.6.5. pp version:1.6.2. But I am facing an error as follows, ``` Traceback (most recent call last): File "/home/a3rmt/LIVE_ECG/file_video.py", line 613, in <module> MakeImagesThread(array_file) File "/home/a3rmt/LIVE_ECG/file_video.py", line 502, in MakeImagesThread job_server = pp.Server(ncpus, ppservers=ppservers) File "/usr/lib/pymodules/python2.6/pp.py", line 366, in __init__ raise ValueError("secret must be set using command-line option or configuration file") ValueError: secret must be set using command-line option or configuration file ```
2012/09/13
[ "https://Stackoverflow.com/questions/12405322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1372331/" ]
The theme is not used as part of the FPC uri and therefore there is only one cache per package. I wrote a little extension to fix the issue and you can grab it on Github. <https://github.com/benjy14/MobileFpcFix>
A simple solution that does not require any patching of code: Add an exception with the same regex-expression as you have in the themes-section into the package section and link it to the exact same package name as the "Current Package Name" is set to. **Prereqs:** Only one exception per section on the theme levels, e.g., `iPhone|iPad -> iphone` (and not `iPhone -> iphone` + `iPad -> iphone`) **Explanation why it works:** The enterprise page-caching is taking the package exceptions into account when generating the cacheid. It does however not check if the package names are identical! So even if the exception package is identical as the main, a different cacheid will be generated, and since the regex exceptions in the themes section are identical, they will be stored in the full page cache using the new chacheid. **Example:** In the "enterprise" package, there are 2 themes "default" and "iphone". You wish to run the theme "iphone" by adding the exception `iPhone|iPad` for the "Templates", "Skin" and "Layout" in the "Themes" subsection. In the "Package" subsection: Set "Current Package Name" to "enterprise". Add an exception to the package with `iPhone|iPad` -> "enterprise" In the "Themes" subsection: Add an exception to the "Templates" with `iPhone|iPad -> enterprise` Add an exception to the "Skin" with `iPhone|iPad -> enterprise` Add an exception to the "Layout" with `iPhone|iPad -> enterprise` Set "Default" to "default" **Note:** Do not forget to clear the FPC in System->Cache Management before testing it.
66,209,089
The problem: ------------ I have a column with a list of redundant values, which I need to be converted into a dictionary-like format in a new column of a PySpark dataframe. The scenario: Here's my PySpark dataframe: | A | C | all\_classes | | --- | --- | --- | | 10 | RDK | [1, 1, 1, 2, 2] | | 10 | USW | [1, 2, 2, 2, 2, 2, 2] | | 8 | RDK | [21, 21, 21, 21, 20] | | 8 | RDJ | [20, 20, 21] | | 10 | RDK | [45, 45, 45, 45, 2, 2, 2] | | 7 | SSW | [6, 6, 6, 19, 19] | which I created using below line: ``` my_df.groupBy(['A', 'C']).agg(collect_list("Class").alias("all_classes")) ``` Now that I want a new column that will collate data as follows: Consider the data of 1'st row from the above column: `[1, 1, 1, 2, 2]` That needs to be converted into `{1: 3, 2: 2}` which is basically the number itself and no. of times it is duplicated. My attempt: ----------- Since, I'm good with python I chose to go with writing a UDF something like this: ``` custom_collect_function = udf(lambda li: {k: li.count(k) for k in set(li)}, StructType(li, ArrayType(elementType=IntegerType()), False)) display(my_df.withColumn("Distribution", custom_collect_function(my_df.all_classes))) ``` I'm clearly failing to set the StructType here and I welcome any other/optimized approach than this. I also welcome any Spark way approach to the same. The expected output: | A | C | Distribution | all\_classes | | --- | --- | --- | --- | | 10 | RDK | {1: 3, 2: 2} | [1, 1, 1, 2, 2] | | 10 | USW | {1: 1, 2: 6} | [1, 2, 2, 2, 2, 2, 2] | | 8 | RDK | {21: 4, 20: 1} | [21, 21, 21, 21, 20] | | 8 | RDJ | {20: 2, 21: 1} | [20, 20, 21] | | 10 | RDK | {45: 4, 2: 3} | [45, 45, 45, 45, 2, 2, 2] | | 7 | SSW | {6: 3, 19: 2} | [6, 6, 6, 19, 19] |
2021/02/15
[ "https://Stackoverflow.com/questions/66209089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8046443/" ]
Just introduce extra variables: ``` int main() { int a, b; std::cin >> a >> b; const int sum = a + b; const int diff = a - b; std::cout << sum << std::endl; std::cout << diff; } ``` or use computation when needed: ``` int main() { int a, b; std::cin >> a >> b; std::cout << a + b << std::endl; std::cout << a - b; } ``` Else you have to use convoluted way which would probably be less readable.
If you want to have: ``` a = a + b b = a - b ``` in the end and not to use any other variable you can also do it like: ``` #include<iostream> using namespace std; int main() { int a,b; cin>>a>>b; a = a + b; b = a - ( 2 * b); cout<<a<<endl; cout<<b; } ``` but please note that it is not a good practice to use `using namespace std;` . instead do it like: ``` #include<iostream> int main() { int a,b; std::cin >> a >> b; a = a + b; b = a - ( 2 * b); std::cout << a << std::endl; std::cout << b << std::endl; } ```
66,209,089
The problem: ------------ I have a column with a list of redundant values, which I need to be converted into a dictionary-like format in a new column of a PySpark dataframe. The scenario: Here's my PySpark dataframe: | A | C | all\_classes | | --- | --- | --- | | 10 | RDK | [1, 1, 1, 2, 2] | | 10 | USW | [1, 2, 2, 2, 2, 2, 2] | | 8 | RDK | [21, 21, 21, 21, 20] | | 8 | RDJ | [20, 20, 21] | | 10 | RDK | [45, 45, 45, 45, 2, 2, 2] | | 7 | SSW | [6, 6, 6, 19, 19] | which I created using below line: ``` my_df.groupBy(['A', 'C']).agg(collect_list("Class").alias("all_classes")) ``` Now that I want a new column that will collate data as follows: Consider the data of 1'st row from the above column: `[1, 1, 1, 2, 2]` That needs to be converted into `{1: 3, 2: 2}` which is basically the number itself and no. of times it is duplicated. My attempt: ----------- Since, I'm good with python I chose to go with writing a UDF something like this: ``` custom_collect_function = udf(lambda li: {k: li.count(k) for k in set(li)}, StructType(li, ArrayType(elementType=IntegerType()), False)) display(my_df.withColumn("Distribution", custom_collect_function(my_df.all_classes))) ``` I'm clearly failing to set the StructType here and I welcome any other/optimized approach than this. I also welcome any Spark way approach to the same. The expected output: | A | C | Distribution | all\_classes | | --- | --- | --- | --- | | 10 | RDK | {1: 3, 2: 2} | [1, 1, 1, 2, 2] | | 10 | USW | {1: 1, 2: 6} | [1, 2, 2, 2, 2, 2, 2] | | 8 | RDK | {21: 4, 20: 1} | [21, 21, 21, 21, 20] | | 8 | RDJ | {20: 2, 21: 1} | [20, 20, 21] | | 10 | RDK | {45: 4, 2: 3} | [45, 45, 45, 45, 2, 2, 2] | | 7 | SSW | {6: 3, 19: 2} | [6, 6, 6, 19, 19] |
2021/02/15
[ "https://Stackoverflow.com/questions/66209089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8046443/" ]
Just introduce extra variables: ``` int main() { int a, b; std::cin >> a >> b; const int sum = a + b; const int diff = a - b; std::cout << sum << std::endl; std::cout << diff; } ``` or use computation when needed: ``` int main() { int a, b; std::cin >> a >> b; std::cout << a + b << std::endl; std::cout << a - b; } ``` Else you have to use convoluted way which would probably be less readable.
For starters if you are going just to output values of the expressions `a + b` and `a - b` then it is enough to write one statement as for example ``` std::cout << "a + b = " << a + b << ", a - b = " << a - b << '\n'; ``` If you indeed need to assign new values to the variables `a` and `b` then you can use for example a temporary intermediate variable. For example ``` #include <iostream> int main() { int a, b; std::cin >> a >> b; int tmp = a + b; b = a - b; a = tmp; std::cout << "a = " << a << ", b = " << b << '\n'; return 0; } ``` If to enter two values `10` and `5` then the output will be ``` a = 15, b = 5 ``` If you want to know something new about C++ then you can use the standard function [`std::exchange`](https://en.cppreference.com/w/cpp/utility/exchange) declared in the header `<utility>`. For example ``` #include <iostream> #include <utility> int main() { int a, b; std::cin >> a >> b; b = std::exchange( a, a + b ) - b; std::cout << "a = " << a << ", b = " << b << '\n'; return 0; } ``` Again if to enter the same values as above then the output will be the same ``` a = 15, b = 5 ```
66,209,089
The problem: ------------ I have a column with a list of redundant values, which I need to be converted into a dictionary-like format in a new column of a PySpark dataframe. The scenario: Here's my PySpark dataframe: | A | C | all\_classes | | --- | --- | --- | | 10 | RDK | [1, 1, 1, 2, 2] | | 10 | USW | [1, 2, 2, 2, 2, 2, 2] | | 8 | RDK | [21, 21, 21, 21, 20] | | 8 | RDJ | [20, 20, 21] | | 10 | RDK | [45, 45, 45, 45, 2, 2, 2] | | 7 | SSW | [6, 6, 6, 19, 19] | which I created using below line: ``` my_df.groupBy(['A', 'C']).agg(collect_list("Class").alias("all_classes")) ``` Now that I want a new column that will collate data as follows: Consider the data of 1'st row from the above column: `[1, 1, 1, 2, 2]` That needs to be converted into `{1: 3, 2: 2}` which is basically the number itself and no. of times it is duplicated. My attempt: ----------- Since, I'm good with python I chose to go with writing a UDF something like this: ``` custom_collect_function = udf(lambda li: {k: li.count(k) for k in set(li)}, StructType(li, ArrayType(elementType=IntegerType()), False)) display(my_df.withColumn("Distribution", custom_collect_function(my_df.all_classes))) ``` I'm clearly failing to set the StructType here and I welcome any other/optimized approach than this. I also welcome any Spark way approach to the same. The expected output: | A | C | Distribution | all\_classes | | --- | --- | --- | --- | | 10 | RDK | {1: 3, 2: 2} | [1, 1, 1, 2, 2] | | 10 | USW | {1: 1, 2: 6} | [1, 2, 2, 2, 2, 2, 2] | | 8 | RDK | {21: 4, 20: 1} | [21, 21, 21, 21, 20] | | 8 | RDJ | {20: 2, 21: 1} | [20, 20, 21] | | 10 | RDK | {45: 4, 2: 3} | [45, 45, 45, 45, 2, 2, 2] | | 7 | SSW | {6: 3, 19: 2} | [6, 6, 6, 19, 19] |
2021/02/15
[ "https://Stackoverflow.com/questions/66209089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8046443/" ]
For starters if you are going just to output values of the expressions `a + b` and `a - b` then it is enough to write one statement as for example ``` std::cout << "a + b = " << a + b << ", a - b = " << a - b << '\n'; ``` If you indeed need to assign new values to the variables `a` and `b` then you can use for example a temporary intermediate variable. For example ``` #include <iostream> int main() { int a, b; std::cin >> a >> b; int tmp = a + b; b = a - b; a = tmp; std::cout << "a = " << a << ", b = " << b << '\n'; return 0; } ``` If to enter two values `10` and `5` then the output will be ``` a = 15, b = 5 ``` If you want to know something new about C++ then you can use the standard function [`std::exchange`](https://en.cppreference.com/w/cpp/utility/exchange) declared in the header `<utility>`. For example ``` #include <iostream> #include <utility> int main() { int a, b; std::cin >> a >> b; b = std::exchange( a, a + b ) - b; std::cout << "a = " << a << ", b = " << b << '\n'; return 0; } ``` Again if to enter the same values as above then the output will be the same ``` a = 15, b = 5 ```
If you want to have: ``` a = a + b b = a - b ``` in the end and not to use any other variable you can also do it like: ``` #include<iostream> using namespace std; int main() { int a,b; cin>>a>>b; a = a + b; b = a - ( 2 * b); cout<<a<<endl; cout<<b; } ``` but please note that it is not a good practice to use `using namespace std;` . instead do it like: ``` #include<iostream> int main() { int a,b; std::cin >> a >> b; a = a + b; b = a - ( 2 * b); std::cout << a << std::endl; std::cout << b << std::endl; } ```
70,134,739
I'm new to python and would appreciate any help i can I'm looking at this code : ``` if left[0] < right[0]: result.append(left[0]) left = left[1:] elif left[0] > right[0]: result.append(right[0]) right = right[1:] max_iter -= 1 ``` it doesn't make sense what it means , its about changing the order of numbers in a sequence to ascending order but what does [0] mean?
2021/11/27
[ "https://Stackoverflow.com/questions/70134739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17303354/" ]
The `%y` code matches a two-digit year - for a four-digit year, you should use `%Y` instead. ``` date = datetime.strptime('2021-11-27 00:00', '%Y-%m-%d %H:%M') ```
as per the [documentation](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior), `%y` is > > Year without century as a zero-padded decimal number. > > > and `%Y` is > > Year with century as a decimal number. > > > so ``` from datetime import datetime date = datetime.strptime('2021-11-27 00:00', '%Y-%m-%d %H:%M') date ``` will give `datetime.datetime(2021, 11, 27, 0, 0)`
70,134,739
I'm new to python and would appreciate any help i can I'm looking at this code : ``` if left[0] < right[0]: result.append(left[0]) left = left[1:] elif left[0] > right[0]: result.append(right[0]) right = right[1:] max_iter -= 1 ``` it doesn't make sense what it means , its about changing the order of numbers in a sequence to ascending order but what does [0] mean?
2021/11/27
[ "https://Stackoverflow.com/questions/70134739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17303354/" ]
The `%y` code matches a two-digit year - for a four-digit year, you should use `%Y` instead. ``` date = datetime.strptime('2021-11-27 00:00', '%Y-%m-%d %H:%M') ```
I'm not familiar with python too much but [this documentation says](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes) `%y` is for year **without** century but `%Y` is for year **with** century: | Directive | Meaning | | --- | --- | | %y | Year without century as a zero-padded decimal number. | | %Y | Year with century as a decimal number. | So, looks like the correct format should be `%Y-%m-%d %H:%M` Here a [`demonstration`](https://ideone.com/wxMCIz). Remember, almost all programming languages have this custom specifiers and most of them are case sensitive.
60,610,009
I tried to do a choice menu, each menu make different things, for example if you choice the number 1, will work good, but if you try to choose 2 or other number, first will try to run 1, and I don't want this. Is there a way to become "independent" for each option? Example (this will work): ``` choice = input (""" 1. Make thing 1 2. Make thing 2 3. Make thing 3 4. Exit Please select your choice:""") if choice == "1": print("thing 1") if choice == "2": print("thing 2") if choice == "3": print("thing 3") if choice == "4": print("thing 4") ``` but, if 1 later has more coding, and you want to work with option 2, python will run also 1...
2020/03/10
[ "https://Stackoverflow.com/questions/60610009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13025132/" ]
Python lacks a switch/case statement (like C/C++) in which you CAN have it perform multiple (adjacent) case conditions, and then have it `break` before processing further cases. In Python you'll need to simulate using if-elif-else statements, perhaps utilizing comparison operators (like `==`, `<`) and/or boolean operators ( like `and`, `or`) in conditionals accordingly. Here's an example of a C language switch/case [switch/case in python](https://bytebaker.com/2008/11/03/switch-case-statement-in-python/): ``` switch(n) { case 0: printf("You typed zero.\n"); break; case 1: case 9: printf("n is a perfect square\n"); break; case 2: printf("n is an even number\n"); case 3: case 5: case 7: printf("n is a prime number\n"); break; case 4: printf("n is a perfect square\n"); case 6: case 8: printf("n is an even number\n"); break; default: printf("Only single-digit numbers are allowed\n"); break; } ``` Here's how you might take a first crack at simulating the switch/case in Python [switch/case in python](https://bytebaker.com/2008/11/03/switch-case-statement-in-python/): ``` if n == 0: print "You typed zero.\n" elif n == 1 or n == 9 or n == 4: print "n is a perfect square\n" elif n == 2 or n == 6 or n == 8: print "n is an even number\n" elif n == 3 or n == 5 or n == 7: print "n is a prime number\n" elif n > 9: print "Only single-digit numbers are allowed\n" ``` And here's a much better, "Pythonic" way of doing it [switch/case in python](https://bytebaker.com/2008/11/03/switch-case-statement-in-python/): ``` options = {0 : zero, 1 : sqr, 4 : sqr, 9 : sqr, 2 : even, 3 : prime, 5 : prime, 7 : prime, } def zero(): print "You typed zero.\n" def sqr(): print "n is a perfect square\n" def even(): print "n is an even number\n" def prime(): print "n is a prime number\n" options[num]() ```
Good news for you, if you are still interested in using the switch case in Python. you can now use `match` with Python 3.10 like this: ```py match n: case 0: print("You typed zero.\n") case "1": print("thing 1") case "2": print("thing 2") case "3": print("thing 3") ``` For more details read [click here to read this python documentation](https://docs.python.org/3/whatsnew/3.10.html)
40,332,032
I'm thinking about writing a desktop application that the GUI is made with either HTML or PHP, but the functions are run by a separate Java or python code, is there any heads up that I can look into?
2016/10/30
[ "https://Stackoverflow.com/questions/40332032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5517067/" ]
There are a couple of possible options: 1. Run your backend code as an embedded HTTP-server (like Jetty\* for Java or Tornado\* for Python). If the user starts the application, the backend runs the server and automatically starts the web browser with the URL of your server. This, however, may cause problems with the operating system firewall (running a server on the local machine) 2. You could also have a look at [CEF](https://en.wikipedia.org/wiki/Chromium_Embedded_Framework) (chromium embedded framework). It is made for exactly this purpose (running an HTML-Application inside your code). It uses the same codebase as the chromium (and chrome) web browser. It was developed originally for C++, but there is also a Java binding: [java-cef](https://bitbucket.org/chromiumembedded/java-cef) Oh and by the way, PHP is a server-side language. I would not recommend to use it in your scenario (since your backend code is Python or Java). \*I have not enough reputation to add more than two links, so you'll have to google those ones yourself.
You could expose data from Java or Python as JSON via GET request and use PHP to access it. There are multiple libraries for each of these languages both for writing and reading JSON. GET request can take parameters if needed.
12,311,348
I am trying to implement a class in which an attempt to access any attributes that do not exist in the current class or any of its ancestors will attempt to access those attributes from a member. Below is a trivial version of what I am trying to do. ``` class Foo: def __init__(self, value): self._value = value def __getattr__(self, name): return getattr(self._value, name) if __name__ == '__main__': print(Foo(5) > Foo(4)) # should do 5 > 4 (or (5).__gt__(4)) ``` However, this raises a `TypeError`. Even using the `operator` module's `attrgetter` class does the same thing. I was taking a look at [the documentation regarding customizing attribute access](http://docs.python.org/py3k/reference/datamodel.html?highlight=__get__#object.__getattr__), but I didn't find it an easy read. How can I get around this?
2012/09/07
[ "https://Stackoverflow.com/questions/12311348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/652722/" ]
If I understand you correctly, what you are doing is correct, but it still won't work for what you're trying to use it for. The reason is that implicit magic-method lookup does not use `__getattr__` (or `__getattribute__` or any other such thing). The methods have to actually explicitly be there with their magic names. Your approach will work for normal attributes, but not magic methods. (Note that if you do `Foo(5).__lt__(4)` explicitly, it will work; it's only the implicit "magic" lookup --- e.g., calling `__lt__` when `<` is used) --- that is blocked.) [This post](https://stackoverflow.com/questions/9057669/how-can-i-intercept-calls-to-pythons-magic-methods-in-new-style-classes) describes an approach for autogenerating magic methods using a metaclass. If you only need certain methods, you can just define them on the class manually.
`__*__` methods will not work unless they actually exist - so neither `__getattr__` nor `__getattribute__` will allow you to proxy those calls. You must create every single methods manually. Yes, this does involve quite a bit of copy&paste. And yes, it's perfectly fine in this case. You might be able to use the [werkzeug LocalProxy](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/local.py#L248) class as a base or instead of your own class; your code would look like this when using `LocalProxy`: ``` print(LocalProxy(lambda: 5) > LocalProxy(lambda: 4)) ```
3,905,179
I'm struggling with setting my scons environment variables for visual studio 2008. Normally I do following: ``` %VS90COMNTOOLS%vsvars32.bat or call %VS90COMNTOOLS%vsvars32.bat ``` And this works in my shell. I try to do that in python using subprocess ``` subprocess.call([os.environ['VS90COMNTOOLS']+r"\vsvars32.bat"]) ``` output: ``` d:\N\workspace>scons test scons: Reading SConscript files ... Setting environment for using Microsoft Visual Studio 2008 x86 tools. KeyError: 'INCLUDE': ``` above invokes batch process, but environment variables are not inherited from it to my 'master process. When i use: ``` subprocess.call([os.environ['VS90COMNTOOLS']+r"\vsvars32.bat"]) ``` I get: ``` d:\N\workspace>scons test scons: Reading SConscript files ... WindowsError: [Error 2] The system cannot find the file specified: File "D:\N\workspace\SConstruct", line 17: subprocess.Popen(["call ", os.environ['VS90COMNTOOLS']+r"\vsvars32.bat"]) File "C:\Python26\lib\subprocess.py", line 595: errread, errwrite) File "C:\Python26\lib\subprocess.py", line 821: startupinfo) ``` How to achieve that?
2010/10/11
[ "https://Stackoverflow.com/questions/3905179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112496/" ]
Write a batch file that runs `vsvars32.bat` and then outputs the values in the form `VARNAME=value`, then have your Python script parse the values and inject them into `os.environ`. This is done in python's own distutils module, [see the source here](http://hg.python.org/distutils2/file/0291648eb2b2/distutils2/compiler/msvc9compiler.py#l239).
In addition to the previous answer. An excerpt of my SConstruct: ``` for key in ['INCLUDE','LIB']: if os.environ.has_key(key): env.Prepend(ENV = {key.upper():os.environ[key]}) ``` Please take care that variable names in Python are case-sensitive. Ensure that your `env['ENV']` dict has no duplicate variable names with different case, otherwise the Windows shell will only see one variant of the variable.
3,905,179
I'm struggling with setting my scons environment variables for visual studio 2008. Normally I do following: ``` %VS90COMNTOOLS%vsvars32.bat or call %VS90COMNTOOLS%vsvars32.bat ``` And this works in my shell. I try to do that in python using subprocess ``` subprocess.call([os.environ['VS90COMNTOOLS']+r"\vsvars32.bat"]) ``` output: ``` d:\N\workspace>scons test scons: Reading SConscript files ... Setting environment for using Microsoft Visual Studio 2008 x86 tools. KeyError: 'INCLUDE': ``` above invokes batch process, but environment variables are not inherited from it to my 'master process. When i use: ``` subprocess.call([os.environ['VS90COMNTOOLS']+r"\vsvars32.bat"]) ``` I get: ``` d:\N\workspace>scons test scons: Reading SConscript files ... WindowsError: [Error 2] The system cannot find the file specified: File "D:\N\workspace\SConstruct", line 17: subprocess.Popen(["call ", os.environ['VS90COMNTOOLS']+r"\vsvars32.bat"]) File "C:\Python26\lib\subprocess.py", line 595: errread, errwrite) File "C:\Python26\lib\subprocess.py", line 821: startupinfo) ``` How to achieve that?
2010/10/11
[ "https://Stackoverflow.com/questions/3905179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112496/" ]
Write a batch file that runs `vsvars32.bat` and then outputs the values in the form `VARNAME=value`, then have your Python script parse the values and inject them into `os.environ`. This is done in python's own distutils module, [see the source here](http://hg.python.org/distutils2/file/0291648eb2b2/distutils2/compiler/msvc9compiler.py#l239).
A short code (Python 3) addition to the accepted answer: ```py def vs_env_dict(): vsvar32 = '{vscomntools}vsvars32.bat'.format(vscomntools=os.environ['VS140COMNTOOLS']) cmd = [vsvar32, '&&', 'set'] popen = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = popen.communicate() if popen.wait() != 0: raise ValueError(stderr.decode("mbcs")) output = stdout.decode("mbcs").split("\r\n") return dict((e[0].upper(), e[1]) for e in [p.rstrip().split("=", 1) for p in output] if len(e) == 2) os.environ.update(vs_env_dict()) ``` It works for me!
24,024,920
I have a python script which runs a fabfile. My issue is that I am asked for a password whenever I run the fabfile from my script. However, the login works fine with the specified key when I run the fabfile manually from the command line even though I am using the same fab parameters. Here is the contents of my fabfile: ``` [root@ip-10-10-20-82 bakery]# cat fabfile.py from fabric.api import run def deploy(): run('wget -P /tmp https://s3.amazonaws.com/LinuxBakery/httpd-2.2.26-1.1.amzn1.x86_64.rpm') run('sudo yum localinstall /tmp/httpd-2.2.26-1.1.amzn1.x86_64.rpm') ``` Here is the syntax I use on the command line that works successfully: ``` fab -u ec2-user -i id_rsa -H 10.10.15.185 deploy ``` Here is the bit of python code which for some reason is prompting for a password instead of using the key: ``` import subprocess subprocess.call(['fab', '-f', '/home/myhome/scripts/bakery/fabfile.py', '-u ec2-user', '-i', '/home/myhome/scripts/bakery/id_rsa', '-H', bakery_internalip, 'deploy']) ``` Here is what happens when I run it: ``` [10.10.15.185] Executing task 'deploy' [10.10.15.185] run: wget -P /tmp https://s3.amazonaws.com/LinuxBakery/httpd-2.2.26-1.1.amzn1.x86_64.rpm [10.10.15.185] Login password for ' ec2-user': ```
2014/06/03
[ "https://Stackoverflow.com/questions/24024920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3507094/" ]
You can use [ssh-agent](http://www.openbsd.org/cgi-bin/man.cgi?query=ssh-agent&sektion=1): ``` $ eval `ssh-agent -s` $ ssh-add /home/myhome/scripts/bakery/id_rsa $ fab -H 10.10.15.185 deploy ```
I was being asked for a password even though I had specified a key because there was an extra space between the "u" and "ec2-user". Here is the snippet before: ``` '-u ec2-user' ``` And here it is after: ``` '-uec2-user' ``` The extra space meant that fab was trying to authenticate with " ec2-user" instead of "ec2-user".
70,386,636
I'm trying to load a large CSV file into Pandas, which I'm new to. The input file should have 13 columns. Howeever, Pandas is reading all of the column headings as one heading, and then just collecting the first few columns of data. The code I am using is;- leases=pd.read\_csv("/content/LEASES\_FULL\_2021\_12.csv", sep=',', delimiter=None, header=0, names=None, index\_col=False, usecols=None, squeeze=False, engine="python") The CSV is formatted as follows:- Unique Identifier,Tenure,Register Property Description,County,Region,Associated Property Description ID,Associated Property Description,OS UPRN,Price Paid,Reg Order,Date of Lease,Term,Alienation Clause Indicator "1608D08BFC5496E31C7926595EE2F1BE278ED436","Leasehold","19 Alcester Crescent, Clapton","GREATER LONDON","GREATER LONDON","501286752","19 ALCESTER CRESCENT, LONDON E5 9PX","10008240310","","2","13-02-1905","99 years from 25 December 1902","N" "5D0FA4909B7C0FD9477C2275E1948C8F135E233F","Leasehold","7 Agnes Street, Limehouse","GREATER LONDON","GREATER LONDON","3125118","7 AGNES STREET, LONDON E14 7DG","6044926","","2","16-10-1866","99 years from 24 June 1862","N" etc The Dataframe then loads with one column as follows:- [enter image description here](https://i.stack.imgur.com/mfStC.png) Any help would be greatly appreciated.
2021/12/16
[ "https://Stackoverflow.com/questions/70386636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16950273/" ]
The problem is that through type erasure, the compiler will produce the method below for your generic method. ``` public static JsonNode of(String key, Object value) { ObjectMapper objectMapper = new ObjectMapper(); ObjectNode root = objectMapper.createObjectNode(); root.put(key, value); // <== error shows up on this line return root; } ``` Per Jackson documentation, there's no such method `put(String key, Object value)`. Instead of calling the method `of(String key, T value)`, I would just do the following: ``` ObjectNode root = new ObjectMapper().createObjectNode(); root.put(key, value); ``` Or you could write write several overloaded methods `of(...)`.
There is another approach that works for any json object: ``` Map<String, Object> map = new ObjectMapper().readValue(json, new TypeReference<HashMap<String,Object>>() {}); ``` The object in the value can be any value object (`String`, `Integer`, etc), another `Map<String, Object>` as a nested object or a `List<Object>`/`List<Map<String, Object>>` and so on down to any depth.
70,386,636
I'm trying to load a large CSV file into Pandas, which I'm new to. The input file should have 13 columns. Howeever, Pandas is reading all of the column headings as one heading, and then just collecting the first few columns of data. The code I am using is;- leases=pd.read\_csv("/content/LEASES\_FULL\_2021\_12.csv", sep=',', delimiter=None, header=0, names=None, index\_col=False, usecols=None, squeeze=False, engine="python") The CSV is formatted as follows:- Unique Identifier,Tenure,Register Property Description,County,Region,Associated Property Description ID,Associated Property Description,OS UPRN,Price Paid,Reg Order,Date of Lease,Term,Alienation Clause Indicator "1608D08BFC5496E31C7926595EE2F1BE278ED436","Leasehold","19 Alcester Crescent, Clapton","GREATER LONDON","GREATER LONDON","501286752","19 ALCESTER CRESCENT, LONDON E5 9PX","10008240310","","2","13-02-1905","99 years from 25 December 1902","N" "5D0FA4909B7C0FD9477C2275E1948C8F135E233F","Leasehold","7 Agnes Street, Limehouse","GREATER LONDON","GREATER LONDON","3125118","7 AGNES STREET, LONDON E14 7DG","6044926","","2","16-10-1866","99 years from 24 June 1862","N" etc The Dataframe then loads with one column as follows:- [enter image description here](https://i.stack.imgur.com/mfStC.png) Any help would be greatly appreciated.
2021/12/16
[ "https://Stackoverflow.com/questions/70386636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16950273/" ]
If you look at the signature of the *ObjectNode#put* method you will see that ``` public JsonNode put(String fieldName, JsonNode value) ``` the second argument is actually bound to a specific type and it is `JsonNode` , not just any `T` (much like your method allows). So, because of the type erasure - the compiler has to ensure you provided a compatible type at compile time and I suggest you to put a suitable bound on the method, for example: ``` public static <T extends JsonNode> JsonNode of(String key, T value) { ObjectMapper objectMapper = new ObjectMapper(); ObjectNode root = objectMapper.createObjectNode(); root.set(key, value); return root; } ``` making sure your method accepts only JsonNode or its descendants. --- Small note 1: it is not a good thing to instantiate ObjectMapper every time the method gets called as it is a bit expensive object to create, better to make it a field. Small note 2: The method *ObjectNode#put* gets deprecated since version 2.4, and it is recommended to use *ObjectNode#set* instead.
The problem is that through type erasure, the compiler will produce the method below for your generic method. ``` public static JsonNode of(String key, Object value) { ObjectMapper objectMapper = new ObjectMapper(); ObjectNode root = objectMapper.createObjectNode(); root.put(key, value); // <== error shows up on this line return root; } ``` Per Jackson documentation, there's no such method `put(String key, Object value)`. Instead of calling the method `of(String key, T value)`, I would just do the following: ``` ObjectNode root = new ObjectMapper().createObjectNode(); root.put(key, value); ``` Or you could write write several overloaded methods `of(...)`.
70,386,636
I'm trying to load a large CSV file into Pandas, which I'm new to. The input file should have 13 columns. Howeever, Pandas is reading all of the column headings as one heading, and then just collecting the first few columns of data. The code I am using is;- leases=pd.read\_csv("/content/LEASES\_FULL\_2021\_12.csv", sep=',', delimiter=None, header=0, names=None, index\_col=False, usecols=None, squeeze=False, engine="python") The CSV is formatted as follows:- Unique Identifier,Tenure,Register Property Description,County,Region,Associated Property Description ID,Associated Property Description,OS UPRN,Price Paid,Reg Order,Date of Lease,Term,Alienation Clause Indicator "1608D08BFC5496E31C7926595EE2F1BE278ED436","Leasehold","19 Alcester Crescent, Clapton","GREATER LONDON","GREATER LONDON","501286752","19 ALCESTER CRESCENT, LONDON E5 9PX","10008240310","","2","13-02-1905","99 years from 25 December 1902","N" "5D0FA4909B7C0FD9477C2275E1948C8F135E233F","Leasehold","7 Agnes Street, Limehouse","GREATER LONDON","GREATER LONDON","3125118","7 AGNES STREET, LONDON E14 7DG","6044926","","2","16-10-1866","99 years from 24 June 1862","N" etc The Dataframe then loads with one column as follows:- [enter image description here](https://i.stack.imgur.com/mfStC.png) Any help would be greatly appreciated.
2021/12/16
[ "https://Stackoverflow.com/questions/70386636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16950273/" ]
If you look at the signature of the *ObjectNode#put* method you will see that ``` public JsonNode put(String fieldName, JsonNode value) ``` the second argument is actually bound to a specific type and it is `JsonNode` , not just any `T` (much like your method allows). So, because of the type erasure - the compiler has to ensure you provided a compatible type at compile time and I suggest you to put a suitable bound on the method, for example: ``` public static <T extends JsonNode> JsonNode of(String key, T value) { ObjectMapper objectMapper = new ObjectMapper(); ObjectNode root = objectMapper.createObjectNode(); root.set(key, value); return root; } ``` making sure your method accepts only JsonNode or its descendants. --- Small note 1: it is not a good thing to instantiate ObjectMapper every time the method gets called as it is a bit expensive object to create, better to make it a field. Small note 2: The method *ObjectNode#put* gets deprecated since version 2.4, and it is recommended to use *ObjectNode#set* instead.
There is another approach that works for any json object: ``` Map<String, Object> map = new ObjectMapper().readValue(json, new TypeReference<HashMap<String,Object>>() {}); ``` The object in the value can be any value object (`String`, `Integer`, etc), another `Map<String, Object>` as a nested object or a `List<Object>`/`List<Map<String, Object>>` and so on down to any depth.
6,866,802
Im fairly proficient in php and am also learning python. I have been wanting to create a basic game for some time now and would like to create it in python. But in order to have a fancy smooth interface I need to use javascript (i dont much care for the flash/silverlight route). So I decided to start looking up game development in JavaScript. And in doing so most of the examples I have seen are games nearly completely done in javascript. And many of these games are quite nice. But what im wondering, is if i combine python and javascript together for creating games; should I rely more heavily on javascript and let python do some of the background stuff? Or should I only use javascript for the basic UI elements, animation, flashy stuff and whatnot and keep the core game engine in python. Or some kind of mix between the two. For php/python im mostly used to MVC style frameworks. So if i used JS only for the visuals would I just make heavy use of the in the view files as I would with a normal application? I know I can make a game in either language completely, but to use the best of both worlds im not quite sure where I should draw the line on letting python do work and letting JS do the work. Also as a reference I would like to use some advanced features like canvas/svg and so on. Not really so much WebGL. And the game I have in mind to practice on is an isometric style RTS. The game will mostly be for learning. Im not really planning on releasing it. Any input is appreciated. --- Clarification: the game will be web based. My web server is nginx. The games i would like to to would be multiplayer games where multiple people are playing online at the same time. Think world of warcraft. each server could hold up to N players that play against eachother. When that one is say 80% full a new one is spun up. Or something along those lines. I would like for the players to actually be able to interact with eachother live. Which is why in same ways i was also kind of looking into node.js but dont know as much about it yet. but seemed like it could fit. -- Update: Im also planning on using mongodb as the database, if that matters to anyones answer.
2011/07/28
[ "https://Stackoverflow.com/questions/6866802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/519990/" ]
I found that splitting the collection view item view into its own XIB and then rewiring the connections so that the collection view item prototype loads the new XIB will allow for you to create the bindings in interface builder without it crashing. I followed these steps... 1. Delete the collection view item view from the default xib. 2. Create a new view and XIB inheriting from NSCollectionViewItem. 3. Create your collection view item in the new view. 4. Bind the fields to the files owner of the new view. 5. Back in the collection view xib, update the properties of collection view item to load the bin name of the new xib. I'm not sure that it's quicker than doing it programmatically, but it does allow you to manage the bindings without writing code. I've got a few apps working this way now.
Yup, I can confirm this bug too, even on Interface Builder 3. The only workaround is to do the binding programmatically: ``` [textField bind:@"value" toObject:collectionViewItem withKeyPath:@"representedObject.foo" options:nil]; ```
6,866,802
Im fairly proficient in php and am also learning python. I have been wanting to create a basic game for some time now and would like to create it in python. But in order to have a fancy smooth interface I need to use javascript (i dont much care for the flash/silverlight route). So I decided to start looking up game development in JavaScript. And in doing so most of the examples I have seen are games nearly completely done in javascript. And many of these games are quite nice. But what im wondering, is if i combine python and javascript together for creating games; should I rely more heavily on javascript and let python do some of the background stuff? Or should I only use javascript for the basic UI elements, animation, flashy stuff and whatnot and keep the core game engine in python. Or some kind of mix between the two. For php/python im mostly used to MVC style frameworks. So if i used JS only for the visuals would I just make heavy use of the in the view files as I would with a normal application? I know I can make a game in either language completely, but to use the best of both worlds im not quite sure where I should draw the line on letting python do work and letting JS do the work. Also as a reference I would like to use some advanced features like canvas/svg and so on. Not really so much WebGL. And the game I have in mind to practice on is an isometric style RTS. The game will mostly be for learning. Im not really planning on releasing it. Any input is appreciated. --- Clarification: the game will be web based. My web server is nginx. The games i would like to to would be multiplayer games where multiple people are playing online at the same time. Think world of warcraft. each server could hold up to N players that play against eachother. When that one is say 80% full a new one is spun up. Or something along those lines. I would like for the players to actually be able to interact with eachother live. Which is why in same ways i was also kind of looking into node.js but dont know as much about it yet. but seemed like it could fit. -- Update: Im also planning on using mongodb as the database, if that matters to anyones answer.
2011/07/28
[ "https://Stackoverflow.com/questions/6866802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/519990/" ]
I've found a temporary work around: Select the "Collection View Item" and under the "Attributes Inspector" → "View Controller" settings, set "Nib Name" to "MainMenu". Once you've done this, it won't crash, and you can set the bindings. Be sure to clear the "Nib Name" setting when building your app.
Yup, I can confirm this bug too, even on Interface Builder 3. The only workaround is to do the binding programmatically: ``` [textField bind:@"value" toObject:collectionViewItem withKeyPath:@"representedObject.foo" options:nil]; ```
6,866,802
Im fairly proficient in php and am also learning python. I have been wanting to create a basic game for some time now and would like to create it in python. But in order to have a fancy smooth interface I need to use javascript (i dont much care for the flash/silverlight route). So I decided to start looking up game development in JavaScript. And in doing so most of the examples I have seen are games nearly completely done in javascript. And many of these games are quite nice. But what im wondering, is if i combine python and javascript together for creating games; should I rely more heavily on javascript and let python do some of the background stuff? Or should I only use javascript for the basic UI elements, animation, flashy stuff and whatnot and keep the core game engine in python. Or some kind of mix between the two. For php/python im mostly used to MVC style frameworks. So if i used JS only for the visuals would I just make heavy use of the in the view files as I would with a normal application? I know I can make a game in either language completely, but to use the best of both worlds im not quite sure where I should draw the line on letting python do work and letting JS do the work. Also as a reference I would like to use some advanced features like canvas/svg and so on. Not really so much WebGL. And the game I have in mind to practice on is an isometric style RTS. The game will mostly be for learning. Im not really planning on releasing it. Any input is appreciated. --- Clarification: the game will be web based. My web server is nginx. The games i would like to to would be multiplayer games where multiple people are playing online at the same time. Think world of warcraft. each server could hold up to N players that play against eachother. When that one is say 80% full a new one is spun up. Or something along those lines. I would like for the players to actually be able to interact with eachother live. Which is why in same ways i was also kind of looking into node.js but dont know as much about it yet. but seemed like it could fit. -- Update: Im also planning on using mongodb as the database, if that matters to anyones answer.
2011/07/28
[ "https://Stackoverflow.com/questions/6866802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/519990/" ]
I found that splitting the collection view item view into its own XIB and then rewiring the connections so that the collection view item prototype loads the new XIB will allow for you to create the bindings in interface builder without it crashing. I followed these steps... 1. Delete the collection view item view from the default xib. 2. Create a new view and XIB inheriting from NSCollectionViewItem. 3. Create your collection view item in the new view. 4. Bind the fields to the files owner of the new view. 5. Back in the collection view xib, update the properties of collection view item to load the bin name of the new xib. I'm not sure that it's quicker than doing it programmatically, but it does allow you to manage the bindings without writing code. I've got a few apps working this way now.
I've found a temporary work around: Select the "Collection View Item" and under the "Attributes Inspector" → "View Controller" settings, set "Nib Name" to "MainMenu". Once you've done this, it won't crash, and you can set the bindings. Be sure to clear the "Nib Name" setting when building your app.
63,345,527
I am trying to build a Docker application that uses Python's gensim library, version 3.8.3, which is being installed via pip from a requirements.txt file. However, Docker seems to have trouble while trying to do RUN pip install -r requirements.txt My Requirement.txt for reference - ``` boto==2.49.0 boto3==1.14.33 botocore==1.17.33 certifi==2020.6.20 chardet==3.0.4 click==7.1.2 Cython==0.29.14 docutils==0.15.2 Flask==1.1.2 gensim==3.8.3 idna==2.10 itsdangerous==1.1.0 Jinja2==2.11.2 jmespath==0.10.0 MarkupSafe==1.1.1 numpy==1.19.1 python-dateutil==2.8.1 requests==2.24.0 s3transfer==0.3.3 scipy==1.5.2 six==1.15.0 smart-open==2.1.0 urllib3==1.25.10 Werkzeug==1.0.1 ``` dockerFile ``` FROM python:3.8.2-alpine WORKDIR /project ADD . /project RUN set -x && apk add --no-cache build-base && apk add --no-cache libexecinfo-dev RUN pip install --upgrade pip RUN pip install -r requirements.txt CMD ["python","similarity.py"] ``` error: ``` (venv) C:\Users\verma\PycharmProjects\flaskTest>docker image build -t similarity-flask-api . Sending build context to Docker daemon 302.7MB Step 1/7 : FROM python:3.8.2-alpine ---> 6c32e2504283 Step 2/7 : WORKDIR /project ---> Using cache ---> 554b6bda89ad Step 3/7 : ADD . /project ---> d085a645ecb1 Step 4/7 : RUN set -x && apk add --no-cache build-base && apk add --no-cache libexecinfo-dev ---> Running in e7117c1e18ff + apk add --no-cache build-base fetch http://dl-cdn.alpinelinux.org/alpine/v3.11/main/x86_64/APKINDEX.tar.gz fetch http://dl-cdn.alpinelinux.org/alpine/v3.11/community/x86_64/APKINDEX.tar.gz (1/18) Installing libgcc (9.2.0-r4) (2/18) Installing libstdc++ (9.2.0-r4) (3/18) Installing binutils (2.33.1-r0) (4/18) Installing libmagic (5.37-r1) (5/18) Installing file (5.37-r1) (6/18) Installing gmp (6.1.2-r1) (7/18) Installing isl (0.18-r0) (8/18) Installing libgomp (9.2.0-r4) (9/18) Installing libatomic (9.2.0-r4) (10/18) Installing mpfr4 (4.0.2-r1) (11/18) Installing mpc1 (1.1.0-r1) (12/18) Installing gcc (9.2.0-r4) (13/18) Installing musl-dev (1.1.24-r2) (14/18) Installing libc-dev (0.7.2-r0) (15/18) Installing g++ (9.2.0-r4) (16/18) Installing make (4.2.1-r2) (17/18) Installing fortify-headers (1.1-r0) (18/18) Installing build-base (0.5-r1) Executing busybox-1.31.1-r9.trigger OK: 182 MiB in 52 packages + apk add --no-cache libexecinfo-dev fetch http://dl-cdn.alpinelinux.org/alpine/v3.11/main/x86_64/APKINDEX.tar.gz fetch http://dl-cdn.alpinelinux.org/alpine/v3.11/community/x86_64/APKINDEX.tar.gz (1/2) Installing libexecinfo (1.1-r1) (2/2) Installing libexecinfo-dev (1.1-r1) OK: 183 MiB in 54 packages Removing intermediate container e7117c1e18ff ---> 9e7a97f8bddc Step 5/7 : RUN pip install --upgrade pip ---> Running in 0286591e9e70 Collecting pip Downloading pip-20.2.1-py2.py3-none-any.whl (1.5 MB) Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 20.1 Uninstalling pip-20.1: Successfully uninstalled pip-20.1 Successfully installed pip-20.2.1 Removing intermediate container 0286591e9e70 ---> ca837786d695 Step 6/7 : RUN pip install -r requirements.txt ---> Running in 7f124c100c0b Collecting boto==2.49.0 Downloading boto-2.49.0-py2.py3-none-any.whl (1.4 MB) Collecting boto3==1.14.33 Downloading boto3-1.14.33-py2.py3-none-any.whl (129 kB) Collecting botocore==1.17.33 Downloading botocore-1.17.33-py2.py3-none-any.whl (6.5 MB) Collecting certifi==2020.6.20 Downloading certifi-2020.6.20-py2.py3-none-any.whl (156 kB) Collecting chardet==3.0.4 Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB) Collecting click==7.1.2 Downloading click-7.1.2-py2.py3-none-any.whl (82 kB) Collecting Cython==0.29.14 Downloading Cython-0.29.14.tar.gz (2.1 MB) Collecting docutils==0.15.2 Downloading docutils-0.15.2-py3-none-any.whl (547 kB) Collecting Flask==1.1.2 Downloading Flask-1.1.2-py2.py3-none-any.whl (94 kB) Collecting gensim==3.8.3 Downloading gensim-3.8.3.tar.gz (23.4 MB) Collecting idna==2.10 Downloading idna-2.10-py2.py3-none-any.whl (58 kB) Collecting itsdangerous==1.1.0 Downloading itsdangerous-1.1.0-py2.py3-none-any.whl (16 kB) Collecting Jinja2==2.11.2 Downloading Jinja2-2.11.2-py2.py3-none-any.whl (125 kB) Collecting jmespath==0.10.0 Downloading jmespath-0.10.0-py2.py3-none-any.whl (24 kB) Collecting MarkupSafe==1.1.1 Downloading MarkupSafe-1.1.1.tar.gz (19 kB) Processing /root/.cache/pip/wheels/df/b2/64/111c431ca7f7d49afb42126b7351fe1a4894803d75026360de/numpy-1.19.1-cp38-cp38-linux_x86_64.whl Collecting python-dateutil==2.8.1 Downloading python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB) Collecting requests==2.24.0 Downloading requests-2.24.0-py2.py3-none-any.whl (61 kB) Collecting s3transfer==0.3.3 Downloading s3transfer-0.3.3-py2.py3-none-any.whl (69 kB) Collecting scipy==1.5.2 Downloading scipy-1.5.2.tar.gz (25.4 MB) Installing build dependencies: started Installing build dependencies: still running... Installing build dependencies: still running... Installing build dependencies: still running... Installing build dependencies: still running... Installing build dependencies: still running... Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing wheel metadata: started Preparing wheel metadata: finished with status 'error' ERROR: Command errored out with exit status 1: command: /usr/local/bin/python /usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmpoyjzx5wb cwd: /tmp/pip-install-r078skp_/scipy Complete output (139 lines): lapack_opt_info: lapack_mkl_info: customize UnixCCompiler libraries mkl_rt not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/'] NOT AVAILABLE openblas_lapack_info: customize UnixCCompiler customize UnixCCompiler libraries openblas not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/'] NOT AVAILABLE openblas_clapack_info: customize UnixCCompiler customize UnixCCompiler libraries openblas,lapack not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/'] NOT AVAILABLE flame_info: customize UnixCCompiler libraries flame not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/'] NOT AVAILABLE atlas_3_10_threads_info: Setting PTATLAS=ATLAS customize UnixCCompiler libraries lapack_atlas not found in /usr/local/lib customize UnixCCompiler libraries tatlas,tatlas not found in /usr/local/lib customize UnixCCompiler libraries lapack_atlas not found in /usr/lib customize UnixCCompiler libraries tatlas,tatlas not found in /usr/lib customize UnixCCompiler libraries lapack_atlas not found in /usr/lib/ customize UnixCCompiler libraries tatlas,tatlas not found in /usr/lib/ <class 'numpy.distutils.system_info.atlas_3_10_threads_info'> NOT AVAILABLE atlas_3_10_info: customize UnixCCompiler libraries lapack_atlas not found in /usr/local/lib customize UnixCCompiler libraries satlas,satlas not found in /usr/local/lib customize UnixCCompiler libraries lapack_atlas not found in /usr/lib customize UnixCCompiler libraries satlas,satlas not found in /usr/lib customize UnixCCompiler libraries lapack_atlas not found in /usr/lib/ customize UnixCCompiler libraries satlas,satlas not found in /usr/lib/ <class 'numpy.distutils.system_info.atlas_3_10_info'> NOT AVAILABLE atlas_threads_info: Setting PTATLAS=ATLAS customize UnixCCompiler libraries lapack_atlas not found in /usr/local/lib customize UnixCCompiler libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib customize UnixCCompiler libraries lapack_atlas not found in /usr/lib customize UnixCCompiler libraries ptf77blas,ptcblas,atlas not found in /usr/lib customize UnixCCompiler libraries lapack_atlas not found in /usr/lib/ customize UnixCCompiler libraries ptf77blas,ptcblas,atlas not found in /usr/lib/ <class 'numpy.distutils.system_info.atlas_threads_info'> NOT AVAILABLE atlas_info: customize UnixCCompiler libraries lapack_atlas not found in /usr/local/lib customize UnixCCompiler libraries f77blas,cblas,atlas not found in /usr/local/lib customize UnixCCompiler libraries lapack_atlas not found in /usr/lib customize UnixCCompiler libraries f77blas,cblas,atlas not found in /usr/lib customize UnixCCompiler libraries lapack_atlas not found in /usr/lib/ customize UnixCCompiler libraries f77blas,cblas,atlas not found in /usr/lib/ <class 'numpy.distutils.system_info.atlas_info'> NOT AVAILABLE accelerate_info: NOT AVAILABLE lapack_info: customize UnixCCompiler libraries lapack not found in ['/usr/local/lib', '/usr/lib', '/usr/lib/'] NOT AVAILABLE lapack_src_info: NOT AVAILABLE NOT AVAILABLE setup.py:460: UserWarning: Unrecognized setuptools command ('dist_info --egg-base /tmp/pip-modern-metadata-ujofw06w'), proceeding with generating Cython sources and expanding templates warnings.warn("Unrecognized setuptools command ('{}'), proceeding with " Running from SciPy source directory. /tmp/pip-build-env-mw61mr08/overlay/lib/python3.8/site-packages/numpy/distutils/system_info.py:1712: UserWarning: Lapack (http://www.netlib.org/lapack/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [lapack]) or by setting the LAPACK environment variable. if getattr(self, '_calc_info_{}'.format(lapack))(): /tmp/pip-build-env-mw61mr08/overlay/lib/python3.8/site-packages/numpy/distutils/system_info.py:1712: UserWarning: Lapack (http://www.netlib.org/lapack/) sources not found. Directories to search for the sources can be specified in the numpy/distutils/site.cfg file (section [lapack_src]) or by setting the LAPACK_SRC environment variable. if getattr(self, '_calc_info_{}'.format(lapack))(): Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py", line 280, in <module> main() File "/usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py", line 263, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py", line 133, in prepare_metadata_for_build_wheel return hook(metadata_directory, config_settings) File "/tmp/pip-build-env-mw61mr08/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 157, in prepare_metadata_for_build_wheel self.run_setup() File "/tmp/pip-build-env-mw61mr08/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 248, in run_setup super(_BuildMetaLegacyBackend, File "/tmp/pip-build-env-mw61mr08/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 142, in run_setup exec(compile(code, __file__, 'exec'), locals()) File "setup.py", line 583, in <module> setup_package() File "setup.py", line 579, in setup_package setup(**metadata) File "/tmp/pip-build-env-mw61mr08/overlay/lib/python3.8/site-packages/numpy/distutils/core.py", line 137, in setup config = configuration() File "setup.py", line 477, in configuration raise NotFoundError(msg) numpy.distutils.system_info.NotFoundError: No lapack/blas resources found. ---------------------------------------- ERROR: Command errored out with exit status 1: /usr/local/bin/python /usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_bu ild_wheel /tmp/tmpoyjzx5wb Check the logs for full command output. The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 ``` **I tried this thread - [Docker unable to install numpy, scipy, or gensim](https://stackoverflow.com/questions/44732303/docker-unable-to-install-numpy-scipy-or-gensim) As suggested I added line 4 and 5 in my dockerFile but it is still not working.**
2020/08/10
[ "https://Stackoverflow.com/questions/63345527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12138506/" ]
in the post you mension, thye install `libc-dev` to compile packs ... you dont. ``` RUN apt-get -y install libc-dev RUN apt-get -y install build-essential ``` I have problems trying to use "alpine" with Python... so we choose ["slim-buster"](https://hub.docker.com/_/python) as docker image for Python. so if you can... 1 - I would try slim-buster if you can 2 - Try a numpy ready docker image and install your python packages.
To install `numpy` on an alpine image, you typically need a few more dependencies: ``` RUN apk update && apk add gfortran build-base openblas-dev libffi-dev ``` Namely the openblas-dev, which you are missing. That will at least get `numpy` to install
54,299,203
I've looked around and haven't found anything just yet. I'm going through emails in an inbox and checking for a specific word set. It works on most emails but some of them don't parse. I checked the broken emails using. ``` print (msg.Body.encode('utf8')) ``` and my problem messages all start with **b'**. like this ``` b'\xe6\xa0\xbc\xe6\xb5\xb4\xe3\xb9\xac\xe6\xa0\xbc\xe6\x85\xa5\xe3\xb9\xa4\xe0\xa8\x8d\xe6\xb4\xbc\xe7\x91\xa5\xe2\x81\xa1\xe7\x91\x ``` I think this is forcing python to read the body as bytes but I'm not sure. Either way after the b, no matter what encoding I try I don't get anything but garbage text. I've tried other encoding methods as well decoding before but I'm just getting a ton of attribute errrors. ``` import win32api import win32com.client import datetime import os import time outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") dater = datetime.date.today() - datetime.timedelta(days = 1) dater = str(dater.strftime("%m-%d-%Y")) print (dater) #for folders in outlook.folders: # print(folders) Receipt = outlook.folders[8] print(Receipt) Ritems = Receipt.folders["Inbox"] Rmessage = Ritems.items for msg in Rmessage: if (msg.Class == 46 and msg.CreationTime.strftime("%m-%d-%Y") == dater): print (msg.CreationTime) print (msg.Subject) print (msg.Body.encode('utf8')) print ('..............................') ``` End result is to have the message printed out in the console, or at least give Python a way to read it so I can find the text I'm looking for in the body.
2019/01/21
[ "https://Stackoverflow.com/questions/54299203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6054714/" ]
Is the dropdown populated on the server or after an ajax call? It might be that you've tried to select a value before any are available as it's still waiting on for a response to provide data. You could wait until that response is received and then select the first option from that data set. You could reference this example: <https://stackoverflow.com/a/16746700/2835914> You could also try: ``` success: function (data) { var markup = ""; markup += "<option value='0'>Seleccionar..</option>";; for (var x = 0; x < data.length; x++) { markup += "<option value='" + data[x].Value + "' " + x === 0 ? "selected" : "" + ">" + data[x].Text + "</option>"; } $("#MyDropDown").html(markup).show(); }, ```
if you used jquery ajax you should do this ```js $(document).on("click", 'button', function() { $(".modal-body").load(YOURURL, function() { $("#MyDropDown").prop('selectedIndex', 1); }); $("#myModal").modal(); }); ```
15,995,987
In python, I have this list containing ``` ['HELLO', 'WORLD'] ``` how do I turn that list into ``` ['OLLEH', 'DLROW'] ```
2013/04/14
[ "https://Stackoverflow.com/questions/15995987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2278906/" ]
``` >>> words = ['HELLO', 'WORLD'] >>> [word[::-1] for word in words] ['OLLEH', 'DLROW'] ```
Using a list comprehension: ``` reversed_list = [x[::-1] for x in old_list] ```
15,995,987
In python, I have this list containing ``` ['HELLO', 'WORLD'] ``` how do I turn that list into ``` ['OLLEH', 'DLROW'] ```
2013/04/14
[ "https://Stackoverflow.com/questions/15995987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2278906/" ]
``` >>> words = ['HELLO', 'WORLD'] >>> [word[::-1] for word in words] ['OLLEH', 'DLROW'] ```
Using `map` and `lambda`(lambdas are slow): ``` >>> lis=['HELLO', 'WORLD'] >>> map(lambda x:x[::-1],lis) ['OLLEH', 'DLROW'] ```
15,995,987
In python, I have this list containing ``` ['HELLO', 'WORLD'] ``` how do I turn that list into ``` ['OLLEH', 'DLROW'] ```
2013/04/14
[ "https://Stackoverflow.com/questions/15995987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2278906/" ]
``` >>> words = ['HELLO', 'WORLD'] >>> [word[::-1] for word in words] ['OLLEH', 'DLROW'] ```
Arguably using the builtin `reversed` is more clear than slice notation `x[::-1]`. ``` [reversed(word) for word in words] ``` or ``` map(reversed, words) ``` Map is fast without the lambda. I just wish it was easier to get the string out of the resulting iterator. Is there anything better than `''.join()` to put together the string from the iterator?
15,995,987
In python, I have this list containing ``` ['HELLO', 'WORLD'] ``` how do I turn that list into ``` ['OLLEH', 'DLROW'] ```
2013/04/14
[ "https://Stackoverflow.com/questions/15995987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2278906/" ]
Using a list comprehension: ``` reversed_list = [x[::-1] for x in old_list] ```
Using `map` and `lambda`(lambdas are slow): ``` >>> lis=['HELLO', 'WORLD'] >>> map(lambda x:x[::-1],lis) ['OLLEH', 'DLROW'] ```
15,995,987
In python, I have this list containing ``` ['HELLO', 'WORLD'] ``` how do I turn that list into ``` ['OLLEH', 'DLROW'] ```
2013/04/14
[ "https://Stackoverflow.com/questions/15995987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2278906/" ]
Using a list comprehension: ``` reversed_list = [x[::-1] for x in old_list] ```
Arguably using the builtin `reversed` is more clear than slice notation `x[::-1]`. ``` [reversed(word) for word in words] ``` or ``` map(reversed, words) ``` Map is fast without the lambda. I just wish it was easier to get the string out of the resulting iterator. Is there anything better than `''.join()` to put together the string from the iterator?
15,995,987
In python, I have this list containing ``` ['HELLO', 'WORLD'] ``` how do I turn that list into ``` ['OLLEH', 'DLROW'] ```
2013/04/14
[ "https://Stackoverflow.com/questions/15995987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2278906/" ]
Arguably using the builtin `reversed` is more clear than slice notation `x[::-1]`. ``` [reversed(word) for word in words] ``` or ``` map(reversed, words) ``` Map is fast without the lambda. I just wish it was easier to get the string out of the resulting iterator. Is there anything better than `''.join()` to put together the string from the iterator?
Using `map` and `lambda`(lambdas are slow): ``` >>> lis=['HELLO', 'WORLD'] >>> map(lambda x:x[::-1],lis) ['OLLEH', 'DLROW'] ```
16,560,497
I am new at Python so this may seem to be very easy. I am trying to remove all **#**, numbers and if the same letter is repeated more then two times in a row, I need to change it to only two letters. This work perfectly but not with ØÆÅ. *Any ideas how this can be done with ØÆÅ letters?* ``` #!/usr/bin/python # -*- coding: utf-8 -*- import math, re, sys, os, codecs reload(sys) sys.setdefaultencoding('utf-8') text = "ån9d ånd ååååånd d9d flllllløde... :)asd " # Remove anything other than digits text = re.sub(r'#', "", text) text = re.sub(r"\d", "", text) text = re.sub(r'(\w)\1+', r'\1\1', text) print "Phone Num : "+ text ``` The result I get now is: ``` Phone Num : ånd ånd ååååånd dd flløde... :)asd ``` What I want is: ``` Phone Num : ånd ånd åånd dd flløde... :)asd ```
2013/05/15
[ "https://Stackoverflow.com/questions/16560497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/871742/" ]
You need to work with Unicode values, not with byte strings. UTF-8 encoded `å` is *two* bytes, and a regular expression matching `\w` *only* matches ascii letters, digits and underscores when operating in the default non-Unicode-aware mode. From the [`re` module documentation](http://docs.python.org/2/library/re.html) on `\w`: > > When the `LOCALE` and `UNICODE` flags are not specified, matches any alphanumeric character and the underscore; this is equivalent to the set `[a-zA-Z0-9_]`. With `LOCALE`, it will match the set `[0-9_]` plus whatever characters are defined as alphanumeric for the current locale. If `UNICODE` is set, this will match the characters `[0-9_]` plus whatever is classified as alphanumeric in the Unicode character properties database. > > > Unfortunately, even when you switch to properly using Unicode values (using a unicode `u''` literal or by decoding your source data to unicode values), using a Unicode regular expression (`re.sub(ur'...')`) and using the `re.UNICODE` flag to switch `\w` to match Unicode alphanumeric characters, the Python `re` module has limited support for Unicode matching still: ``` >>> print re.sub(ur'(\w)\1+', r'\1\1', text, re.UNICODE) ånd ånd ååååånd dd flløde... :)asd ``` because `å` is not being recognized as alphanumeric: ``` >>> print re.sub(ur'\w', '', text, re.UNICODE) å å ååååå ø... :) ``` The solution is to use the external [`regex` library](http://pypi.python.org/pypi/regex) which is a version of the `re` library that adds proper full Unicode support: ``` >>> import regex >>> print regex.sub(ur'(\w)\1+', r'\1\1', text, re.UNICODE) ånd ånd åånd dd flløde... :)asd ``` That module can do more than just recognize more alphanumeric characters in Unicode values, see the linked package page for more details.
Change: ``` text = u"ån9d ånd åååååååånd d9d flllllløde... :)asd " ``` and ``` text = re.sub(r'(\w)\1+', r'\1\1', text) ``` **COMPELTE SOLUTION** ``` import math, re, sys, os, codecs reload(sys) sys.setdefaultencoding('utf-8') text = u"ån9d ånd åååååååånd d9d flllllløde... :)asd " # Remove anything other than digits text = re.sub(r'#', "", text) text = re.sub(r"\d", "", text) text = re.sub(r'(\w)\1+', r'\1\1', text) text = re.sub(r'(\W)\1+', r'\1\1', text) print "1: "+ text ``` Print: ``` 1: ånd ånd åånd dd flløde.. :)asd ```
40,664,786
I'm a beginner using python, and am writing a "guess my number game". So far I have everything working fine. The computer picks a random number between 1 and 3 and asks the player to guess the number. If the guess is higher than the random number, the program prints "Lower", and vice versa. The player only has 5 tries, and when they run out, the player gets a message and the game ends. If the player guesses correctly, they are congratulated and the game ends. However, sometimes when the number is guessed correctly, the program doesn't print the congratulatory message and I can't figure out why... ``` import random print("\tWelcome to 'Guess My Number'!:") print("\nI'm thinking of a numer between 1 and 100.") print("Guess carefully, you only have 5 tries!.\n") #sets initial values the_number = random.randint(1,3) guess = int(input("Take a guess: ")) tries = 1 guesses = 4 #guessing loop while guess != the_number: if guess > the_number: print("Lower...") elif guesses <= 0: print("Sorry, you're out of guesses! Try again...") break elif guess < the_number: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 guesses -= 1 if guess == the_number: print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") ```
2016/11/17
[ "https://Stackoverflow.com/questions/40664786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6912990/" ]
To answer your original question about the lack of congratulatory message for correct number, end the code with input(), to ensure it does not terminate before displaying the last message. Order of calculation: 1. give input guess 2. reduce guesses (starting at 5), increase tries (starting at 1) 3. immediate break if guesses == 0 4. evaluate guess (lower, higher or equal, which would end while loop) ```html import random print("\tWelcome to 'Guess My Number'!:") print("\nI'm thinking of a numer between 1 and 3.") print("Guess carefully, you only have 5 tries!.\n") #sets initial values the_number = random.randint(1,3) guess = int(input("Take a guess: ")) tries = 1 guesses = 5 #guessing loop while guess != the_number: tries += 1 guesses -= 1 if guesses == 0: print("Sorry, you're out of guesses! Try again...") break elif guess > the_number: print("Lower...") elif guess < the_number: print("Higher...") guess = int(input("Take a guess: ")) if guess == the_number: print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") input() ```
Assuming everything else works, un-indent the final check. You can't check `guess == the_number` while it isn't equal ``` #guessing loop while guess != the_number: # do logic # outside guessing loop if guesses > 0: print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") ```
40,664,786
I'm a beginner using python, and am writing a "guess my number game". So far I have everything working fine. The computer picks a random number between 1 and 3 and asks the player to guess the number. If the guess is higher than the random number, the program prints "Lower", and vice versa. The player only has 5 tries, and when they run out, the player gets a message and the game ends. If the player guesses correctly, they are congratulated and the game ends. However, sometimes when the number is guessed correctly, the program doesn't print the congratulatory message and I can't figure out why... ``` import random print("\tWelcome to 'Guess My Number'!:") print("\nI'm thinking of a numer between 1 and 100.") print("Guess carefully, you only have 5 tries!.\n") #sets initial values the_number = random.randint(1,3) guess = int(input("Take a guess: ")) tries = 1 guesses = 4 #guessing loop while guess != the_number: if guess > the_number: print("Lower...") elif guesses <= 0: print("Sorry, you're out of guesses! Try again...") break elif guess < the_number: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 guesses -= 1 if guess == the_number: print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") ```
2016/11/17
[ "https://Stackoverflow.com/questions/40664786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6912990/" ]
To answer your original question about the lack of congratulatory message for correct number, end the code with input(), to ensure it does not terminate before displaying the last message. Order of calculation: 1. give input guess 2. reduce guesses (starting at 5), increase tries (starting at 1) 3. immediate break if guesses == 0 4. evaluate guess (lower, higher or equal, which would end while loop) ```html import random print("\tWelcome to 'Guess My Number'!:") print("\nI'm thinking of a numer between 1 and 3.") print("Guess carefully, you only have 5 tries!.\n") #sets initial values the_number = random.randint(1,3) guess = int(input("Take a guess: ")) tries = 1 guesses = 5 #guessing loop while guess != the_number: tries += 1 guesses -= 1 if guesses == 0: print("Sorry, you're out of guesses! Try again...") break elif guess > the_number: print("Lower...") elif guess < the_number: print("Higher...") guess = int(input("Take a guess: ")) if guess == the_number: print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") input() ```
If you guess the number in your first try, the program will require another guess nevertheless since ``` guess = int(input("Take a guess: ")) tries += 1 guesses -= 1 ``` comes before ``` if guess == the_number: print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") ``` when you already asked for a guess outside the loop. You should only ask for input inside the loop: ``` the_number = random.randint(1,3) tries = 0 guesses = 5 #guessing loop guess = None while guess != the_number: guess = int(input("Take a guess: ")) tries += 1 guesses -= 1 if guess > the_number: print("Lower...") elif guess < the_number: print("Higher...") if guess == the_number: print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") if guesses <= 0: print("Sorry, you're out of guesses! Try again...") break ```
11,055,921
I am using mongoexport to export mongodb data which also has Image data in Binary format. Export is done in csv format. I tried to read image data from csv file into python and tried to store as in Image File in .jpg format on disk. But it seems that, data is corrupt and image is not getting stored. Has anybody come across such situation or resolved similar thing ? Thanks,
2012/06/15
[ "https://Stackoverflow.com/questions/11055921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1459413/" ]
One thing to watch out for is an arbitrary 2MB BSON Object size limit in several of 10gen's implementations. You might have to denormalize your image data and store it across multiple objects.
Depending how you stored the data, it may be prefixed with 4 bytes of size. Are the corrupt exports 4 bytes/GridFS chunk longer than you'd expect?
58,851,954
Im trying to do the obeythetestinggoat tutorial and cant set my geckodriver, Im working in Win10 64bits my pip freeze shows: Django==1.7,selenium==3.141.0,urllib3==1.25.7 i download the geckodriver (geckodriver-v0.26.0-win64) when i try to get the geckodriver version (via `$geckodriver --version`) stops and show me a error 'application error' I think that the error are in the enviroment variables (i was trying to put the file in location where the variables are set (windows/system32 or python/scripts) but nothing works i also trying this solution (put the file in some file where path are viable) in another computer and works.
2019/11/14
[ "https://Stackoverflow.com/questions/58851954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663963/" ]
Vim 8 ( and a number of Vim emulations ) I'd start with ``` <h1>This is h0</h1> <h2>This is h0</h2> <h3>This is h0</h3> <h4>This is h0</h4> <h5>This is h0</h5> <h6>This is h0</h6> ``` then on the top 0 of h0. I'd block highlight with `CTRL-V` go down to the bottom 0 of the h6 tag with `5j` then type `g` and then `CTRL-A` and it will be what you want
With my [UnconditionalPaste plugin](http://www.vim.org/scripts/script.php?script_id=3355), you just need to yank the first `<h1>This is h1</h1>` line, and then paste 5 times with `5gPp`, which pastes with all decimal numbers incremented by 1. This also is repeatable via `.`, so you could have also pasted just once and then repeat that 4 times. There are also mapping variants that decrement, increment just one number, and many more mappings around paste variations.
58,851,954
Im trying to do the obeythetestinggoat tutorial and cant set my geckodriver, Im working in Win10 64bits my pip freeze shows: Django==1.7,selenium==3.141.0,urllib3==1.25.7 i download the geckodriver (geckodriver-v0.26.0-win64) when i try to get the geckodriver version (via `$geckodriver --version`) stops and show me a error 'application error' I think that the error are in the enviroment variables (i was trying to put the file in location where the variables are set (windows/system32 or python/scripts) but nothing works i also trying this solution (put the file in some file where path are viable) in another computer and works.
2019/11/14
[ "https://Stackoverflow.com/questions/58851954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663963/" ]
Vim 8 ( and a number of Vim emulations ) I'd start with ``` <h1>This is h0</h1> <h2>This is h0</h2> <h3>This is h0</h3> <h4>This is h0</h4> <h5>This is h0</h5> <h6>This is h0</h6> ``` then on the top 0 of h0. I'd block highlight with `CTRL-V` go down to the bottom 0 of the h6 tag with `5j` then type `g` and then `CTRL-A` and it will be what you want
I would do this ``` :for i in range(1,6) | put='<h'.i'.'>This is h'.i.'</h'.i.'>' | endfor :1d ``` We are concatening string with the variable 'i'. Tha's why we are using the dot on the put statement More explanation - If you want simple to put a string on the first line: ``` :0put='my string' ``` A second way to increase numbers automatically is: Let's consider you already have this code and the first line coincides with the first line of the actual archive you want to change. ``` <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> :2,$s,\d\+,\=line('.'),g ``` If by any chance those lines are in another place you can make something like: ``` :5,9s,\d\+,\=line('.')-3,g ``` OBS: the use of the `line('.')` comes in handy because it is naturally an increasing sequence of numbers. A third way to insert an ascending sequence is: In normal mode type: `6i<h1>This is h1</h1>` `Enter``Esc` The above action will insert 6 lines like this: ``` <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> ``` Now put the cursor at the first 1 on the second line and make a visual block selection with `Ctrl``v`, then extend the selection till the last line, like seen below: [![enter image description here](https://i.stack.imgur.com/rP2is.png)](https://i.stack.imgur.com/rP2is.png) Now press `g` `Ctrl``a` Now press `f``1``.` to jump to the next number and repeat the action. Finally press `;` to jump to the last number and then `.`
58,851,954
Im trying to do the obeythetestinggoat tutorial and cant set my geckodriver, Im working in Win10 64bits my pip freeze shows: Django==1.7,selenium==3.141.0,urllib3==1.25.7 i download the geckodriver (geckodriver-v0.26.0-win64) when i try to get the geckodriver version (via `$geckodriver --version`) stops and show me a error 'application error' I think that the error are in the enviroment variables (i was trying to put the file in location where the variables are set (windows/system32 or python/scripts) but nothing works i also trying this solution (put the file in some file where path are viable) in another computer and works.
2019/11/14
[ "https://Stackoverflow.com/questions/58851954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663963/" ]
Vim 8 ( and a number of Vim emulations ) I'd start with ``` <h1>This is h0</h1> <h2>This is h0</h2> <h3>This is h0</h3> <h4>This is h0</h4> <h5>This is h0</h5> <h6>This is h0</h6> ``` then on the top 0 of h0. I'd block highlight with `CTRL-V` go down to the bottom 0 of the h6 tag with `5j` then type `g` and then `CTRL-A` and it will be what you want
Normally I'll use macro to generate numbers in order. In this case, I'll write `<h1>This is h1</h1>` first. 1. `qq`, (first `q` is to start recording your keystroke and store it as a macro in key `q`) 2. `yyp`, to duplicate the line (`yy` to copy current line, `p` to paste) 3. `ctrl-a`, to increase first occurred number which is from `<h1>` 4. `w` then `ctrl-a`, to jump to the next word and then increase the second occurred which is h1` 5. repeat step 4 again to increase `</h1>` 6. `q`, to stop recording 7. `4@q`, to redo your recording four more times (`@` from `shift+2`, means to execute macro, `q` specified the macro function stored in key `q`, and `4` means do the action 4 times)
58,851,954
Im trying to do the obeythetestinggoat tutorial and cant set my geckodriver, Im working in Win10 64bits my pip freeze shows: Django==1.7,selenium==3.141.0,urllib3==1.25.7 i download the geckodriver (geckodriver-v0.26.0-win64) when i try to get the geckodriver version (via `$geckodriver --version`) stops and show me a error 'application error' I think that the error are in the enviroment variables (i was trying to put the file in location where the variables are set (windows/system32 or python/scripts) but nothing works i also trying this solution (put the file in some file where path are viable) in another computer and works.
2019/11/14
[ "https://Stackoverflow.com/questions/58851954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663963/" ]
Vim 8 ( and a number of Vim emulations ) I'd start with ``` <h1>This is h0</h1> <h2>This is h0</h2> <h3>This is h0</h3> <h4>This is h0</h4> <h5>This is h0</h5> <h6>This is h0</h6> ``` then on the top 0 of h0. I'd block highlight with `CTRL-V` go down to the bottom 0 of the h6 tag with `5j` then type `g` and then `CTRL-A` and it will be what you want
Will it be okay to copy the `h1, h2, ...` column and paste? Use `Ctrl` + `v` and select `h1` and then `5j`. This will block select next 5 line, Change number accordingly. Copy the selected lines using y. Now, nagivate to `h` where you want to past and repeat `Ctrl` + `v` and `5j`, Thereafter finish the paste with `shift` + `p`
58,851,954
Im trying to do the obeythetestinggoat tutorial and cant set my geckodriver, Im working in Win10 64bits my pip freeze shows: Django==1.7,selenium==3.141.0,urllib3==1.25.7 i download the geckodriver (geckodriver-v0.26.0-win64) when i try to get the geckodriver version (via `$geckodriver --version`) stops and show me a error 'application error' I think that the error are in the enviroment variables (i was trying to put the file in location where the variables are set (windows/system32 or python/scripts) but nothing works i also trying this solution (put the file in some file where path are viable) in another computer and works.
2019/11/14
[ "https://Stackoverflow.com/questions/58851954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663963/" ]
I would do this ``` :for i in range(1,6) | put='<h'.i'.'>This is h'.i.'</h'.i.'>' | endfor :1d ``` We are concatening string with the variable 'i'. Tha's why we are using the dot on the put statement More explanation - If you want simple to put a string on the first line: ``` :0put='my string' ``` A second way to increase numbers automatically is: Let's consider you already have this code and the first line coincides with the first line of the actual archive you want to change. ``` <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> :2,$s,\d\+,\=line('.'),g ``` If by any chance those lines are in another place you can make something like: ``` :5,9s,\d\+,\=line('.')-3,g ``` OBS: the use of the `line('.')` comes in handy because it is naturally an increasing sequence of numbers. A third way to insert an ascending sequence is: In normal mode type: `6i<h1>This is h1</h1>` `Enter``Esc` The above action will insert 6 lines like this: ``` <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> ``` Now put the cursor at the first 1 on the second line and make a visual block selection with `Ctrl``v`, then extend the selection till the last line, like seen below: [![enter image description here](https://i.stack.imgur.com/rP2is.png)](https://i.stack.imgur.com/rP2is.png) Now press `g` `Ctrl``a` Now press `f``1``.` to jump to the next number and repeat the action. Finally press `;` to jump to the last number and then `.`
With my [UnconditionalPaste plugin](http://www.vim.org/scripts/script.php?script_id=3355), you just need to yank the first `<h1>This is h1</h1>` line, and then paste 5 times with `5gPp`, which pastes with all decimal numbers incremented by 1. This also is repeatable via `.`, so you could have also pasted just once and then repeat that 4 times. There are also mapping variants that decrement, increment just one number, and many more mappings around paste variations.
58,851,954
Im trying to do the obeythetestinggoat tutorial and cant set my geckodriver, Im working in Win10 64bits my pip freeze shows: Django==1.7,selenium==3.141.0,urllib3==1.25.7 i download the geckodriver (geckodriver-v0.26.0-win64) when i try to get the geckodriver version (via `$geckodriver --version`) stops and show me a error 'application error' I think that the error are in the enviroment variables (i was trying to put the file in location where the variables are set (windows/system32 or python/scripts) but nothing works i also trying this solution (put the file in some file where path are viable) in another computer and works.
2019/11/14
[ "https://Stackoverflow.com/questions/58851954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663963/" ]
With my [UnconditionalPaste plugin](http://www.vim.org/scripts/script.php?script_id=3355), you just need to yank the first `<h1>This is h1</h1>` line, and then paste 5 times with `5gPp`, which pastes with all decimal numbers incremented by 1. This also is repeatable via `.`, so you could have also pasted just once and then repeat that 4 times. There are also mapping variants that decrement, increment just one number, and many more mappings around paste variations.
Normally I'll use macro to generate numbers in order. In this case, I'll write `<h1>This is h1</h1>` first. 1. `qq`, (first `q` is to start recording your keystroke and store it as a macro in key `q`) 2. `yyp`, to duplicate the line (`yy` to copy current line, `p` to paste) 3. `ctrl-a`, to increase first occurred number which is from `<h1>` 4. `w` then `ctrl-a`, to jump to the next word and then increase the second occurred which is h1` 5. repeat step 4 again to increase `</h1>` 6. `q`, to stop recording 7. `4@q`, to redo your recording four more times (`@` from `shift+2`, means to execute macro, `q` specified the macro function stored in key `q`, and `4` means do the action 4 times)
58,851,954
Im trying to do the obeythetestinggoat tutorial and cant set my geckodriver, Im working in Win10 64bits my pip freeze shows: Django==1.7,selenium==3.141.0,urllib3==1.25.7 i download the geckodriver (geckodriver-v0.26.0-win64) when i try to get the geckodriver version (via `$geckodriver --version`) stops and show me a error 'application error' I think that the error are in the enviroment variables (i was trying to put the file in location where the variables are set (windows/system32 or python/scripts) but nothing works i also trying this solution (put the file in some file where path are viable) in another computer and works.
2019/11/14
[ "https://Stackoverflow.com/questions/58851954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663963/" ]
With my [UnconditionalPaste plugin](http://www.vim.org/scripts/script.php?script_id=3355), you just need to yank the first `<h1>This is h1</h1>` line, and then paste 5 times with `5gPp`, which pastes with all decimal numbers incremented by 1. This also is repeatable via `.`, so you could have also pasted just once and then repeat that 4 times. There are also mapping variants that decrement, increment just one number, and many more mappings around paste variations.
Will it be okay to copy the `h1, h2, ...` column and paste? Use `Ctrl` + `v` and select `h1` and then `5j`. This will block select next 5 line, Change number accordingly. Copy the selected lines using y. Now, nagivate to `h` where you want to past and repeat `Ctrl` + `v` and `5j`, Thereafter finish the paste with `shift` + `p`
58,851,954
Im trying to do the obeythetestinggoat tutorial and cant set my geckodriver, Im working in Win10 64bits my pip freeze shows: Django==1.7,selenium==3.141.0,urllib3==1.25.7 i download the geckodriver (geckodriver-v0.26.0-win64) when i try to get the geckodriver version (via `$geckodriver --version`) stops and show me a error 'application error' I think that the error are in the enviroment variables (i was trying to put the file in location where the variables are set (windows/system32 or python/scripts) but nothing works i also trying this solution (put the file in some file where path are viable) in another computer and works.
2019/11/14
[ "https://Stackoverflow.com/questions/58851954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663963/" ]
I would do this ``` :for i in range(1,6) | put='<h'.i'.'>This is h'.i.'</h'.i.'>' | endfor :1d ``` We are concatening string with the variable 'i'. Tha's why we are using the dot on the put statement More explanation - If you want simple to put a string on the first line: ``` :0put='my string' ``` A second way to increase numbers automatically is: Let's consider you already have this code and the first line coincides with the first line of the actual archive you want to change. ``` <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> :2,$s,\d\+,\=line('.'),g ``` If by any chance those lines are in another place you can make something like: ``` :5,9s,\d\+,\=line('.')-3,g ``` OBS: the use of the `line('.')` comes in handy because it is naturally an increasing sequence of numbers. A third way to insert an ascending sequence is: In normal mode type: `6i<h1>This is h1</h1>` `Enter``Esc` The above action will insert 6 lines like this: ``` <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> ``` Now put the cursor at the first 1 on the second line and make a visual block selection with `Ctrl``v`, then extend the selection till the last line, like seen below: [![enter image description here](https://i.stack.imgur.com/rP2is.png)](https://i.stack.imgur.com/rP2is.png) Now press `g` `Ctrl``a` Now press `f``1``.` to jump to the next number and repeat the action. Finally press `;` to jump to the last number and then `.`
Normally I'll use macro to generate numbers in order. In this case, I'll write `<h1>This is h1</h1>` first. 1. `qq`, (first `q` is to start recording your keystroke and store it as a macro in key `q`) 2. `yyp`, to duplicate the line (`yy` to copy current line, `p` to paste) 3. `ctrl-a`, to increase first occurred number which is from `<h1>` 4. `w` then `ctrl-a`, to jump to the next word and then increase the second occurred which is h1` 5. repeat step 4 again to increase `</h1>` 6. `q`, to stop recording 7. `4@q`, to redo your recording four more times (`@` from `shift+2`, means to execute macro, `q` specified the macro function stored in key `q`, and `4` means do the action 4 times)
58,851,954
Im trying to do the obeythetestinggoat tutorial and cant set my geckodriver, Im working in Win10 64bits my pip freeze shows: Django==1.7,selenium==3.141.0,urllib3==1.25.7 i download the geckodriver (geckodriver-v0.26.0-win64) when i try to get the geckodriver version (via `$geckodriver --version`) stops and show me a error 'application error' I think that the error are in the enviroment variables (i was trying to put the file in location where the variables are set (windows/system32 or python/scripts) but nothing works i also trying this solution (put the file in some file where path are viable) in another computer and works.
2019/11/14
[ "https://Stackoverflow.com/questions/58851954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663963/" ]
I would do this ``` :for i in range(1,6) | put='<h'.i'.'>This is h'.i.'</h'.i.'>' | endfor :1d ``` We are concatening string with the variable 'i'. Tha's why we are using the dot on the put statement More explanation - If you want simple to put a string on the first line: ``` :0put='my string' ``` A second way to increase numbers automatically is: Let's consider you already have this code and the first line coincides with the first line of the actual archive you want to change. ``` <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> :2,$s,\d\+,\=line('.'),g ``` If by any chance those lines are in another place you can make something like: ``` :5,9s,\d\+,\=line('.')-3,g ``` OBS: the use of the `line('.')` comes in handy because it is naturally an increasing sequence of numbers. A third way to insert an ascending sequence is: In normal mode type: `6i<h1>This is h1</h1>` `Enter``Esc` The above action will insert 6 lines like this: ``` <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> <h1>This is h1</h1> ``` Now put the cursor at the first 1 on the second line and make a visual block selection with `Ctrl``v`, then extend the selection till the last line, like seen below: [![enter image description here](https://i.stack.imgur.com/rP2is.png)](https://i.stack.imgur.com/rP2is.png) Now press `g` `Ctrl``a` Now press `f``1``.` to jump to the next number and repeat the action. Finally press `;` to jump to the last number and then `.`
Will it be okay to copy the `h1, h2, ...` column and paste? Use `Ctrl` + `v` and select `h1` and then `5j`. This will block select next 5 line, Change number accordingly. Copy the selected lines using y. Now, nagivate to `h` where you want to past and repeat `Ctrl` + `v` and `5j`, Thereafter finish the paste with `shift` + `p`
82,607
I get DNS records from a Python program, using [DNS Python](http://www.dnspython.org/) I can get various DNSSEC-related records: ``` >>> import dns.resolver >>> myresolver = dns.resolver.Resolver() >>> myresolver.use_edns(1, 0, 1400) >>> print myresolver.query('sources.org', 'DNSKEY') <dns.resolver.Answer object at 0xb78ed78c> >>> print myresolver.query('ripe.net', 'NSEC') <dns.resolver.Answer object at 0x8271c0c> ``` But no RRSIG records: ``` >>> print myresolver.query('sources.org', 'RRSIG') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer ``` I tried several signed domains like absolight.fr or ripe.net. Trying with dig, I see that there are indeed RRSIG records. Checking with tcpdump, I can see that DNS Python sends the correct query and receives correct replies (here, eight records): ``` 16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40) 16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain] ``` DNS Python 1.6.0 - Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44) [GCC 4.3.1] on linux2
2008/09/17
[ "https://Stackoverflow.com/questions/82607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
You probably mean RRSIG ANY (otherwise, the order is wrong, the class needs to be after the type) ``` >>> print myresolver.query('sources.org', 'RRSIG', 'ANY') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer dns.resolver.NoAnswer ```
If you try this, what happens? ``` print myresolver.query('sources.org', 'ANY', 'RRSIG') ```
82,607
I get DNS records from a Python program, using [DNS Python](http://www.dnspython.org/) I can get various DNSSEC-related records: ``` >>> import dns.resolver >>> myresolver = dns.resolver.Resolver() >>> myresolver.use_edns(1, 0, 1400) >>> print myresolver.query('sources.org', 'DNSKEY') <dns.resolver.Answer object at 0xb78ed78c> >>> print myresolver.query('ripe.net', 'NSEC') <dns.resolver.Answer object at 0x8271c0c> ``` But no RRSIG records: ``` >>> print myresolver.query('sources.org', 'RRSIG') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer ``` I tried several signed domains like absolight.fr or ripe.net. Trying with dig, I see that there are indeed RRSIG records. Checking with tcpdump, I can see that DNS Python sends the correct query and receives correct replies (here, eight records): ``` 16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40) 16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain] ``` DNS Python 1.6.0 - Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44) [GCC 4.3.1] on linux2
2008/09/17
[ "https://Stackoverflow.com/questions/82607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
RRSIG is not a record, it's a hashed digest of a valid DNS Record. You can query a DNSKEY record, set want\_dnssec=True and get a DNSKEY Record, and an "RRSIG of a DNSKEY Record". More generally, RRSIG is just a signature of a valid record (such as a DS Record). So when you ask the server ``` myresolver.query('sources.org', 'RRSIG') ``` It doesn't know what you are asking for. RRSIG in itself has no meaning, you need to specify *RRSIG of what?*
If you try this, what happens? ``` print myresolver.query('sources.org', 'ANY', 'RRSIG') ```
82,607
I get DNS records from a Python program, using [DNS Python](http://www.dnspython.org/) I can get various DNSSEC-related records: ``` >>> import dns.resolver >>> myresolver = dns.resolver.Resolver() >>> myresolver.use_edns(1, 0, 1400) >>> print myresolver.query('sources.org', 'DNSKEY') <dns.resolver.Answer object at 0xb78ed78c> >>> print myresolver.query('ripe.net', 'NSEC') <dns.resolver.Answer object at 0x8271c0c> ``` But no RRSIG records: ``` >>> print myresolver.query('sources.org', 'RRSIG') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer ``` I tried several signed domains like absolight.fr or ripe.net. Trying with dig, I see that there are indeed RRSIG records. Checking with tcpdump, I can see that DNS Python sends the correct query and receives correct replies (here, eight records): ``` 16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40) 16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain] ``` DNS Python 1.6.0 - Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44) [GCC 4.3.1] on linux2
2008/09/17
[ "https://Stackoverflow.com/questions/82607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
You probably mean RRSIG ANY (otherwise, the order is wrong, the class needs to be after the type) ``` >>> print myresolver.query('sources.org', 'RRSIG', 'ANY') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer dns.resolver.NoAnswer ```
This looks like a probable bug in the Python DNS library, although I don't read Python well enough to find it. Note that in any case your EDNS0 buffer size parameter is not large enough to handle the RRSIG records for sources.org, so your client and server would have to fail over to TCP/IP.
82,607
I get DNS records from a Python program, using [DNS Python](http://www.dnspython.org/) I can get various DNSSEC-related records: ``` >>> import dns.resolver >>> myresolver = dns.resolver.Resolver() >>> myresolver.use_edns(1, 0, 1400) >>> print myresolver.query('sources.org', 'DNSKEY') <dns.resolver.Answer object at 0xb78ed78c> >>> print myresolver.query('ripe.net', 'NSEC') <dns.resolver.Answer object at 0x8271c0c> ``` But no RRSIG records: ``` >>> print myresolver.query('sources.org', 'RRSIG') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer ``` I tried several signed domains like absolight.fr or ripe.net. Trying with dig, I see that there are indeed RRSIG records. Checking with tcpdump, I can see that DNS Python sends the correct query and receives correct replies (here, eight records): ``` 16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40) 16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain] ``` DNS Python 1.6.0 - Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44) [GCC 4.3.1] on linux2
2008/09/17
[ "https://Stackoverflow.com/questions/82607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
You probably mean RRSIG ANY (otherwise, the order is wrong, the class needs to be after the type) ``` >>> print myresolver.query('sources.org', 'RRSIG', 'ANY') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer dns.resolver.NoAnswer ```
You may want to use `raise_on_no_answer=False` and you will get the correct response: ``` resolver.query(hostname, dnsrecord, raise_on_no_answer=False) ```
82,607
I get DNS records from a Python program, using [DNS Python](http://www.dnspython.org/) I can get various DNSSEC-related records: ``` >>> import dns.resolver >>> myresolver = dns.resolver.Resolver() >>> myresolver.use_edns(1, 0, 1400) >>> print myresolver.query('sources.org', 'DNSKEY') <dns.resolver.Answer object at 0xb78ed78c> >>> print myresolver.query('ripe.net', 'NSEC') <dns.resolver.Answer object at 0x8271c0c> ``` But no RRSIG records: ``` >>> print myresolver.query('sources.org', 'RRSIG') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer ``` I tried several signed domains like absolight.fr or ripe.net. Trying with dig, I see that there are indeed RRSIG records. Checking with tcpdump, I can see that DNS Python sends the correct query and receives correct replies (here, eight records): ``` 16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40) 16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain] ``` DNS Python 1.6.0 - Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44) [GCC 4.3.1] on linux2
2008/09/17
[ "https://Stackoverflow.com/questions/82607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
You probably mean RRSIG ANY (otherwise, the order is wrong, the class needs to be after the type) ``` >>> print myresolver.query('sources.org', 'RRSIG', 'ANY') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer dns.resolver.NoAnswer ```
RRSIG is not a record, it's a hashed digest of a valid DNS Record. You can query a DNSKEY record, set want\_dnssec=True and get a DNSKEY Record, and an "RRSIG of a DNSKEY Record". More generally, RRSIG is just a signature of a valid record (such as a DS Record). So when you ask the server ``` myresolver.query('sources.org', 'RRSIG') ``` It doesn't know what you are asking for. RRSIG in itself has no meaning, you need to specify *RRSIG of what?*
82,607
I get DNS records from a Python program, using [DNS Python](http://www.dnspython.org/) I can get various DNSSEC-related records: ``` >>> import dns.resolver >>> myresolver = dns.resolver.Resolver() >>> myresolver.use_edns(1, 0, 1400) >>> print myresolver.query('sources.org', 'DNSKEY') <dns.resolver.Answer object at 0xb78ed78c> >>> print myresolver.query('ripe.net', 'NSEC') <dns.resolver.Answer object at 0x8271c0c> ``` But no RRSIG records: ``` >>> print myresolver.query('sources.org', 'RRSIG') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer ``` I tried several signed domains like absolight.fr or ripe.net. Trying with dig, I see that there are indeed RRSIG records. Checking with tcpdump, I can see that DNS Python sends the correct query and receives correct replies (here, eight records): ``` 16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40) 16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain] ``` DNS Python 1.6.0 - Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44) [GCC 4.3.1] on linux2
2008/09/17
[ "https://Stackoverflow.com/questions/82607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
RRSIG is not a record, it's a hashed digest of a valid DNS Record. You can query a DNSKEY record, set want\_dnssec=True and get a DNSKEY Record, and an "RRSIG of a DNSKEY Record". More generally, RRSIG is just a signature of a valid record (such as a DS Record). So when you ask the server ``` myresolver.query('sources.org', 'RRSIG') ``` It doesn't know what you are asking for. RRSIG in itself has no meaning, you need to specify *RRSIG of what?*
This looks like a probable bug in the Python DNS library, although I don't read Python well enough to find it. Note that in any case your EDNS0 buffer size parameter is not large enough to handle the RRSIG records for sources.org, so your client and server would have to fail over to TCP/IP.
82,607
I get DNS records from a Python program, using [DNS Python](http://www.dnspython.org/) I can get various DNSSEC-related records: ``` >>> import dns.resolver >>> myresolver = dns.resolver.Resolver() >>> myresolver.use_edns(1, 0, 1400) >>> print myresolver.query('sources.org', 'DNSKEY') <dns.resolver.Answer object at 0xb78ed78c> >>> print myresolver.query('ripe.net', 'NSEC') <dns.resolver.Answer object at 0x8271c0c> ``` But no RRSIG records: ``` >>> print myresolver.query('sources.org', 'RRSIG') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answer = Answer(qname, rdtype, rdclass, response) File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 121, in __init__ raise NoAnswer ``` I tried several signed domains like absolight.fr or ripe.net. Trying with dig, I see that there are indeed RRSIG records. Checking with tcpdump, I can see that DNS Python sends the correct query and receives correct replies (here, eight records): ``` 16:09:39.342532 IP 192.134.4.69.53381 > 192.134.4.162.53: 22330+ [1au] RRSIG? sources.org. (40) 16:09:39.343229 IP 192.134.4.162.53 > 192.134.4.69.53381: 22330 8/5/6 RRSIG[|domain] ``` DNS Python 1.6.0 - Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44) [GCC 4.3.1] on linux2
2008/09/17
[ "https://Stackoverflow.com/questions/82607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
RRSIG is not a record, it's a hashed digest of a valid DNS Record. You can query a DNSKEY record, set want\_dnssec=True and get a DNSKEY Record, and an "RRSIG of a DNSKEY Record". More generally, RRSIG is just a signature of a valid record (such as a DS Record). So when you ask the server ``` myresolver.query('sources.org', 'RRSIG') ``` It doesn't know what you are asking for. RRSIG in itself has no meaning, you need to specify *RRSIG of what?*
You may want to use `raise_on_no_answer=False` and you will get the correct response: ``` resolver.query(hostname, dnsrecord, raise_on_no_answer=False) ```
45,368,847
Very related to this post but I don't have the priviledge to comment there so I had to make a new post. [Deploy a simple VS2017 Django app to Azure - server error](https://stackoverflow.com/questions/43506691/deploy-a-simple-vs2017-django-app-to-azure-server-error) I followed Silencer's tutorial there and I am getting this error from \LogFiles\wfastcgi.log: ``` 2017-07-28 08:28:57.746719: Activating virtualenv with D:\home\site\wwwroot\env\Scripts\python.exe 2017-07-28 08:28:57.777987: Error occurred while reading WSGI handler: Traceback (most recent call last): File "D:\home\python360x64\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "D:\home\python360x64\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "D:\home\python360x64\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File ".\ptvs_virtualenv_proxy.py", line 99, in get_virtualenv_handler execfile(activate_this, dict(__file__=activate_this)) File ".\ptvs_virtualenv_proxy.py", line 27, in execfile code = f.read() File "D:\Repos\azure-python-siteextensions\source_packages\python.3.6.0\tools\Lib\encodings\cp1252.py", line 23, in decode UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to <undefined> ``` I have installed python360x64 as an extension in azure portal, I am using this <https://github.com/Azure/azure-sdk-for-python/blob/master/examples/AzureResourceViewer/ptvs_virtualenv_proxy.py> And my web.config: ``` <configuration> <system.diagnostics> <trace> <listeners> <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics"> <filter type="" /> </add> </listeners> </trace> </system.diagnostics> <appSettings> <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="WSGI_ALT_VIRTUALENV_ACTIVATE_THIS" value="D:\home\site\wwwroot\env\Scripts\python.exe" /> <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_virtualenv_handler()" /> <add key="PYTHONPATH" value="D:\home\site\wwwroot" /> <add key="DJANGO_SETTINGS_MODULE" value="DjangoWebProject.settings" /> <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <add name="Python FastCGI" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python360x64\python.exe|D:\home\python360x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <rewrite> <rules> <rule name="Static Files" stopProcessing="true"> <conditions> <add input="true" pattern="false" /> </conditions> </rule> <rule name="Configure Python" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" /> </conditions> <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> </configuration> ``` My /env/ python version is python360x64. Any help appreciated!
2017/07/28
[ "https://Stackoverflow.com/questions/45368847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335827/" ]
I had the same problem and finally it was fixed by changing this line in app config: ``` <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_virtualenv_handler()" /> ``` to this: ``` <add key="WSGI_HANDLER" value="myProject.wsgi.application" /> ``` myProject is the name of my django project so you should put the your project's name.
I get the same errors in python 3.4. For python 2.7 there is an activate\_this.py script, which can help in some way. Just put the activate\_this.py from a python 2.7 virtual environment in the .\env\Scripts folder and changed the path in web.config to point to activate\_this.py. It seems to work. I am just not sure which version of python I am using now as 2.7 is still present on the system.
45,368,847
Very related to this post but I don't have the priviledge to comment there so I had to make a new post. [Deploy a simple VS2017 Django app to Azure - server error](https://stackoverflow.com/questions/43506691/deploy-a-simple-vs2017-django-app-to-azure-server-error) I followed Silencer's tutorial there and I am getting this error from \LogFiles\wfastcgi.log: ``` 2017-07-28 08:28:57.746719: Activating virtualenv with D:\home\site\wwwroot\env\Scripts\python.exe 2017-07-28 08:28:57.777987: Error occurred while reading WSGI handler: Traceback (most recent call last): File "D:\home\python360x64\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "D:\home\python360x64\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "D:\home\python360x64\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File ".\ptvs_virtualenv_proxy.py", line 99, in get_virtualenv_handler execfile(activate_this, dict(__file__=activate_this)) File ".\ptvs_virtualenv_proxy.py", line 27, in execfile code = f.read() File "D:\Repos\azure-python-siteextensions\source_packages\python.3.6.0\tools\Lib\encodings\cp1252.py", line 23, in decode UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to <undefined> ``` I have installed python360x64 as an extension in azure portal, I am using this <https://github.com/Azure/azure-sdk-for-python/blob/master/examples/AzureResourceViewer/ptvs_virtualenv_proxy.py> And my web.config: ``` <configuration> <system.diagnostics> <trace> <listeners> <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics"> <filter type="" /> </add> </listeners> </trace> </system.diagnostics> <appSettings> <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="WSGI_ALT_VIRTUALENV_ACTIVATE_THIS" value="D:\home\site\wwwroot\env\Scripts\python.exe" /> <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_virtualenv_handler()" /> <add key="PYTHONPATH" value="D:\home\site\wwwroot" /> <add key="DJANGO_SETTINGS_MODULE" value="DjangoWebProject.settings" /> <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <add name="Python FastCGI" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python360x64\python.exe|D:\home\python360x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <rewrite> <rules> <rule name="Static Files" stopProcessing="true"> <conditions> <add input="true" pattern="false" /> </conditions> </rule> <rule name="Configure Python" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" /> </conditions> <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> </configuration> ``` My /env/ python version is python360x64. Any help appreciated!
2017/07/28
[ "https://Stackoverflow.com/questions/45368847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335827/" ]
I had the same problem and finally it was fixed by changing this line in app config: ``` <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_virtualenv_handler()" /> ``` to this: ``` <add key="WSGI_HANDLER" value="myProject.wsgi.application" /> ``` myProject is the name of my django project so you should put the your project's name.
I had same problem, I was wrong in WSGI\_HANDLER, for python 3.4 must be: ``` <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_venv_handler()" /> ```
31,096,631
I am currently writing a script that installs my software-under-test then automatically runs my smoke tests using py.test. If a failure occurs during any of these tests, I would like to tell my software to not publish the software to the build servers. This is basically how it goes in pseudo-code: ``` def install_build_and_test(): # some python code installs some_build install_my_build(some_build) # then I want to test my build subprocess.Popen(["py.test", "smoke_test_suite.py"]) # test_failures = ??? # If any failures occurred during testing, do not publish build if test_failures is True: print "Build will not publish because there were errors in your logs" if test_failures is False: publish_build(some_build) ``` My question here is how do I use pytest failures to tell my install\_and\_test\_build code to not publish some\_build?
2015/06/28
[ "https://Stackoverflow.com/questions/31096631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4621806/" ]
Approach #1 =========== This is I think the road you were heading down. Basically, just treat test.py as a black box process and use the exit code to determine if there were any test failures (e.g. if there is a non-zero exit code) ``` exit_code = subprocess.Popen(["py.test", "smoke_test_suite.py"]).wait() test_failures = bool(exit_code) ``` Approach #2 =========== Another even cleaner way is to [run py.test in python directly](https://pytest.org/latest/usage.html#calling-pytest-from-python-code). ``` import pytest exit_code = pytest.main("smoke_test_suite.py") test_failures = bool(exit_code) ```
py.test must return a non-zero exit code if the tests fail. The simplest way to handle that would be using [`subprocess.check_call()`](https://docs.python.org/2/library/subprocess.html#subprocess.check_call): ``` try: subprocess.check_call(["py.test", "smoke_test_suite.py"]) except subprocess.CalledProcessError: print "Smoke tests have failed, not publishing" else: print "Smoke tests have passed, publishing" # ... ```
41,724,259
Happy new year 2017! Hello everybody! I have some issues when I try to deploy my docker image in a BlueMix container (where `cf ic run = docker run`) I can't access the container from web even if the image is running well inside. I pinged the binded adress: ``` ping 169.46.18.91 PING 169.46.18.91 (169.46.18.91): 56 data bytes 64 bytes from 169.46.18.91: icmp_seq=0 ttl=48 time=124.247 ms 64 bytes from 169.46.18.91: icmp_seq=1 ttl=48 time=122.701 ms ``` The image was working locally but now that I gave it an IP and hosted it on bluemix container service, I have reported an issue while the image is setting up after `cf ic -v run` command Here are the logs of the command: ``` cf ic -v run -p 3000 --name bootingtest 1ed1b527771b DEMANDE : [2017-01-18T10:32:31+01:00] POST /UAALoginServerWAR/oauth/token HTTP/1.1 Host: login.ng.bluemix.net Accept: application/json Authorization: [DONNEES PRIVEES MASQUEES] Connection: close Content-Type: application/x-www-form-urlencoded User-Agent: go-cli 6.22.2+a95e24c / darwin grant_type=refresh_token&refresh_token=eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIwNzJlYTFmNy00NGRlLTRmYmYtODUxOS1lNmU0NmU2MTk1Y2ItciIsInN1YiI6ImZkMWVmM2Q3LTI2OTQtNDQ4Ni1iNjY2LWRmNTVjY2M4MzVmOCIsInNjb3BlIjpbIm9wZW5pZCIsInVhYS51c2VyIiwiY2xvdWRfY29udHJvbGxlci5yZWFkIiwicGFzc3dvcmQud3JpdGUiLCJjbG91ZF9jb250cm9sbGVyLndyaXRlIl0sImlhdCI6MTQ4NDczMTE3MSwiZXhwIjoxNDg3MzIzMTcxLCJjaWQiOiJjZiIsImNsaWVudF9pZCI6ImNmIiwiaXNzIjoiaHR0cHM6Ly91YWEubmcuYmx1ZW1peC5uZXQvb2F1dGgvdG9rZW4iLCJ6aWQiOiJ1YWEiLCJncmFudF90eXBlIjoicGFzc3dvcmQiLCJ1c2VyX25hbWUiOiJlbW1hbnVlbC5zb2xvbUBmci5pYm0uY29tIiwib3JpZ2luIjoidWFhIiwidXNlcl9pZCI6ImZkMWVmM2Q3LTI2OTQtNDQ4Ni1iNjY2LWRmNTVjY2M4MzVmOCIsInJldl9zaWciOiI2MWNkZjM4MiIsImF1ZCI6WyJjZiIsIm9wZW5pZCIsInVhYSIsImNsb3VkX2NvbnRyb2xsZXIiLCJwYXNzd29yZCJdfQ._gxevCN9cCYX3Fw_FUEYvxFsRhHqfOT9KhjZFiHcNao&scope= REPONSE : [2017-01-18T10:32:32+01:00] HTTP/1.1 200 OK Connection: close Transfer-Encoding: chunked Cache-Control: no-cache, no-store, max-age=0, must-revalidate,no-store Content-Security-Policy: default-src 'self' www.ibm.com 'unsafe-inline'; Content-Type: application/json;charset=UTF-8 Date: Wed, 18 Jan 2017 09:32:31 GMT Expires: 0 Pragma: no-cache,no-cache Server: Apache-Coyote/1.1 Strict-Transport-Security: max-age=2592000 ; includeSubDomains X-Backside-Transport: OK OK,OK OK X-Client-Ip: 91.151.65.169 X-Content-Type-Options: nosniff X-Frame-Options: DENY X-Global-Transaction-Id: 1804077409 X-Powered-By: Servlet/3.1 X-Vcap-Request-Id: e683d47d-28aa-43c1-6356-d5818dfd86f1 X-Xss-Protection: 1; mode=block 6f6 {"access_token":"[DONNEES PRIVEES MASQUEES]","token_type":"[DONNEES PRIVEES MASQUEES]","refresh_token":"[DONNEES PRIVEES MASQUEES]","expires_in":1209599,"scope":"cloud_controller.read password.write cloud_controller.write openid uaa.user","jti":"edcd9c51-4521-4f49-bf03-def030e81626"} 0 a9dc3ad4-1a34-4848-9b16-8d1410b79a06 ``` So is there a way to set up the connection from a "close" state to a "waiting for incoming connection" state when i'm running or building the image? Something like an option `cf ic (docker) run -p 3000 --accept_all imageid cmd` (I didn't saw it in the --help menu) or maybe you saw something wrong elsewhere? I thought about logging into the container with `docker exec -it ID /bin/bash` but I don't know a bash command to accept all incoming connection... (and moreover I think it's the bash of the VM not the container itself) Thank you for your answers and have a good day! Emmanuel --- **Other infos**: Dockerfile ``` FROM ubuntu:14.04 RUN apt-get update && apt-get -y install python2.7 RUN apt-get -y install python-pip RUN pip install Flask RUN pip install ibmiotf RUN pip install requests RUN pip install flask-socketio RUN pip install cloudant ENV PORT=12345 EXPOSE 12345 ADD ./SIARA /opt/SIARA/ WORKDIR /opt/SIARA/ CMD sleep 80 && python testGUI.py ``` Flask server port mapping and running: ``` if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) socketio.run(app, host='0.0.0.0', port=port) ``` --- **Clues** I had this warning messages when I used to test my image locally they weren't responsible of any crash but maybe now it's on the cloud this kind of error are responsible of the unsuccessful connection attempt from web? tl;dr: apparently SSH connection are not available since (apparently) my version of python (2.7) needs an update (??) But SSH aren't supposed to be relevant only in case of https:// connection? ``` cf ic logs -ft guiplay 2017-01-19T09:17:38.870006264Z /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:334: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings 32017-01-19T09:17:38.870062551Z SNIMissingWarning �2017-01-19T09:17:38.870081733Z /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:132: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings 92017-01-19T09:17:38.870089026Z InsecurePlatformWarning �2017-01-19T09:17:39.145906849Z /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:132: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings 92017-01-19T09:17:39.145950355Z InsecurePlatformWarning �2017-01-19T09:17:39.186165706Z WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved performance. Y2017-01-19T09:17:39.192990810Z * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) ```
2017/01/18
[ "https://Stackoverflow.com/questions/41724259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7365430/" ]
Hmm - I see that you published port 3000 (the -p 3000 parameter in the run command), but the default port would be 5000. In the dockerfile, you switched that to 12345, so that's presumably what you're actually listening on there. Guessing that's the reason you want to open all ports? Docker only exposes the ports that you tell it to - adding an additional -p 5000 for that default, or -p 12345 according to that Dockerfile, or both should allow you to connect to the app in those cases. Or, if you want to just publish all the ports that are EXPOSEd via the Dockerfile (in this case, that would be 12345), use the -P parameter. More info: running in the cloud, there is additional security that your container is only accessible via the ports you want published. Within a space (in the private ips from other containers in the same space, or definitely from within the container itself), you should still be able to access those ports. From external, though, only the ports you have published should be accessible. I don't see a way to effectively publish \* (and, that seems like a rather questionable practice from a security standpoint)
Looks like Bluemix single container service is a bit touchy, it was hard to reach from web until I added a "scalable" container which asks for the required HTTP port. I think the problem was this http port wasn't exposed, but now problem is solved the way I said above.
28,478,279
Hi I have this sample path "\10.81.67.162" which is a remote server (windows OS) I want to be able to transfer files (local) to the remote server using paramiko in python. I can make it work if the server is in linux. This is my sample code ``` import paramiko import base64 username = 'username' password = 'password' host = "10.81.67.162" port = 22 transport = paramiko.Transport((host,port)) transport.connect(username = username, password = password) stfp = paramiko.SFTPClient.from_transport(transport) ``` But having thhis error in windows: ``` Traceback (most recent call last): File "ssh.py", line 9, in <module> transport = paramiko.Transport((host,port)) File "build\bdist.win32\egg\paramiko\transport.py", line 289, in __init__ File "C:\Python27\lib\socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 10061] No connection could be made because the target machi ne actively refused it ``` Python version 2.7 Paramiko version 1.7.5 Thanks!
2015/02/12
[ "https://Stackoverflow.com/questions/28478279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3728094/" ]
If you are asking about method argument and method internal variables the answer is no. These variables are allocated on stack and are different for each thread. EDIT: Issues may happen when passing shared (among several threads) not thread safe objects. For example your method `foo()` accepts parameter of type `MyClass`: ``` foo(MyClass param) {} ``` Somewhere into `foo()` you call `param.bar()` that operates (directly or indirectly) with not thread safe member variable. In this case you will get race condition. (thanks to @lexicore) The threads synchronization issues are relevant however for class fields.
There shouldn't be any problems with your code since you don't manipulate the `parameters` (e.g. `adding/removing` stuff from the maps ). of course there is this assumption that those maps are not related (e.g `sharing same resources`) **AND** no where else in you program you will manipulate those objects at the same time of this method is running. Yes my explanation may give the readers some headache. but out of experience working with `map` and `multi-threaded programming`, there could be tons of other stuff that could go wrong. So a word of advice try to make your program as `thread-safe` as possible, even though you are very sure that nothing would go wrong.
54,675,259
I am answering the Euler project questions in python and I don't know how to multiply a list by itself I can get a list within the range though
2019/02/13
[ "https://Stackoverflow.com/questions/54675259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11051957/" ]
Seems like this should do it: ``` SET Row1 = CASE WHEN Row1 = 'From1' THEN 'To1' WHEN Row1 = 'From2' THEN 'To2' etc END ```
Are you simply looking for a `case` expression? ``` UPDATE TOP (@batchsize) Table1 SET Row1 = (CASE table1.Row1 WHEN 'From1' THEN 'To1' WHEN 'From2' THEN 'To2' WHEN 'From3' THEN 'To3' WHEN 'From4' THEN 'To4' WHEN 'From5' THEN 'To5' END) FROM (SELECT TOP (@batchsize) Id FROM Table1 ORDER BY TimeStamp DESC ) tto WHERE Table1.Row1 in ('From1', 'From2', 'From3', 'From4', 'From5') AND Table1.Id = tto.Id; ```
69,067,530
I installed several files based upon `https://pbpython.com/pdf-reports.htm to create reports. However the following error messages ``` Traceback (most recent call last): File "C:\histdata\test02.py", line 10, in <module> from weasyprint import HTML File "C:\Users\AquaTrader\AppData\Local\Programs\Python\Python38\lib\site-packages\weasyprint\__init__.py", line 322, in <module> from .css import preprocess_stylesheet # noqa isort:skip File "C:\Users\AquaTrader\AppData\Local\Programs\Python\Python38\lib\site-packages\weasyprint\css\__init__.py", line 27, in <module> from . import computed_values, counters, media_queries File "C:\Users\AquaTrader\AppData\Local\Programs\Python\Python38\lib\site-packages\weasyprint\css\computed_values.py", line 16, in <module> from ..text.ffi import ffi, pango, units_to_double File "C:\Users\AquaTrader\AppData\Local\Programs\Python\Python38\lib\site-packages\weasyprint\text\ffi.py", line 380, in <module> gobject = _dlopen( File "C:\Users\AquaTrader\AppData\Local\Programs\Python\Python38\lib\site-packages\weasyprint\text\ffi.py", line 377, in _dlopen return ffi.dlopen(names[0]) # pragma: no cover File "C:\Users\AquaTrader\AppData\Local\Programs\Python\Python38\lib\site-packages\cffi\api.py", line 150, in dlopen lib, function_cache = _make_ffi_library(self, name, flags) File "C:\Users\AquaTrader\AppData\Local\Programs\Python\Python38\lib\site-packages\cffi\api.py", line 832, in _make_ffi_library backendlib = _load_backend_lib(backend, libname, flags) File "C:\Users\AquaTrader\AppData\Local\Programs\Python\Python38\lib\site-packages\cffi\api.py", line 827, in _load_backend_lib raise OSError(msg) OSError: cannot load library 'gobject-2.0-0': error 0x7e. Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0' ``` Any suggestions? Thanks in advance. (Please note that there is a similar issue on github which tells the individual to install GTK3.) Is this correct?
2021/09/05
[ "https://Stackoverflow.com/questions/69067530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6090578/" ]
The error means that the `gobject-2.0.0` library, which is part of GTK3+, cannot be found. Did you follow the installation instructions (<https://doc.courtbouillon.org/weasyprint/stable/first_steps.html>), which include installation of GTK3+? If no, do that. If yes, then the problem is, that the GTK3+ DLLs are not where Python is looking for them. For this, you need to add the directory containing the DLLs (e.g. `C:\Program Files\GTK3-Runtime Win64\bin` on Windows) to your PATH environment variable. That directory contains the relevant `libgobject-2.0-0.dll` library. For Python 3.8+ and weasyprint 54+ you can manually set the path to your GTK3+ library with the environment variable `WEASYPRINT_DLL_DIRECTORIES` ([documentation](https://doc.courtbouillon.org/weasyprint/v54.0b1/first_steps.html#missing-library)).
As @mad said, you need the GTK3 library to have the `libobject-2.0.0` DLL. In Github Actions for example, you might be interested to use the [tschoonj/GTK-for-Windows](https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer) repository : ```sh # Download GTK3 resources git clone -b 2022-01-04 https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer GTK cd GTK # Add it to classic Windows install PATH $Env:PATH += "$PWD\gtk-nsis-pack\bin" # Add it to GitHub Actions PATH # echo "$PWD\gtk-nsis-pack\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append ```
16,819,938
I have a class which would be a container for a number of variables of different types. The collection is finite and not very large so I didn't use a dictionary. Is there a way to automate, or shorten the creation of variables based on whether or not they are requested (specified as True/False) in the constructor? Here is what I have for example: ``` class test: def __init__(self,a=False,b=False,c=False): if a: self.a = {} if b: self.b = 34 if c: self.c = "generic string" ``` For any of a,b,c that are true in the constructor they will be created in the object. I have a collection of standard variables (a,b,c,d..) that some objects will have and some objects won't. The number of combinations is too large to create separate classes, but the number of variables isn't enough to have a dictionary for them in each class. Is there any way in python to do something like this: ``` class test: def __init__(self,*args): default_values = {a:{},b:34,c:"generic string"} for item in args: if item: self.arg = default_values[arg] ``` Maybe there is a whole other way to do this? EDIT: To clarify this a class which represents different type of bounding boxes on a 2D surface. Depending on the function of the box it can have any of frame coordinates, internal cross coordinates, id, population statistics (attached to that box), and some other cached values for easy calculation. I don't want to have each object as a dictionary because there are methods attached to it which allow it to export and modify its internal data and interact with other objects of the same type (similar to how strings interact with + - .join, etc.). I also don't want to have a dictionary inside each object because the call to that variable is inelegant: ``` print foo.info["a"] ``` versus ``` print foo.a ``` Thanks to ballsdotball I've come up with a solution: ``` class test: def __init__(self, a=False, b=False,c =False): default_values = {"a":{},"b":34,"c":"generic string"} for k, v in default_values.iteritems(): if eval(k): setattr(self,k,v) ```
2013/05/29
[ "https://Stackoverflow.com/questions/16819938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2433420/" ]
Maybe something like: ``` def __init__(self,*args,**kwargs): default_values = {a:{},b:34,c:"generic string"} for k,v in kwargs.iteritems(): try: if not v is False: setattr(self,k,default_values[k]) except Exception, e: print "Argument has no default value.",e ``` But to be honest I would just put the default values in with the init arguments instead of having to test for them like that. \*Edited a couple times for syntax.
You can subclass `dict` (if you aren't using positional arguments): ``` class Test(dict): def your_method(self): return self['foo'] * 4 ``` You can also override `__getattr__` and `__setattr__` if the `self['foo']` syntax bothers you: ``` class Test(dict): def __getattr__(self, key): return dict.__getattr__(self, key) def __setattr__(self, key, value): return dict.__getattr__(self, key, value) def your_method(self): return self.foo * 4 ```
50,271,354
Consider the following python snippet (I am running Python 3) ``` name = "Sammy" def greet(): name = 'johny' def hello(): print('hello ' + name) # gets 'name' from the enclosing 'greet' hello() greet() ``` This produces the output `hello johny` as expected However, ``` x = 50 def func1(): x = 20 def func2(): print("x is ", x) # Generates error here x = 2 print("Changed the local x to ",x) func2() func1() print("x is still ",x) ``` generates an `UnboundLocalError: local variable 'x' referenced before assignment`. Why does the first snippet work, whereas the second doesn't?
2018/05/10
[ "https://Stackoverflow.com/questions/50271354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5157905/" ]
The error is actually caused (indirectly) by the following line, i.e. `x = 2`. Try commenting out that line and you'll see that the function works. The fact that there is an assignment to a variable named `x` makes `x` local to the function at *compile time*, however, at *execution time* the first reference to `x` fails because, at the time that the `print()` statement is executed, it does not exist yet *in the current scope*. Correct it by using [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement) in `func2()`: ``` def func2(): nonlocal x print("x is ", x) x = 2 print("Changed the local x to ",x) ``` The reason that the first function (`greet()`) works is because it's OK to read variables in an outer scope, however, you can not assign to them unless you specify that the variable exists in an outer scope (with `nonlocal` or `global`). You can assign to a variable of the same name, however, that would create a new local variable, not the variable in the outer scope. So this also works: ``` def func1(): x = 20 def func2(): x = 2 print('Inner x is', x) func2() print('Outer x is', x) ``` Here `x` is assigned to before being referenced. This creates a new variable named `x` in the scope of function `func2()` which shadows the `x` defined in `func1()`.
In a given scope, *you can only reference a variable's name from one given scope*. Your variable cannot be global at some point and local later on or vice versa. For that reason, if `x` is ever to be declared in a scope, Python will assume that you are refering to the local variable everywhere in that scope, unless you explicitly state otherwise. This is why you first function, `greet`, works. The variable `name` is unambiguously coming from the closure. Although, in `func2` the variable `x` is used in the scope and thus you cannot reference the `x` from the closure unless explicitly stating otherwise with [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement). The following errors might enlighten us on this. A variable cannot become global after use ----------------------------------------- ``` def func1(): x = 20 def func2(): print("x is ", x) global x print("Changed the local x to ",x) func2() ``` This raises a `SyntaxError: name 'x' is used prior to global declaration`. This means that the closure's `x` cannot be used and then the global one. A global variable cannot become local ------------------------------------- Here is another case using `global` at the top of `func2`. ``` def func1(): x = 20 def func2(): global x print("x is ", x) x = 2 print("Changed the local x to ",x) func2() ``` This code was exectued without error, but notice that the assignment to `x` updated the global variable, it did not make `x` become local again.
55,717,203
I wrote this small function: ``` def sets(): set1 = random.sample(range(1, 50), 10) set2 = random.sample(range(1, 50), 10) return(set1,set2) sets() ``` The output of this function looks like this: ``` ([24, 29, 43, 42, 45, 28, 26, 3, 8, 21], [22, 37, 38, 44, 25, 42, 29, 7, 35, 9]) ``` I want to plot this in a two way Venn diagram. I know how to plot the NUMBERS of overlap between the sets using the matplotlib, i.e. using [this](https://python-graph-gallery.com/170-basic-venn-diagram-with-2-groups/) exact code; however I want to plot the ACTUAL VALUES in the plot instead. i.e. the overlap between the two should read: 29,42 as these are the two items in common, and not the number 2, to represent the number of numbers that overlap. Would someone know how to do this?
2019/04/16
[ "https://Stackoverflow.com/questions/55717203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8407951/" ]
A possible solution is to output the labels instead of the set size. With the [matplotlib\_venn](https://pypi.org/project/matplotlib-venn/) package, you can do something like this: ``` import matplotlib.pyplot as plt from matplotlib_venn import venn2 import random set1 = set(random.sample(range(1, 50), 10)) set2 = set(random.sample(range(1, 50), 10)) venn = venn2([set1,set2], ('Group A', 'Group B')) venn.get_label_by_id('100').set_text('\n'.join(map(str,set1-set2))) venn.get_label_by_id('110').set_text('\n'.join(map(str,set1&set2))) venn.get_label_by_id('010').set_text('\n'.join(map(str,set2-set1))) plt.axis('on') plt.show() ``` We're accessing the labels by a binary ID, which denotes the sets. [![enter image description here](https://i.stack.imgur.com/PopoC.png)](https://i.stack.imgur.com/PopoC.png)
The default behaviour of the venn2 package is to print the size of the overlap of the two sets. Here's the line of the source code where those sizes are added to the Venn diagram plot: <https://github.com/konstantint/matplotlib-venn/blob/master/matplotlib_venn/_venn2.py#L247> To make this print the overlapping numbers you'll have to change the **compute\_venn2\_subsets(a,b)** function in this file. Replace the returned argument of **compute\_venn2\_subsets(a,b)** with: ``` ([val for val in a if val not in b], [val for val in a if val in b], [val for val in b if val not in a]) ``` instead of the set sizes that it's returning right now. If you only want to print the overlapping columns, then make **compute\_venn2\_subsets(a,b)** return ``` ("", [val for val in a if val in b], "") ```
63,416,534
I've recently tried to create a simple bot in discord with Python Code. I'm testing just the first features to DM a user when he joins the server Here is my code: ``` import os import discord from dotenv import load_dotenv load_dotenv() #load .env files TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') client = discord.Client() @client.event async def on_ready(): guild = discord.utils.get(client.guilds, name=GUILD) print( f'{client.user} has connected to the following guild:\n' f'{guild.name}(id: {guild.id})' ) #debug members = '\n - '.join([member.name for member in guild.members]) print(f'Guild Members:\n - {members}') #debug @client.event async def on_member_join(member): await member.creat_dm() await member.dm_channel.send( f'Hi {member.name}, welcome to my Discord Server!' ) client.run(TOKEN) ``` ``` Ignoring exception in on_member_join Traceback (most recent call last): File "/home/andre/.local/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event await coro(*args, **kwargs) File "/home/andre/repos/github/discord_project/bot.py", line 30, in on_member_join await member.creat_dm() AttributeError: 'Member' object has no attribute 'creat_dm' ``` Can anyone help me with this annoying bug? I've seen articles that show `member.create_dm()` being used
2020/08/14
[ "https://Stackoverflow.com/questions/63416534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13461081/" ]
So You Need To Edit Your Code Sligitly Store Orginal Image To a temp for a while ``` originalBlue = image[i][j].rgbtBlue; originalRed = image[i][j].rgbtRed; originalGreen = image[i][j].rgbtGreen; ``` the result of each of these formulas may not be an integer so use float and round them to nearest integer ``` sepiaRed = round(.393 * originalRed + .769 * originalGreen + .189 * originalBlue); sepiaGreen = round(.349 * originalRed + .686 * originalGreen + .168 * originalBlue); sepiaBlue = round(.272 * originalRed + .534 * originalGreen + .131 * originalBlue); if (sepiaRed > 255) { sepiaRed = 255; } if (sepiaGreen > 255) { sepiaGreen = 255; } if (sepiaBlue > 255) { sepiaBlue = 255; } ``` now store the values to the orignal ones ``` image[i][j].rgbtBlue = sepiaBlue; image[i][j].rgbtRed = sepiaRed; image[i][j].rgbtGreen = sepiaGreen; ``` **Declare all Variable Outside For Loop** ``` float sepiaRed; float sepiaBlue; float sepiaGreen; int originalRed; int originalBlue; int originalGreen; ``` I Hope It's Help
You need to use "saturation math". For near white colors, your intermediate values (e.g. `sepiared`) can exceed 255. 255 (0xFF) is the maximum value that can fit in an `unsigned char` For example, if `sepiared` were 256 (0x100), when it gets put into `rgbtRed`, only the rightmost 8 bits will be retained and the value will be *truncated* to 0. So, instead of a very bright value [near white], you'll end up with a very dark value [near black]. To fix this, add: ``` if (sepiared > 255) sepiared = 255; ``` --- Also, note with the ordering of your `for` loops, it is very cache inefficient. And, it's wasteful [and can be slow] to use `image[i][j].whatever` everywhere. Better to use a pointer to the current pixel. Anyway, here's an updated version of your code with these changes: ``` void sepia(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE *pix; for (int i = 0; i < height; i++) { pix = &image[i][0]; for (int j = 0; j < width; j++, pix++) { int sepiared = pix->rgbtRed * .393 + pix->rgbtGreen * .769 + pix->rgbtBlue * .189; int sepiagreen = pix->rgbtRed * .349 + pix->rgbtGreen * .686 + pix->rgbtBlue * .168; int sepiablue = pix->rgbtRed * .272 + pix->rgbtGreen * .534 + pix->rgbtBlue * .131; if (sepiared > 255) sepiared = 255; if (sepiagreen > 255) sepiagreen = 255; if (sepiablue > 255) sepiablue = 255; pix->rgbtRed = sepiared; pix->rgbtGreen = sepiagreen; pix->rgbtBlue = sepiablue; } } } ``` --- Also, note that it can be a bit slow to use floating point math on pixel images. In this case, it's faster/better to use scaled integer math. Here's a version that does that: ``` void sepia(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE *pix; for (int i = 0; i < height; i++) { pix = &image[i][0]; for (int j = 0; j < width; j++, pix++) { int sepiared = pix->rgbtRed * 393 + pix->rgbtGreen * 769 + pix->rgbtBlue * 189; int sepiagreen = pix->rgbtRed * 349 + pix->rgbtGreen * 686 + pix->rgbtBlue * 168; int sepiablue = pix->rgbtRed * 272 + pix->rgbtGreen * 534 + pix->rgbtBlue * 131; sepiared /= 1000; sepiagreen /= 1000; sepiablue /= 1000; if (sepiared > 255) sepiared = 255; if (sepiagreen > 255) sepiagreen = 255; if (sepiablue > 255) sepiablue = 255; pix->rgbtRed = sepiared; pix->rgbtGreen = sepiagreen; pix->rgbtBlue = sepiablue; } } } ```
63,416,534
I've recently tried to create a simple bot in discord with Python Code. I'm testing just the first features to DM a user when he joins the server Here is my code: ``` import os import discord from dotenv import load_dotenv load_dotenv() #load .env files TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') client = discord.Client() @client.event async def on_ready(): guild = discord.utils.get(client.guilds, name=GUILD) print( f'{client.user} has connected to the following guild:\n' f'{guild.name}(id: {guild.id})' ) #debug members = '\n - '.join([member.name for member in guild.members]) print(f'Guild Members:\n - {members}') #debug @client.event async def on_member_join(member): await member.creat_dm() await member.dm_channel.send( f'Hi {member.name}, welcome to my Discord Server!' ) client.run(TOKEN) ``` ``` Ignoring exception in on_member_join Traceback (most recent call last): File "/home/andre/.local/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event await coro(*args, **kwargs) File "/home/andre/repos/github/discord_project/bot.py", line 30, in on_member_join await member.creat_dm() AttributeError: 'Member' object has no attribute 'creat_dm' ``` Can anyone help me with this annoying bug? I've seen articles that show `member.create_dm()` being used
2020/08/14
[ "https://Stackoverflow.com/questions/63416534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13461081/" ]
First, as an aside, when you have a CS50 question, please search for the keywords in StackOverflow before asking. The answer is probably there. If you search for `sepia RGBTRIPLE cs50` you get quite a few hits. After doing a lot of pixel processing, you'll hone some useful debugging intuitions. Among those: * If you see diagonal offsets, your image's bytes-per-row may be greater than the width times the pixel size. (Especially in YCbCr images or on platforms where image buffers are aligned to 128-bit vector sizes.) * 2x or 0.5x image displays probably mean you're not heeding the scale value on a Retina display. * Certain colorspace errors will point you immediately to BGR vs RGB byte ordering issues. No blue channel at all or all blue? Probably mixing ARGB with BGRA. But more to the point: * If you see wackiness in the bright or color-saturated areas, your pixel component values are probably oversaturating (exceeding the maximum value, and dropping the high bit(s)). Every time you either (1) multiply a color component by a number great than 1 or (2) add multiple color components together, you need to think about what happens if you exceed the maximum value. If your intermediate math will add two values and then divide by 2, make sure your compiled operations will be using a large enough variable size to hold that extra bit. So in your inner loop here, when operating on a white pixel, almost every color component will exceed 255 (i.e. red and green will exceed, but not blue, because sepia is low in blue): ``` int sepiared = image[i][j].rgbtRed *.393 + image[i][j].rgbtGreen *.769 + image[i][j].rgbtBlue *.189; int sepiagreen = image[i][j].rgbtRed *.349 + image[i][j].rgbtGreen *.686 + image[i][j].rgbtBlue *.168; int sepiablue = image[i][j].rgbtRed *.272 + image[i][j].rgbtGreen *.534 + image[i][j].rgbtBlue *.131; ``` The resulting value would be {255, 255, 255} x {.393+.769+.189, .349+.686+.168, .272+.534+.131}, or {344.5, 306.8, 238.9}. But because you don't have that enough bits for those values in the BYTE components of an RGBTRIPLE struct, your values will be incorrect. So instead, you can do this: ``` int sepiared = (int) image[i][j].rgbtRed *.393 + image[i][j].rgbtGreen *.769 + image[i][j].rgbtBlue *.189; int sepiagreen = (int) image[i][j].rgbtRed *.349 + image[i][j].rgbtGreen *.686 + image[i][j].rgbtBlue *.168; int sepiablue = (int) image[i][j].rgbtRed *.272 + image[i][j].rgbtGreen *.534 + image[i][j].rgbtBlue *.131; sepiared = min(sepiared, 255); sepiagreen = min(sepiagreen, 255); sepiablue = min(sepiablue, 255); ``` Note that I have made two changes: 1. Cast the first value in each expression to (int); otherwise the calculation will be done on bytes and you'll lose your high bit. 2. Enforce the maximum value of 255 on each pixel component. When considering the other answers, please add my first fix. Checking for a max of 255 won't help if you've already dropped your high bit!
You need to use "saturation math". For near white colors, your intermediate values (e.g. `sepiared`) can exceed 255. 255 (0xFF) is the maximum value that can fit in an `unsigned char` For example, if `sepiared` were 256 (0x100), when it gets put into `rgbtRed`, only the rightmost 8 bits will be retained and the value will be *truncated* to 0. So, instead of a very bright value [near white], you'll end up with a very dark value [near black]. To fix this, add: ``` if (sepiared > 255) sepiared = 255; ``` --- Also, note with the ordering of your `for` loops, it is very cache inefficient. And, it's wasteful [and can be slow] to use `image[i][j].whatever` everywhere. Better to use a pointer to the current pixel. Anyway, here's an updated version of your code with these changes: ``` void sepia(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE *pix; for (int i = 0; i < height; i++) { pix = &image[i][0]; for (int j = 0; j < width; j++, pix++) { int sepiared = pix->rgbtRed * .393 + pix->rgbtGreen * .769 + pix->rgbtBlue * .189; int sepiagreen = pix->rgbtRed * .349 + pix->rgbtGreen * .686 + pix->rgbtBlue * .168; int sepiablue = pix->rgbtRed * .272 + pix->rgbtGreen * .534 + pix->rgbtBlue * .131; if (sepiared > 255) sepiared = 255; if (sepiagreen > 255) sepiagreen = 255; if (sepiablue > 255) sepiablue = 255; pix->rgbtRed = sepiared; pix->rgbtGreen = sepiagreen; pix->rgbtBlue = sepiablue; } } } ``` --- Also, note that it can be a bit slow to use floating point math on pixel images. In this case, it's faster/better to use scaled integer math. Here's a version that does that: ``` void sepia(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE *pix; for (int i = 0; i < height; i++) { pix = &image[i][0]; for (int j = 0; j < width; j++, pix++) { int sepiared = pix->rgbtRed * 393 + pix->rgbtGreen * 769 + pix->rgbtBlue * 189; int sepiagreen = pix->rgbtRed * 349 + pix->rgbtGreen * 686 + pix->rgbtBlue * 168; int sepiablue = pix->rgbtRed * 272 + pix->rgbtGreen * 534 + pix->rgbtBlue * 131; sepiared /= 1000; sepiagreen /= 1000; sepiablue /= 1000; if (sepiared > 255) sepiared = 255; if (sepiagreen > 255) sepiagreen = 255; if (sepiablue > 255) sepiablue = 255; pix->rgbtRed = sepiared; pix->rgbtGreen = sepiagreen; pix->rgbtBlue = sepiablue; } } } ```
63,416,534
I've recently tried to create a simple bot in discord with Python Code. I'm testing just the first features to DM a user when he joins the server Here is my code: ``` import os import discord from dotenv import load_dotenv load_dotenv() #load .env files TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') client = discord.Client() @client.event async def on_ready(): guild = discord.utils.get(client.guilds, name=GUILD) print( f'{client.user} has connected to the following guild:\n' f'{guild.name}(id: {guild.id})' ) #debug members = '\n - '.join([member.name for member in guild.members]) print(f'Guild Members:\n - {members}') #debug @client.event async def on_member_join(member): await member.creat_dm() await member.dm_channel.send( f'Hi {member.name}, welcome to my Discord Server!' ) client.run(TOKEN) ``` ``` Ignoring exception in on_member_join Traceback (most recent call last): File "/home/andre/.local/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event await coro(*args, **kwargs) File "/home/andre/repos/github/discord_project/bot.py", line 30, in on_member_join await member.creat_dm() AttributeError: 'Member' object has no attribute 'creat_dm' ``` Can anyone help me with this annoying bug? I've seen articles that show `member.create_dm()` being used
2020/08/14
[ "https://Stackoverflow.com/questions/63416534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13461081/" ]
You need to use "saturation math". For near white colors, your intermediate values (e.g. `sepiared`) can exceed 255. 255 (0xFF) is the maximum value that can fit in an `unsigned char` For example, if `sepiared` were 256 (0x100), when it gets put into `rgbtRed`, only the rightmost 8 bits will be retained and the value will be *truncated* to 0. So, instead of a very bright value [near white], you'll end up with a very dark value [near black]. To fix this, add: ``` if (sepiared > 255) sepiared = 255; ``` --- Also, note with the ordering of your `for` loops, it is very cache inefficient. And, it's wasteful [and can be slow] to use `image[i][j].whatever` everywhere. Better to use a pointer to the current pixel. Anyway, here's an updated version of your code with these changes: ``` void sepia(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE *pix; for (int i = 0; i < height; i++) { pix = &image[i][0]; for (int j = 0; j < width; j++, pix++) { int sepiared = pix->rgbtRed * .393 + pix->rgbtGreen * .769 + pix->rgbtBlue * .189; int sepiagreen = pix->rgbtRed * .349 + pix->rgbtGreen * .686 + pix->rgbtBlue * .168; int sepiablue = pix->rgbtRed * .272 + pix->rgbtGreen * .534 + pix->rgbtBlue * .131; if (sepiared > 255) sepiared = 255; if (sepiagreen > 255) sepiagreen = 255; if (sepiablue > 255) sepiablue = 255; pix->rgbtRed = sepiared; pix->rgbtGreen = sepiagreen; pix->rgbtBlue = sepiablue; } } } ``` --- Also, note that it can be a bit slow to use floating point math on pixel images. In this case, it's faster/better to use scaled integer math. Here's a version that does that: ``` void sepia(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE *pix; for (int i = 0; i < height; i++) { pix = &image[i][0]; for (int j = 0; j < width; j++, pix++) { int sepiared = pix->rgbtRed * 393 + pix->rgbtGreen * 769 + pix->rgbtBlue * 189; int sepiagreen = pix->rgbtRed * 349 + pix->rgbtGreen * 686 + pix->rgbtBlue * 168; int sepiablue = pix->rgbtRed * 272 + pix->rgbtGreen * 534 + pix->rgbtBlue * 131; sepiared /= 1000; sepiagreen /= 1000; sepiablue /= 1000; if (sepiared > 255) sepiared = 255; if (sepiagreen > 255) sepiagreen = 255; if (sepiablue > 255) sepiablue = 255; pix->rgbtRed = sepiared; pix->rgbtGreen = sepiagreen; pix->rgbtBlue = sepiablue; } } } ```
For me it worked when I kept all the variables outside the loop and rounded off in the end after checking the value of each R G B less than 255.
63,416,534
I've recently tried to create a simple bot in discord with Python Code. I'm testing just the first features to DM a user when he joins the server Here is my code: ``` import os import discord from dotenv import load_dotenv load_dotenv() #load .env files TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') client = discord.Client() @client.event async def on_ready(): guild = discord.utils.get(client.guilds, name=GUILD) print( f'{client.user} has connected to the following guild:\n' f'{guild.name}(id: {guild.id})' ) #debug members = '\n - '.join([member.name for member in guild.members]) print(f'Guild Members:\n - {members}') #debug @client.event async def on_member_join(member): await member.creat_dm() await member.dm_channel.send( f'Hi {member.name}, welcome to my Discord Server!' ) client.run(TOKEN) ``` ``` Ignoring exception in on_member_join Traceback (most recent call last): File "/home/andre/.local/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event await coro(*args, **kwargs) File "/home/andre/repos/github/discord_project/bot.py", line 30, in on_member_join await member.creat_dm() AttributeError: 'Member' object has no attribute 'creat_dm' ``` Can anyone help me with this annoying bug? I've seen articles that show `member.create_dm()` being used
2020/08/14
[ "https://Stackoverflow.com/questions/63416534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13461081/" ]
So You Need To Edit Your Code Sligitly Store Orginal Image To a temp for a while ``` originalBlue = image[i][j].rgbtBlue; originalRed = image[i][j].rgbtRed; originalGreen = image[i][j].rgbtGreen; ``` the result of each of these formulas may not be an integer so use float and round them to nearest integer ``` sepiaRed = round(.393 * originalRed + .769 * originalGreen + .189 * originalBlue); sepiaGreen = round(.349 * originalRed + .686 * originalGreen + .168 * originalBlue); sepiaBlue = round(.272 * originalRed + .534 * originalGreen + .131 * originalBlue); if (sepiaRed > 255) { sepiaRed = 255; } if (sepiaGreen > 255) { sepiaGreen = 255; } if (sepiaBlue > 255) { sepiaBlue = 255; } ``` now store the values to the orignal ones ``` image[i][j].rgbtBlue = sepiaBlue; image[i][j].rgbtRed = sepiaRed; image[i][j].rgbtGreen = sepiaGreen; ``` **Declare all Variable Outside For Loop** ``` float sepiaRed; float sepiaBlue; float sepiaGreen; int originalRed; int originalBlue; int originalGreen; ``` I Hope It's Help
For me it worked when I kept all the variables outside the loop and rounded off in the end after checking the value of each R G B less than 255.
63,416,534
I've recently tried to create a simple bot in discord with Python Code. I'm testing just the first features to DM a user when he joins the server Here is my code: ``` import os import discord from dotenv import load_dotenv load_dotenv() #load .env files TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') client = discord.Client() @client.event async def on_ready(): guild = discord.utils.get(client.guilds, name=GUILD) print( f'{client.user} has connected to the following guild:\n' f'{guild.name}(id: {guild.id})' ) #debug members = '\n - '.join([member.name for member in guild.members]) print(f'Guild Members:\n - {members}') #debug @client.event async def on_member_join(member): await member.creat_dm() await member.dm_channel.send( f'Hi {member.name}, welcome to my Discord Server!' ) client.run(TOKEN) ``` ``` Ignoring exception in on_member_join Traceback (most recent call last): File "/home/andre/.local/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event await coro(*args, **kwargs) File "/home/andre/repos/github/discord_project/bot.py", line 30, in on_member_join await member.creat_dm() AttributeError: 'Member' object has no attribute 'creat_dm' ``` Can anyone help me with this annoying bug? I've seen articles that show `member.create_dm()` being used
2020/08/14
[ "https://Stackoverflow.com/questions/63416534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13461081/" ]
First, as an aside, when you have a CS50 question, please search for the keywords in StackOverflow before asking. The answer is probably there. If you search for `sepia RGBTRIPLE cs50` you get quite a few hits. After doing a lot of pixel processing, you'll hone some useful debugging intuitions. Among those: * If you see diagonal offsets, your image's bytes-per-row may be greater than the width times the pixel size. (Especially in YCbCr images or on platforms where image buffers are aligned to 128-bit vector sizes.) * 2x or 0.5x image displays probably mean you're not heeding the scale value on a Retina display. * Certain colorspace errors will point you immediately to BGR vs RGB byte ordering issues. No blue channel at all or all blue? Probably mixing ARGB with BGRA. But more to the point: * If you see wackiness in the bright or color-saturated areas, your pixel component values are probably oversaturating (exceeding the maximum value, and dropping the high bit(s)). Every time you either (1) multiply a color component by a number great than 1 or (2) add multiple color components together, you need to think about what happens if you exceed the maximum value. If your intermediate math will add two values and then divide by 2, make sure your compiled operations will be using a large enough variable size to hold that extra bit. So in your inner loop here, when operating on a white pixel, almost every color component will exceed 255 (i.e. red and green will exceed, but not blue, because sepia is low in blue): ``` int sepiared = image[i][j].rgbtRed *.393 + image[i][j].rgbtGreen *.769 + image[i][j].rgbtBlue *.189; int sepiagreen = image[i][j].rgbtRed *.349 + image[i][j].rgbtGreen *.686 + image[i][j].rgbtBlue *.168; int sepiablue = image[i][j].rgbtRed *.272 + image[i][j].rgbtGreen *.534 + image[i][j].rgbtBlue *.131; ``` The resulting value would be {255, 255, 255} x {.393+.769+.189, .349+.686+.168, .272+.534+.131}, or {344.5, 306.8, 238.9}. But because you don't have that enough bits for those values in the BYTE components of an RGBTRIPLE struct, your values will be incorrect. So instead, you can do this: ``` int sepiared = (int) image[i][j].rgbtRed *.393 + image[i][j].rgbtGreen *.769 + image[i][j].rgbtBlue *.189; int sepiagreen = (int) image[i][j].rgbtRed *.349 + image[i][j].rgbtGreen *.686 + image[i][j].rgbtBlue *.168; int sepiablue = (int) image[i][j].rgbtRed *.272 + image[i][j].rgbtGreen *.534 + image[i][j].rgbtBlue *.131; sepiared = min(sepiared, 255); sepiagreen = min(sepiagreen, 255); sepiablue = min(sepiablue, 255); ``` Note that I have made two changes: 1. Cast the first value in each expression to (int); otherwise the calculation will be done on bytes and you'll lose your high bit. 2. Enforce the maximum value of 255 on each pixel component. When considering the other answers, please add my first fix. Checking for a max of 255 won't help if you've already dropped your high bit!
For me it worked when I kept all the variables outside the loop and rounded off in the end after checking the value of each R G B less than 255.
18,296,394
I've got a list of instances of a particular class Foo, that has a field bar: ``` foo[1..n].bar ``` I'd like to "convert" this to just a list of bar items, so that I have `bar[1..n]` Sorry for the 1..n notation - I'm just trying to indicate I have an arbitrarily long list. Be gentle - I'm new to python.
2013/08/18
[ "https://Stackoverflow.com/questions/18296394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8478/" ]
Use a list comprehension ``` bar = [ i.bar for i in foo ] ``` Also, list indices in python start from 0, so a list of N elements would have items from `0` to `n - 1`.
> > Be gentle - I'm new to python. > > > Okay. > > I've got a list of items: > > > > ``` > foo[1..n].bar > > ``` > > How in the heck is that a list? A list looks like this: ``` [1, 2, 3] ``` How does `foo[1..n].bar` fit that format? Like this? ``` foo[1, 2, 3].bar ``` That's nonsensical. > > I'd like to "convert" this to just a list of bar items, so that I have bar[1..n] > > > Once again your converted list has to have the format: ``` [obj1, obj2, obj3] ``` Now the question is what is the conversion factor that transforms your starting list: ``` [obj1, obj2, obj3 ] ``` into your transformed list: ``` [obj4, obj5, obj6] ``` ???? > > can you please put your actual list – Anshuman Dwibhashi no I > actually can't. They are not trivial objects > > > Well, then post an example with trivial objects. I sense that you know something about programming in some language, but that this is your first foray into a new language. The bottom line is: you have to learn the basic syntax in any language before you can speak intelligently about it. Get a beginning python book and start reading.
41,778,173
I have been using turtle package in python idle. Now I have switched to using Jupyter notebook. How can I make turtle inline instead of opening a separate graphic screen. I am totally clueless about. Any pointers and advice will be highly appreciated.
2017/01/21
[ "https://Stackoverflow.com/questions/41778173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3668042/" ]
I found the following library that has a Turtle implementation working in Jupyter notebooks: <https://github.com/takluyver/mobilechelonian>
It seems you can get turtle module to work, if you run the Jupyter Notebook cell containing the code twice. Not sure why it works, but it does!
41,778,173
I have been using turtle package in python idle. Now I have switched to using Jupyter notebook. How can I make turtle inline instead of opening a separate graphic screen. I am totally clueless about. Any pointers and advice will be highly appreciated.
2017/01/21
[ "https://Stackoverflow.com/questions/41778173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3668042/" ]
I am a windows user, so run the CMD as an administrator and run this: ``` jupyter nbextension enable --py --sys-prefix ipyturtle ``` Run the above after installing the ipyturtle ``` pip3 install ipyturtle ```
It seems you can get turtle module to work, if you run the Jupyter Notebook cell containing the code twice. Not sure why it works, but it does!
41,778,173
I have been using turtle package in python idle. Now I have switched to using Jupyter notebook. How can I make turtle inline instead of opening a separate graphic screen. I am totally clueless about. Any pointers and advice will be highly appreciated.
2017/01/21
[ "https://Stackoverflow.com/questions/41778173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3668042/" ]
With python3.6+: ``` python -m pip install ipyturtle3 ``` Try the examples listed in this repo: <https://github.com/williamnavaraj/ipyturtle3> <https://pypi.org/project/ipyturtle3/> I found this to work in JupyterLab and VSCode
It seems you can get turtle module to work, if you run the Jupyter Notebook cell containing the code twice. Not sure why it works, but it does!
41,778,173
I have been using turtle package in python idle. Now I have switched to using Jupyter notebook. How can I make turtle inline instead of opening a separate graphic screen. I am totally clueless about. Any pointers and advice will be highly appreciated.
2017/01/21
[ "https://Stackoverflow.com/questions/41778173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3668042/" ]
I found the following library that has a Turtle implementation working in Jupyter notebooks: <https://github.com/takluyver/mobilechelonian>
I am a windows user, so run the CMD as an administrator and run this: ``` jupyter nbextension enable --py --sys-prefix ipyturtle ``` Run the above after installing the ipyturtle ``` pip3 install ipyturtle ```
41,778,173
I have been using turtle package in python idle. Now I have switched to using Jupyter notebook. How can I make turtle inline instead of opening a separate graphic screen. I am totally clueless about. Any pointers and advice will be highly appreciated.
2017/01/21
[ "https://Stackoverflow.com/questions/41778173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3668042/" ]
With python3.6+: ``` python -m pip install ipyturtle3 ``` Try the examples listed in this repo: <https://github.com/williamnavaraj/ipyturtle3> <https://pypi.org/project/ipyturtle3/> I found this to work in JupyterLab and VSCode
I am a windows user, so run the CMD as an administrator and run this: ``` jupyter nbextension enable --py --sys-prefix ipyturtle ``` Run the above after installing the ipyturtle ``` pip3 install ipyturtle ```